auth

package
v0.29.2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package auth implements bearer-token authorization for the HTTP transport: the token store, the middleware that resolves a request to a principal with a Policy, and the per-KB RBAC check the tools are gated on (`kb:<name>:r` / `kb:<name>:rw` scopes are parsed into Policy permissions). Disabled by default; stdio is trusted and never passes through it.

Index

Constants

View Source
const PluginPrefix = "plugin:"

PluginPrefix starts the principal id of a token bound to a plugin ("plugin:<plugin>/<token id>"); no other token may carry an id with it.

View Source
const WellKnownProtectedResourcePath = "/.well-known/oauth-protected-resource"

WellKnownProtectedResourcePath is the RFC 9728 discovery path for OAuth Protected Resource Metadata. It is exempted from authentication here (by definition it must be public) and served by mcpserver.MultiKBServer.Handler using ProtectedResourceMetadata.

Variables

View Source
var (
	ErrIdentityUnavailable = errors.New("identity service unavailable")
	ErrIdentityDenied      = errors.New("identity denied")
)

The two failures an IdentityHook reports: the proxy's request is refused with 503 (the hook is down under fail_closed) or 403 (the hook denied the user).

Functions

func ContextWithPrincipal added in v0.4.0

func ContextWithPrincipal(ctx context.Context, principal Principal) context.Context

func ParseTrustedAddresses added in v0.29.0

func ParseTrustedAddresses(list []string) ([]netip.Prefix, error)

ParseTrustedAddresses reads CIDRs strictly: a /0 prefix (trust everyone) and anything that is not a prefix or an address is an error. A bare address is a host prefix. There is no implicit loopback trust.

func ProtectedResourceMetadata

func ProtectedResourceMetadata(issuer, resourceID string) []byte

ProtectedResourceMetadata returns JSON for /.well-known/oauth-protected-resource (RFC 9728).

Types

type Identity added in v0.29.0

type Identity struct {
	User   string
	Groups []string
	// Via is the id of the proxy token the request came in on.
	Via string
}

Identity is who a proxy says made the request.

type IdentityHook added in v0.29.0

type IdentityHook func(r *http.Request, via Principal, header Identity) (id Identity, supplied bool, err error)

IdentityHook may replace the identity the proxy header named. It runs only for a trusted peer on a proxy token whose header carries an identity (header, groups and all), after the default reader. supplied false: no opinion, or a failure the operator chose to ignore (fail_open), and header stays in force. The answer is only names: the group mapping and the clamp run on it as on any other identity, so it can never exceed the proxy token.

type IdentityResolver added in v0.29.0

type IdentityResolver func(r *http.Request, via Principal) (id Identity, found bool, err error)

IdentityResolver reads the identity of a request that arrived through a trusted proxy token. found false: the request carries none and stays the proxy token's own. An error is a malformed identity (answered 400). The header reader is the default; a plugin may supply another one, and the trust checks and the group mapping run in either case.

type KBScope

type KBScope struct {
	KB    string // KB name
	Write bool   // true = rw, false = r
}

KBScope represents per-KB access rights extracted from a token.

func ParseScopes

func ParseScopes(scope string) []KBScope

ParseScopes parses a scope string like "kb:docs:rw kb:notes:r" (or ";"-separated, e.g. "kb:docs:rw;kb:notes:r") into KBScope entries.

Malformed components are skipped. That is tolerable ONLY because every configuration path validates with ParseScopesStrict first (D179): on its own, silently dropping a component makes a typo indistinguishable from an absent restriction, and a token whose every restriction vanished used to be read as an unrestricted legacy admin.

func ParseScopesStrict added in v0.11.0

func ParseScopesStrict(scope string) ([]KBScope, error)

ParseScopesStrict parses scope and rejects anything ParseScopes would have discarded, naming the offending component. It never includes the whole input in the error: a scope field is a place credentials get pasted by mistake, and a startup error is a place they must not appear.

type Kind added in v0.29.0

type Kind string

Kind says what sort of caller a token stands for. The zero value is read as KindHuman, so every token written before kinds existed keeps its meaning.

const (
	KindHuman    Kind = "human"
	KindClient   Kind = "client"
	KindSurveyor Kind = "surveyor"
)

func ParseKind added in v0.29.0

func ParseKind(s string) (Kind, error)

ParseKind reads a configured kind strictly: an empty string is human, an unknown value is an error (a typo must not silently fall back to the widest kind).

func (Kind) NonHuman added in v0.29.0

func (k Kind) NonHuman() bool

NonHuman reports whether the kind is one of the machine kinds, whose tokens must be KB-scoped and expiring.

type Permission added in v0.4.0

type Permission struct {
	KB                string
	Write             bool
	Maps              []string
	Journals          []string
	Types             []string
	ReadOnlyArtifacts bool
	NoSecrets         bool
}

Permission is one immutable allow rule. Empty Maps, Journals and Types are wildcards; non-empty selectors are intersected. There are intentionally no deny rules: permissions are unioned, which keeps policy evaluation deterministic and order-independent.

ReadOnlyArtifacts is therefore a narrower allow, not a deny: a rule that carries it grants what it grants today except the artifact write tools (skills, agents, hooks every client of the KB syncs and executes). A second rule of the same token without it restores them, as the union of any two rules does. NoSecrets is the same shape for secrets: the rule grants what it grants except authority over the KB's secrets (the secret tools, service resolution, and concept fields that point at a secret).

type Policy added in v0.4.0

type Policy struct {
	Admin       bool
	Permissions []Permission
}

Policy is the complete, immutable policy assigned to a principal.

func Clamp added in v0.29.0

func Clamp(p, ceiling Policy) Policy

Clamp narrows p by a ceiling: a permission survives only on a KB where the ceiling has an unselected (whole-KB) rule of the mode it needs, so a ceiling scoped to maps, journals or types grants nothing here (ValidateAuth refuses such a proxy token; this is the defence in depth). It loses Write where the ceiling cannot write whole, and takes the ceiling's restrictions: artifacts it cannot write, secrets it cannot see (any mode) or cannot resolve (write). The proxy token is the ceiling, so a read-only SSO bearer yields read-only people and the person never holds an authority the token lacks.

func (Policy) Allows added in v0.4.0

func (p Policy) Allows(kbName, mapName, journalName, typeName string, write bool) bool

Allows reports whether a policy allows an operation on a resource. mapName and journalName are mutually exclusive resource descriptors; typeName may be empty for non-concept resources. rw implies r.

func (Policy) AllowsArtifactWrite added in v0.27.1

func (p Policy) AllowsArtifactWrite(kbName string) bool

AllowsArtifactWrite reports whether a policy may change a KB's artifacts (artifact_write, artifact_delete, artifact_move, skill_install): an unselected write rule that does not carry ReadOnlyArtifacts.

func (Policy) AllowsCollection added in v0.16.0

func (p Policy) AllowsCollection(kbName, mapName, journalName string, write bool) bool

AllowsCollection reports whether a policy reaches anything inside a map or journal. The type selector is not consulted: a collection has no type, and passing an empty one to Allows matched no rule that names types — so a role narrowed to a map *and* a type could see no collection at all, and the UI told it no KB was visible (D228). Concept-level checks still apply the type.

func (Policy) AllowsSecrets added in v0.29.0

func (p Policy) AllowsSecrets(kbName string) bool

AllowsSecrets reports whether a policy has authority over a KB's secrets (secret_resolve, secret_set, service_get with resolve_secrets): an unselected write rule that does not carry NoSecrets.

func (Policy) AllowsWholeKB added in v0.4.0

func (p Policy) AllowsWholeKB(kbName string, write bool) bool

AllowsWholeKB requires an unselected permission. It is used for operations which cannot safely be scoped to a partial collection.

func (Policy) HasKBAccess added in v0.4.0

func (p Policy) HasKBAccess(kbName string, write bool) bool

HasKBAccess reports whether any rule grants the requested mode on a KB, regardless of resource selectors. It gates protocol metadata only.

func (Policy) SecretsVisible added in v0.29.0

func (p Policy) SecretsVisible(kbName string) bool

SecretsVisible reports whether a policy may see a KB's secret files in the Atlas (names and pointers, no value): an unselected rule of any mode that does not carry NoSecrets.

func (Policy) WithholdsSecrets added in v0.29.0

func (p Policy) WithholdsSecrets(kbName string) bool

WithholdsSecrets reports whether a policy is restricted from the concept fields that point at a secret on a KB: it writes the KB through at least one rule that carries NoSecrets and has no unselected write rule without it (AllowsSecrets false). Fail-closed on mixed rules: a whole-KB NoSecrets rule is not undone by a scoped rule without the key, which restores the authority only inside its own selection. A token with no NoSecrets write rule is not restricted, as before the key existed.

type Principal added in v0.4.0

type Principal struct {
	ID     string
	Policy Policy
	// Kind is what the token stands for; the zero value is human.
	Kind Kind
	// Via is the id of the token behind an identity that is not the token's
	// own (a person named by a trusted proxy); empty when the ID is the token's.
	Via string
	// ProxyToken is set when the bearer token is a trusted-proxy token
	// (ScopedToken.Proxy), whether or not the request named a person: a proxy
	// that forwards anonymous traffic on its own token leaves Via empty. It
	// changes no authorization decision; it tells a caller that the TCP peer
	// may be the proxy and not the caller.
	ProxyToken bool
	// Groups are the groups a trusted proxy named for the person.
	Groups []string
	// Local marks the principal the server itself creates for a trusted local
	// caller (stdio, or HTTP with authentication off). A token store never sets
	// it, so no configured token, whatever its name or policy, can claim it.
	Local bool
}

Principal identifies the caller without retaining its bearer secret.

func LocalAdminPrincipal added in v0.4.0

func LocalAdminPrincipal() Principal

LocalAdminPrincipal is used for auth-disabled HTTP and trusted stdio. It is explicit so handlers never infer authority from a missing context value.

func PrincipalFromContext added in v0.4.0

func PrincipalFromContext(ctx context.Context) Principal

type ProxyConfig added in v0.29.0

type ProxyConfig struct {
	Trusted         []netip.Prefix
	UserHeader      string
	GroupsHeader    string
	GroupsSeparator string
	// GroupPolicies is the permission set each group maps to (the union of its
	// roles), before the clamp.
	GroupPolicies map[string]Policy
	// Resolver replaces the header reader when set.
	Resolver IdentityResolver
	// Hook is the operator's identity hook, nil when there is none.
	Hook IdentityHook
}

ProxyConfig is the compiled proxy_identity section.

type Recheck added in v0.29.0

type Recheck func() (Principal, bool)

Recheck answers, for a request that has outlived its authentication (an event stream), who the bearer is now: the principal in force in the current token generation, or false once the token is unknown, revoked or expired. A narrowed token comes back narrowed. Nil when the request was not authenticated by a token (auth off): there is nothing to revoke.

func RecheckFromContext added in v0.29.0

func RecheckFromContext(ctx context.Context) Recheck

RecheckFromContext returns the Recheck the middleware attached, or nil.

type ScopedToken

type ScopedToken struct {
	Token     string
	Scopes    []KBScope
	Principal string
	Policy    Policy
	// Kind is the token's kind (zero: human).
	Kind Kind
	// Via is carried onto the principal (see Principal.Via).
	Via string
	// ExpiresAt is the instant the token stops being valid; zero never expires.
	ExpiresAt time.Time
	// Proxy marks the bearer of a trusted SSO proxy: only such a token's
	// requests may carry an identity header (ProxyConfig).
	Proxy bool
	// Plugin binds the token to a plugin as its service identity: it never
	// has authority over secrets, and its legacy scopes never change artifacts
	// (a role rule says artifacts: rw to give them back, compiled by the
	// caller).
	Plugin string
}

ScopedToken pairs a plaintext bearer token with the KB scopes it grants.

type TokenStore

type TokenStore struct {
	// contains filtered or unexported fields
}

TokenStore manages valid bearer tokens stored as SHA-256 hashes, each mapped to the immutable policy it grants. Unrestricted access is declared by the caller (Policy.Admin), never inferred from an empty policy (D179).

func NewScopedTokenStore

func NewScopedTokenStore(tokens []ScopedToken) *TokenStore

NewScopedTokenStore creates a token store where each token carries its own policy: role-derived permissions, legacy per-KB scopes, or an explicit Policy.Admin. A token whose policy ends up empty grants NOTHING — see the comment inside. Entries with an empty token value are skipped; a caller that requires authentication must mark the store with RequireAuth so an empty result fails closed rather than disabling enforcement.

func NewTokenStore

func NewTokenStore(tokens []string) *TokenStore

NewTokenStore creates a token store from plain token strings, each granted full access. If tokens is nil or empty, auth is disabled.

Admin is set explicitly rather than inferred from an empty permission set (D179): a bare token string IS the declaration of an unrestricted token, and stating it here is what lets the store refuse to invent that intent for anyone else.

func (*TokenStore) IsEnabled

func (ts *TokenStore) IsEnabled() bool

IsEnabled returns true if authentication is enforced for requests.

A store built by RequireAuth enforces even when it holds no token, so that a configuration which asked for authentication and produced no usable credential fails closed instead of serving every request as a local admin (D179).

func (*TokenStore) Middleware

func (ts *TokenStore) Middleware(next http.Handler) http.Handler

Middleware returns an HTTP middleware that validates the Authorization: Bearer header. If auth is disabled, passes through as the local admin. On failure, returns 401 with WWW-Authenticate header. On success, injects the token's principal into the request context. A public path (isPublicPath) is never refused: it carries the principal of a valid bearer when there is one and no principal otherwise.

func (*TokenStore) PrincipalOf added in v0.4.0

func (ts *TokenStore) PrincipalOf(token string) (Principal, bool)

PrincipalOf returns the authenticated immutable principal.

func (*TokenStore) Replace added in v0.29.0

func (ts *TokenStore) Replace(tokens []ScopedToken) error

Replace swaps the tokens in force for a new set, on a running store: a reload of the configuration (tokens, roles) needs no restart. The set is compiled exactly as at construction. A store that enforces authentication (RequireAuth) refuses a set with no usable token and keeps the old one, the fail-closed rule of D179 applied to a reload: an emptied file must not turn into a locked-out or, worse, an open server. A request in flight finishes with the principal it resolved (principals are immutable copies).

func (*TokenStore) ReplaceAll added in v0.29.0

func (ts *TokenStore) ReplaceAll(tokens []ScopedToken, proxy *ProxyConfig) error

ReplaceAll is Replace with the proxy identity section, swapped in the same snapshot so a request never sees new tokens with the old mapping.

func (*TokenStore) RequireAuth added in v0.11.0

func (ts *TokenStore) RequireAuth() *TokenStore

RequireAuth marks the store as enforcing regardless of how many tokens it holds. serve calls it whenever auth resolved to "on", so the decision to enforce is carried explicitly instead of being re-derived from the token count — the two disagreed, because the count that gated the decision was of configured records while the store had already dropped the unusable ones.

func (*TokenStore) SetProxy added in v0.29.0

func (ts *TokenStore) SetProxy(proxy *ProxyConfig) *TokenStore

SetProxy installs the proxy identity section on a store being built, before it serves; a running store changes it through ReplaceAll.

func (*TokenStore) TokenCount added in v0.11.0

func (ts *TokenStore) TokenCount() int

TokenCount reports how many usable tokens the store holds — the count AFTER unusable entries were dropped, which is the number a caller must check against its own expectations rather than the number of configured records.

func (*TokenStore) Validate

func (ts *TokenStore) Validate(token string) (agentID string, ok bool)

Validate checks if the given token is valid. The returned ID is never derived from the plaintext token.

Jump to

Keyboard shortcuts

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