auth

package
v0.73.0-rc.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package auth provides agent token authentication for MCPProxy.

It implements token generation, validation, HMAC-based hashing, and context propagation for distinguishing admin vs agent access. Agent tokens use the "mcp_agt_" prefix and are secured with HMAC-SHA256 hashing before storage.

Index

Constants

View Source
const (
	KindAgent  = "agent"
	KindClient = "client"
)

Kind values for AgentToken.Kind (data-model.md §3). The empty string is the legacy default and is always equivalent to KindAgent.

View Source
const (
	ProfileModeLocked     = "locked"
	ProfileModeSwitchable = "switchable"
)

ProfileMode values for a client credential's AgentToken.ProfileMode (data-model.md §3). Applies to Kind=client only; empty/not-applicable for every regular token.

View Source
const (
	PermRead        = "read"
	PermWrite       = "write"
	PermDestructive = "destructive"
)

Permission constants define the allowed permission tiers.

View Source
const (
	// DefaultTokenExpiry is the expiry applied when expires_in is omitted.
	DefaultTokenExpiry = 30 * 24 * time.Hour
	// MaxTokenExpiry caps every owned or operator token at 365 days.
	MaxTokenExpiry = 365 * 24 * time.Hour
)

Token expiry rule shared by core POST /api/v1/tokens and the server edition's POST /api/v1/user/tokens (Spec 107 FR-011).

View Source
const (
	AuthTypeAdmin     = "admin"      // API key admin (personal edition)
	AuthTypeAgent     = "agent"      // Agent token authentication
	AuthTypeUser      = "user"       // Regular OAuth-authenticated user (server edition)
	AuthTypeAdminUser = "admin_user" // OAuth-authenticated admin (server edition)
)

Auth type constants.

View Source
const (
	ServerOpAdd             = "add"
	ServerOpRemove          = "remove"
	ServerOpUpdate          = "update"
	ServerOpPatch           = "patch"
	ServerOpEnable          = "enable"
	ServerOpDisable         = "disable"
	ServerOpRestart         = "restart"
	ServerOpRefresh         = "refresh"
	ServerOpDiscoverTools   = "discover_tools"
	ServerOpQuarantine      = "quarantine"
	ServerOpUnquarantine    = "unquarantine"
	ServerOpAddFromRegistry = "add_from_registry"
	ServerOpLogin           = "login"
	ServerOpLogout          = "logout"
	ServerOpConfigToSecret  = "config_to_secret"
	ServerOpApproveTools    = "approve_tools"
	ServerOpBlockTools      = "block_tools"

	// REST-only mutating operations that reach server/security/config state
	// through routes OTHER than /api/v1/servers/{id}. They are denied to agents
	// so the /servers gate cannot be bypassed via a sibling endpoint
	// (config apply rewrites mcpServers; registry add creates a server; the
	// security scanner mutates a server's approval state).
	ServerOpConfigWrite     = "config_write"
	ServerOpScan            = "scan"
	ServerOpSecurityApprove = "security_approve"
	ServerOpSecurityReject  = "security_reject"
	ServerOpSecretWrite     = "secret_write"
	ServerOpDiagnosticsFix  = "diagnostics_fix"
	// ServerOpBundleManage covers the Spec 101 TPA bundle mutations (roll back,
	// unpin, reload). A rollback is the one operator override of the downgrade
	// watermark, so it is an admin-only decision.
	ServerOpBundleManage = "bundle_manage"
)

Server-mutating operation identifiers.

These name the write operations on upstream MCP servers that are exposed on BOTH the MCP `upstream_servers` / `quarantine_security` tools and the REST `/api/v1/servers/...` surface. They are the single source of truth for which operations agent tokens (non-admin) may NOT perform, so the two surfaces can never drift apart again (issues #877/#878).

The string values for the operations that also exist on the MCP `upstream_servers` tool intentionally match that tool's operation names (see internal/server/mcp.go: operationAdd/operationRemove and the literal "update"/"patch"/"enable"/"disable"/"restart"/"refresh"/"add_from_registry" dispatch), so the MCP denylist can consume this policy without changing its observable behavior. REST-only operations (quarantine, login, …) use their own identifiers; the MCP surface never passes those strings here, so listing them is a no-op for MCP and closes the REST gap.

View Source
const ClientTokenPrefixStr = "mcp_cli_"

ClientTokenPrefixStr is the secret prefix for a per-client credential (Spec 108-c, FR-021). Same length and HMAC-SHA256 scheme as a regular agent token, so the kind is carried by the secret itself: a pre-108 binary, which only recognises TokenPrefixStr, never treats a client credential as a wildcard agent token (rollback safety, research D27).

View Source
const LeaseThreshold = 24 * time.Hour

LeaseThreshold is the longest lifetime at issue that is presented as a task lease rather than a long-lived credential (Spec 115 Definitions).

View Source
const MaxClientDisplayName = 64

MaxClientDisplayName bounds AgentToken.DisplayName (characters).

View Source
const MaxCredentialPurpose = 500

MaxCredentialPurpose bounds AgentToken.Purpose (characters, Spec 115 A10).

View Source
const MaxRateLimitPerMinute = 100000

MaxRateLimitPerMinute bounds TokenRateLimit.PerMinute and Burst. It is far above any sane agent budget; it only keeps the arithmetic and a typo ("600000000") from silently meaning "unlimited".

View Source
const MaxTokens = 100

MaxTokens is the maximum number of stored agent tokens allowed deployment-wide.

View Source
const MaxTokensPerOwner = 25

MaxTokensPerOwner caps how many stored agent tokens a single owner may hold in the server edition. Without an owner cap, any authenticated tenant can consume the entire deployment-wide pool and prevent every other tenant, including an administrator, from minting a token (issue #1177).

Ownerless personal-edition tokens are exempt so their established MaxTokens limit remains unchanged. Twenty-five preserves room for at least four fully provisioned owners inside the existing deployment cap.

View Source
const TokenPrefixStr = "mcp_agt_"

Token prefix used for all agent tokens.

Variables

This section is empty.

Functions

func AgentDeniedServerOp added in v0.52.0

func AgentDeniedServerOp(op string) bool

AgentDeniedServerOp reports whether the named operation is forbidden to agent tokens (non-admin auth contexts). It is case-sensitive: callers pass the canonical ServerOp* identifiers, never user-controlled free text.

func AuthorizeServerOp added in v0.52.0

func AuthorizeServerOp(ac *AuthContext, op string) bool

AuthorizeServerOp is the shared gate both surfaces use. It returns true when the caller is permitted to perform op. An admin context (API key or OS-authenticated socket) is always allowed. A nil context means the request arrived without an AuthContext — the auth middleware only leaves it nil in test/no-config passthrough scenarios that never occur once a real *config.Config is loaded, so it is treated as allowed here (the middleware, not this policy, is responsible for rejecting unauthenticated production requests). Any present non-admin context (agent token) is denied when op is on the denylist.

func CanEnumerateServer added in v0.64.0

func CanEnumerateServer(ctx context.Context, name string) bool

CanEnumerateServer is THE shared predicate for "may this caller SEE that a server named `name` exists?" (issue #1166).

The MCP door has filtered upstream enumeration through AuthContext.CanAccessServer since Spec 028; the REST doors never did, so a token scoped to `allowed_servers: ["alpha"]` still enumerated every configured server on GET /api/v1/servers, /api/v1/config, /api/v1/tools, /api/v1/status and the /events stream. Reads on both surfaces now answer from one place.

Fails OPEN on absence, deliberately and in exact mirror of AuthorizeServerOp: apiKeyAuthMiddleware forwards a request with NO AuthContext whenever the controller has no usable config (the testing / bootstrap passthrough), and treating that as "sees nothing" would blank the server list for every such caller. Absence of a token must not be stricter than a scoped token — it must be treated exactly as today's unrestricted behaviour. The unauthenticated /mcp back-compat context (AnonymousContext) is admin-typed and likewise unrestricted here; hiding a server's NAME from it is not the boundary this predicate defends, revealing its CREDENTIALS is, and that is what RevealSecretsAllowed refuses it.

func ClientTokenName added in v0.70.0

func ClientTokenName(clientID string) string

ClientTokenName is the FR-021 token name for a client credential.

func ConstantTimeEqual added in v0.69.0

func ConstantTimeEqual(candidate, secret string) bool

ConstantTimeEqual reports whether candidate equals secret, in time that does not depend on how many leading bytes they share.

Go's `==` on strings returns at the first differing byte, so using it to check a presented credential against a configured one leaks a prefix of the secret to a caller who can measure response time. Every comparison that decides access should go through this helper instead.

An empty candidate or secret is never a match. This matters: subtle's ConstantTimeCompare returns 1 for two empty slices, so a bare swap of `token == cfg.APIKey` for subtle.ConstantTimeCompare would make an absent credential authenticate as admin wherever the caller's `!= ""` guard was dropped. Folding the emptiness check in here means call sites cannot make that mistake.

The length of the two values is still compared in variable time (a length mismatch returns immediately). That is the standard subtle.ConstantTimeCompare contract: credential length is not the secret, its contents are.

func GenerateClientToken added in v0.70.0

func GenerateClientToken() (string, error)

GenerateClientToken creates a new client credential secret with the mcp_cli_ prefix followed by 64 hex characters (32 random bytes) — same length and shape as GenerateToken, so hashing and prefix extraction are unchanged; only the prefix differs (FR-021).

func GenerateToken

func GenerateToken() (string, error)

GenerateToken creates a new agent token with the mcp_agt_ prefix followed by 64 hex characters (32 random bytes). Total length: 72 chars.

func GetOrCreateHMACKey

func GetOrCreateHMACKey(dataDir string) ([]byte, error)

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 HashToken

func HashToken(token string, key []byte) string

HashToken computes HMAC-SHA256 of the token using the given key and returns the hex-encoded digest.

func IsAdminOrAbsent added in v0.70.0

func IsAdminOrAbsent(ac *AuthContext) bool

IsAdminOrAbsent keeps the historical admin-shaped management view for an unconfined anonymous MCP request while allowing ScopedView to narrow a confined anonymous request first.

func IsNonAdmin added in v0.70.0

func IsNonAdmin(ac *AuthContext) bool

IsNonAdmin is the nil-safe counterpart used by handlers after ScopedView.

func IsScopedCaller added in v0.64.0

func IsScopedCaller(ctx context.Context) bool

IsScopedCaller reports whether ctx carries a non-admin identity whose visibility is limited by AllowedServers. It is the cheap short-circuit for handlers that would otherwise copy a payload just to filter it: an admin (or an absent context, per CanEnumerateServer) sees everything, so the payload can be forwarded untouched.

func ParseTokenExpiry added in v0.68.0

func ParseTokenExpiry(expiresIn string, now time.Time) (time.Time, error)

ParseTokenExpiry is THE expiry rule for an agent token (Spec 107 FR-011, contracts/entitlement-predicate.md §5): positive, at most 365 days, fixed error text. Accepted formats: "30d" (days), "720h" (hours), or any Go duration string; "" means the 30-day default. Both minting doors call it, so neither can drift to an unbounded lifetime again (the server-edition door used to parse with a bare time.ParseDuration and no cap).

func RevealSecretsAllowed added in v0.64.0

func RevealSecretsAllowed(ctx context.Context, flagEnabled bool) bool

RevealSecretsAllowed is THE shared predicate for "may this caller be handed raw credential values?" (issues #1148 and #1167).

Both halves are required and neither is sufficient:

  • flagEnabled — the operator's `reveal_secret_headers` opt-in, and
  • CanRevealSecrets() — an authenticated, non-anonymous admin identity.

#1167: the MCP door already ANDed the two; the REST list, the whole-config read, both doctor doors and the per-server diagnostics door checked the flag ALONE, so a read-only agent token scoped to one server received every other server's Authorization header, URL query credential, argv secret and env secret in plaintext the moment an operator turned the flag on. Every request-scoped door now reads the answer from here so they cannot drift apart again.

Fails CLOSED on absence: a nil ctx (an in-process or future background caller) and a ctx with no AuthContext both yield false. A payload with no caller has no identity to check, so it gets masked values.

func TokenPrefix

func TokenPrefix(token string) string

TokenPrefix returns the first 12 characters of the token for display purposes.

func ValidClientID added in v0.70.0

func ValidClientID(id string) bool

ValidClientID reports whether id matches the FR-021 client_id pattern.

func ValidateAnyTokenFormat added in v0.70.0

func ValidateAnyTokenFormat(token string) (kind string, ok bool)

ValidateAnyTokenFormat checks a raw secret against BOTH recognised prefixes (mcp_agt_ and mcp_cli_, FR-021/FR-023) and reports which kind the secret CLAIMS to be, so the caller (storage.ValidateAgentToken) can check that claim against the stored record's own Kind (ValidateTokenInvariants) rather than trusting the record alone. ok is false for any other shape, including a correctly-shaped but foreign prefix.

func ValidatePermissions

func ValidatePermissions(perms []string) error

ValidatePermissions checks that the given permissions list is valid. It must contain "read" and only contain valid permission values.

func ValidateTokenFormat

func ValidateTokenFormat(token string) bool

ValidateTokenFormat checks that a token has the correct format: mcp_agt_ prefix followed by exactly 64 hex characters (72 chars total).

func ValidateTokenInvariants added in v0.70.0

func ValidateTokenInvariants(t *AgentToken, claimedKind string) error

ValidateTokenInvariants is THE fail-closed check for FR-021: every AgentToken record must satisfy these invariants before it may authenticate a request, checked IDENTICALLY at mint time (self-consistent: claimedKind == normalizeKind(t.Kind)) and on every authentication (storage.ValidateAgentToken, claimedKind derived from the presented secret's prefix via ValidateAnyTokenFormat). Any violation returns the exact FR-021 refusal text "malformed credential record" — never a downgrade to a regular wildcard agent token.

func WithAuthContext

func WithAuthContext(ctx context.Context, ac *AuthContext) context.Context

WithAuthContext returns a new context with the given AuthContext attached.

Types

type AgentToken

type AgentToken struct {
	Name           string     `json:"name"`
	TokenHash      string     `json:"token_hash"`
	TokenPrefix    string     `json:"token_prefix"` // first 12 chars of the raw token
	AllowedServers []string   `json:"allowed_servers"`
	Permissions    []string   `json:"permissions"`
	ExpiresAt      time.Time  `json:"expires_at"`
	CreatedAt      time.Time  `json:"created_at"`
	LastUsedAt     *time.Time `json:"last_used_at,omitempty"`
	Revoked        bool       `json:"revoked"`
	UserID         string     `json:"user_id,omitempty"`     // Owner user ID (server edition)
	ProfilePin     string     `json:"profile_pin,omitempty"` // Profile this token is pinned to (Profiles v2 T3)
	// PriorProfilePin/PriorProfileMode snapshot the binding of the revoked or
	// expired record a fresh client mint replaced. An aborted or undone connect
	// restores them onto the tombstone so it does not keep the binding of a
	// connect that never took effect. PriorProfileMode is the presence marker.
	PriorProfilePin  string `json:"prior_profile_pin,omitempty"`
	PriorProfileMode string `json:"prior_profile_mode,omitempty"`

	// Kind, ClientID and ProfileMode are the Spec 108-c client-credential
	// fields (data-model.md §3). Kind is ""/"agent" for a regular token,
	// "client" for a per-client credential; any other value is invalid
	// (fail closed at authentication, FR-021). ClientID and ProfileMode are
	// set iff Kind=client.
	Kind        string `json:"kind,omitempty"`
	ClientID    string `json:"client_id,omitempty"`
	ProfileMode string `json:"profile_mode,omitempty"`

	// DisplayName is the human name of a CUSTOM client (one not in the connect
	// registry), shown on the Clients page (Spec 108-f, FR-021). It is set
	// only for Kind=client and is at most MaxClientDisplayName characters.
	// Additive and omitempty: a binary that predates it ignores the field.
	DisplayName string `json:"display_name,omitempty"`

	// PendingHash/PendingPrefix/RotationStartedAt track an in-progress
	// staged rotation (FR-021a, Kind=client only): both the old secret's
	// hash (the record's own TokenHash) and PendingHash authenticate while
	// a rotation is staged, until finalize promotes PendingHash and clears
	// these fields.
	PendingHash       string     `json:"pending_hash,omitempty"`
	PendingPrefix     string     `json:"pending_prefix,omitempty"`
	RotationStartedAt *time.Time `json:"rotation_started_at,omitempty"`

	// ConnectedAt is when connect/add minted this credential.
	ConnectedAt *time.Time `json:"connected_at,omitempty"`

	// OwnerEmail, OwnerProvider and OwnerRole are the owner's identity as of
	// THIS authentication (Spec 107 FR-004/FR-013, data-model.md §3). They are
	// NEVER persisted (`json:"-"` keeps them out of the BBolt record, which is
	// json.Marshal'ed): storage.ValidateAgentToken stamps them on the token
	// value it returns from the single owner resolution, and AuthContext()
	// copies them into the request context. A token read back from the store
	// by any other path carries them empty. Role is derived live from
	// admin_emails, so it can change between two authentications of the same
	// token — which is exactly why it must not be stored.
	OwnerEmail    string `json:"-"`
	OwnerProvider string `json:"-"`
	OwnerRole     string `json:"-"`

	// RevokedAt, Issuer, Purpose and GuardBound are the Spec 115 lifecycle
	// fields (data-model.md §1). All are additive and omitempty: a binary
	// that predates them ignores them, and none participates in
	// ValidateTokenInvariants except GuardBound's own shape rule.
	//
	// RevokedAt is stamped (UTC) the first time Revoked flips to true and is
	// never overwritten. Legacy revoked records carry none.
	RevokedAt *time.Time `json:"revoked_at,omitempty"`
	// Issuer records who issued the credential through the credentials
	// service. Absent on pre-115 records and on connect-minted clients.
	Issuer *CredentialIssuer `json:"issuer,omitempty"`
	// Purpose is the stated, UNENFORCED task brief an issuer recorded, at
	// most MaxCredentialPurpose characters. Display-only.
	Purpose string `json:"purpose,omitempty"`
	// GuardBound marks an agent token minted through the MCP credentials
	// path: its ProfilePin counts as a standing FR-008a binding in every later
	// guard evaluation (Spec 115 FR-012a). Never set on client records or on
	// REST/CLI tokens; immutable after mint.
	GuardBound bool `json:"guard_bound,omitempty"`

	// RateLimit is this token's own call budget (issue #1699). Nil means the
	// token has none of its own and inherits agent_token_rate_limit from the
	// config; a non-nil value replaces that default for this token, and a
	// PerMinute of 0 opts the token out of it. Additive and omitempty: a binary
	// that predates it ignores the field.
	RateLimit *TokenRateLimit `json:"rate_limit,omitempty"`
}

AgentToken represents a stored agent token record.

func (*AgentToken) AuthContext added in v0.58.0

func (t *AgentToken) AuthContext() *AuthContext

AuthContext builds the request AuthContext for a validated agent token. It is the single constructor for the agent tier so no auth path can silently drop a field: the REST path used to omit ProfilePin, which meant a profile-pinned token evaluated (and, with Spec 098, preflighted) against the unpinned server set. Returns nil for a nil token.

Spec 107 (T076): it also copies the non-persisted OwnerEmail/OwnerProvider/ OwnerRole that storage stamped on the validated token value into Email/Provider/Role, so an owned token's request carries its owner's live identity without a second store read. CredentialKind is always agent_token.

func (*AgentToken) IsExpired

func (t *AgentToken) IsExpired() bool

IsExpired returns true if the token has passed its expiry time.

func (*AgentToken) IsLease added in v0.71.0

func (t *AgentToken) IsLease() bool

IsLease reports whether the credential's lifetime at issue is at most LeaseThreshold. A record without an expiry is never a lease.

func (*AgentToken) IsRevoked

func (t *AgentToken) IsRevoked() bool

IsRevoked returns true if the token has been revoked.

type AuthContext

type AuthContext struct {
	Type           string   // "admin", "agent", "user", or "admin_user"
	AgentName      string   // Name of the agent token (empty for admin)
	TokenPrefix    string   // First 12 chars of raw token (empty for admin)
	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
	// (AgentToken.AuthContext). TokenKind is "" for every non-agent-token
	// AuthContext (admin, user, anonymous); for an agent-token context it is
	// KindAgent or KindClient. ClientID and ProfileMode are set iff
	// TokenKind == KindClient.
	TokenKind   string
	ClientID    string
	ProfileMode string

	// RateLimit is the calling agent token's own call budget (issue #1699),
	// copied from AgentToken at authentication. Nil for every other context
	// and for a token with none of its own; the managed-client admission seam
	// then falls back to the agent_token_rate_limit default.
	RateLimit *TokenRateLimit

	// Multi-user OAuth fields (server edition). Empty for non-user auth types.
	UserID      string // User's unique ULID identifier
	Email       string // User's email from OAuth provider
	DisplayName string // User's display name
	Role        string // "admin" or "user" (empty for API key / agent token auth)
	Provider    string // OAuth provider used (e.g., "google", "github")

	// Anonymous marks a context that was NOT authenticated and only carries
	// admin type for backward compatibility (issue #1148).
	//
	// /mcp is deliberately unprotected by default (require_mcp_auth=false) so
	// MCP clients that cannot send an API key keep working, and the middleware
	// therefore hands an unauthenticated request an admin context. That is
	// fine for the operations those clients need — and it is NOT an identity,
	// so it must not satisfy a check that hands back raw credentials. See
	// CanRevealSecrets.
	Anonymous bool

	// CredentialKind is the FR-001 source that authenticated this request
	// (Spec 107). Stamped by apiKeyAuthMiddleware, mcpAuthMiddleware and the
	// server-edition middleware; empty for contexts built in-process.
	CredentialKind CredentialKind
}

AuthContext carries authentication identity through request context.

func AdminContext

func AdminContext() *AuthContext

AdminContext returns an AuthContext representing full admin access (API key auth).

func AdminUserContext added in v0.21.0

func AdminUserContext(userID, email, displayName, provider string) *AuthContext

AdminUserContext returns an AuthContext for an OAuth-authenticated admin user.

func AnonymousContext added in v0.64.0

func AnonymousContext() *AuthContext

AnonymousContext returns the back-compat admin context for an UNAUTHENTICATED MCP request (issue #1148).

Type stays AuthTypeAdmin on purpose: every existing IsAdmin()-based allowance — ordinary tool calls, retrieve_tools, server add/update/patch, quarantine approvals — behaves exactly as it did, so no MCP client that works today stops working. The only thing the Anonymous bit changes is CanRevealSecrets.

func AuthContextFromContext

func AuthContextFromContext(ctx context.Context) *AuthContext

AuthContextFromContext extracts the AuthContext from the context. Returns nil if no AuthContext is present.

func ScopedView added in v0.70.0

func ScopedView(ac *AuthContext, confinedAnonymous bool) *AuthContext

ScopedView returns the request's existing authorization identity unless it is an anonymous MCP caller confined by a named profile. Such callers retain the historical admin-shaped AnonymousContext everywhere else; management handlers use this non-admin view so their operation gates match a client credential without granting secret-reveal or administrator behavior.

func UserContext added in v0.21.0

func UserContext(userID, email, displayName, provider string) *AuthContext

UserContext returns an AuthContext for a regular OAuth-authenticated user.

func (*AuthContext) BoundToPinReach added in v0.73.0

func (ac *AuthContext) BoundToPinReach(reach []string) *AuthContext

BoundToPinReach returns a copy of ac whose AllowedServers is the caller's VISIBLE SET under Spec 118 (issue #1686): the token's grant intersected with `reach`, the effective server set of the profile the token is pinned to.

The operator-set pin is a visibility boundary on every surface, not an ergonomic filter: a token minted with `--profile p` takes its grant from the profile, so its stored AllowedServers is normally "*" and, read alone, let the token enumerate the whole fleet on every REST door that the MCP resolver (which applies the pin as its first tier) already narrowed. Folding the intersection into AllowedServers at authentication time means every consumer of the grant — CanEnumerateServer, CanAccessServer, the grant-as-filter seams that hand storage an allow-list, the usage cache key — answers from one resolved set, so no door and no derived count can disagree.

Fails CLOSED (FR-002): a nil or empty reach — the pinned profile was deleted, emptied, names only unconfigured servers, or no longer overlaps the grant — yields an EMPTY, NON-NIL slice, which every downstream filter reads as "allowed nothing" (nil would read as unrestricted). The result is then indistinguishable from a token whose grant is [].

Administrators, callers with no pin and a nil receiver are returned as-is: the pin can only narrow, never widen, and it never applies to them. The receiver is never edited in place — the validated token value it was built from may be shared.

The caller resolves `reach` from the LIVE configuration on every request and every SSE frame (FR-003); nothing here is cached.

func (*AuthContext) CanAccessServer

func (ac *AuthContext) CanAccessServer(name string) bool

CanAccessServer checks whether this context is allowed to access the named server. Admin contexts have unrestricted access. Agent contexts check their AllowedServers list, where "*" is treated as a wildcard granting access to all servers.

func (*AuthContext) CanRevealSecrets added in v0.64.0

func (ac *AuthContext) CanRevealSecrets() bool

CanRevealSecrets reports whether this caller may be handed RAW credential values (issue #1148) — today, `upstream_servers list` under the opt-in `reveal_secret_headers` flag.

It is deliberately stricter than IsAdmin and deliberately nil-safe:

  • an unauthenticated /mcp caller is admin for back-compat but has proved no identity, so it gets masked values like everyone else;
  • a nil context (the stdio transport before it installs one, an in-process caller, a test) is unprivileged rather than admin-by-absence — the opposite of the `authCtx != nil && !authCtx.IsAdmin()` shape, which lets the ABSENCE of a token pass a gate that a scoped token fails.

Authenticated admins — the API key, a tray/socket connection, stdio, an OAuth admin user in the server edition — are unaffected.

func (*AuthContext) GetUserID added in v0.21.0

func (ac *AuthContext) GetUserID() string

GetUserID returns the user's unique identifier, or empty string for non-user auth.

func (*AuthContext) HasPermission

func (ac *AuthContext) HasPermission(perm string) bool

HasPermission checks whether this context includes the given permission. Admin contexts have all permissions. Agent contexts check their Permissions list.

func (*AuthContext) IsAdmin

func (ac *AuthContext) IsAdmin() bool

IsAdmin returns true if this is an admin authentication context. Both API key admins ("admin") and OAuth-authenticated admins ("admin_user") are considered admin.

func (*AuthContext) IsAuthenticated added in v0.21.0

func (ac *AuthContext) IsAuthenticated() bool

IsAuthenticated returns true if this context has any authentication type set.

func (*AuthContext) IsClientCredential added in v0.70.0

func (ac *AuthContext) IsClientCredential() bool

IsClientCredential reports whether this context authenticated with a Spec 108-c client credential (kind=client, secret prefix mcp_cli_). Nil-safe.

func (*AuthContext) IsSessionPrincipal added in v0.68.0

func (ac *AuthContext) IsSessionPrincipal() bool

IsSessionPrincipal reports whether this context was installed by a session credential — the mcpproxy_session cookie or a user JWT (Spec 107 FR-002 "session principal"). Nil-safe. Session principals never satisfy CanRevealSecrets, and only the cookie kind may reach a minting door (FR-011: a derived credential never mints another credential).

func (*AuthContext) IsUser added in v0.21.0

func (ac *AuthContext) IsUser() bool

IsUser returns true if this is an OAuth-authenticated user context. Both regular users ("user") and admin users ("admin_user") are considered users.

type CredentialIssuer added in v0.71.0

type CredentialIssuer struct {
	ActorKind string `json:"actor_kind"`
	ActorName string `json:"actor_name,omitempty"`
	Surface   string `json:"surface"`
}

CredentialIssuer records who issued a credential, using the Actor fields of the profile_change record that announced it (Spec 115 data-model §1).

type CredentialKind added in v0.68.0

type CredentialKind string

CredentialKind records WHICH credential source authenticated a request (Spec 107 FR-001 precedence, data-model.md §4). It lives in this package — not httpapi — because httpapi imports auth, so an AuthContext field of an httpapi type would be an import cycle. It drives the session-cookie-only minting doors (FR-011), `caller.kind` on the audit line (FR-013) and CanRevealSecrets (FR-002). Empty means "not recorded" (a context built by an in-process caller or a test), which every consumer treats as the least privileged reading for its own decision.

const (
	CredentialKindSocket     CredentialKind = "socket"      // tray Unix socket / Windows named pipe
	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
	CredentialKindCookie     CredentialKind = "cookie"      // the mcpproxy_session cookie
	CredentialKindAnonymous  CredentialKind = "anonymous"   // no credential (require_mcp_auth: false back-compat)
)

The credential kinds an AuthContext can carry.

type TokenRateLimit added in v0.72.0

type TokenRateLimit struct {
	PerMinute int `json:"per_minute"`
	Burst     int `json:"burst,omitempty"`
}

TokenRateLimit is a per-token call budget: PerMinute calls a minute on average, with room for Burst calls at once. It is a token bucket that refills continuously, so a caller that has used its burst regains one call every 60/PerMinute seconds. PerMinute 0 means no limit. Burst 0 means "as many as PerMinute".

func (*TokenRateLimit) Validate added in v0.72.0

func (r *TokenRateLimit) Validate() error

Validate checks a rate limit supplied by a caller. A nil limit is valid.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL