Documentation
¶
Overview ¶
Package auth defines the per-caller identity primitive used by the multi-session attach layer. See docs/multi-session-design.md for the full design.
The package is intentionally substrate-only: it defines Caller, Authenticator, the authorization matrix, and the static user table loader. Wiring into the attach server, per-session sub-gates, and audit-log threading are layered on in later phases (see issue #162).
Backward compatibility: when no Authenticator is configured, callers should default to AnonymousAuth — every request resolves to the same "anon" identity and the multi-session features behave as if disabled.
Index ¶
- Constants
- Variables
- func Authorize(c Caller, a Action, acl SessionACL) bool
- func HashToken(token string) string
- func ProxyByFromContext(ctx context.Context) (by string, ok bool)
- func WithCaller(ctx context.Context, c Caller) context.Context
- func WithProxyBy(ctx context.Context, by string) context.Context
- type Action
- type AnonymousAuth
- type Authenticator
- type AuthenticatorWithProxy
- type BearerTokenAuth
- type Caller
- type SessionACL
- type User
- type UsersFile
Constants ¶
const HeaderAssertedCaller = "X-Asserted-Caller"
HeaderAssertedCaller is the conventional header name a proxy Caller uses to assert the effective identity. The actual header name is operator-configurable (attach.multi_session.asserted_caller_header) but this constant is the default.
const UsersFileSchemaVersion = 1
UsersFileSchemaVersion is the schema version this loader understands. Bump when the on-disk shape changes in a way that breaks older loaders; LoadUsersFile rejects unknown versions so operators don't silently lose new fields.
token_sha256 did not bump it: the field is additive, and a loader that predates it refuses a row carrying it as an unknown field, which is the fail-closed answer a downgrade needs.
Variables ¶
var Anonymous = Caller{Identity: "anon"}
Anonymous is the conventional Caller for unauthenticated requests when AnonymousAuth is in effect. Callers of AnonymousAuth may override the identity via configuration (attach.multi_session.default_identity) but "anon" is the documented default.
var ErrAssertedCallerForbidden = errors.New("auth: caller is not permitted to assert identities")
ErrAssertedCallerForbidden is returned when a non-proxy Caller attempts to use the X-Asserted-Caller header. Callers map this to a 401 response and should log the attempt — it indicates either misconfiguration or a credential that should not be assertable.
var ErrAssertedCallerUnknown = errors.New("auth: asserted identity is not provisioned")
ErrAssertedCallerUnknown is returned when a proxy Caller asserts an identity that is not present in the configured user table. Callers map this to a 401 response.
var ErrUnauthenticated = errors.New("auth: unauthenticated")
ErrUnauthenticated is returned by Authenticator.Authenticate when no valid credential is present on the request. Callers map this to a 401 response.
Functions ¶
func Authorize ¶
func Authorize(c Caller, a Action, acl SessionACL) bool
Authorize reports whether c may perform a against the given session ACL. The matrix follows docs/multi-session-design.md §"Authorization rules":
| Action | Admin | Owner | Viewers | Contributors | |-----------------|-------|-------|---------|--------------| | SessionList | ✓ | ✓ | ✓ | ✓ | | SessionRead | ✓ | ✓ | ✓ | ✓ | | SessionWrite | ✓ | ✓ | | ✓ | | SessionAdmin | ✓ | ✓ | | | | DaemonAdmin | ✓ | | | |
SessionList is always permitted at the API layer; handlers filter results per-Caller (hiding the existence of unauthorized sessions prevents leaking activity patterns).
func HashToken ¶
HashToken returns the value a users.json row stores in token_sha256 for token: the lowercase hex encoding of its SHA-256.
An unkeyed fast hash is the right tool here and a password hash (bcrypt, argon2) is not. Bearer tokens are minted random — 256 bits from `openssl rand -hex 32` — so there is no dictionary to slow down and a preimage search is the whole attack; a deliberately slow hash would only add its cost to every authenticated request. A key would have to live where the daemon can read it, which is where the agent can read it too. See docs/hashed-bearer-tokens-design.md.
func ProxyByFromContext ¶
ProxyByFromContext returns the proxying identity previously stored on ctx by WithProxyBy. ok is false (and the string empty) when the request did not go through the proxy path.
func WithCaller ¶
WithCaller returns a new context carrying c. Use in middleware that has resolved the request's Caller; downstream code reads it via CallerFromContext.
func WithProxyBy ¶
WithProxyBy returns a new context carrying the proxying identity alongside the effective Caller. Set when the request was routed via the proxy path (X-Asserted-Caller header) so audit logs can capture BOTH the effective Caller and the credential that asserted it (e.g., effective="alice@", proxy_by="sa:slack-bot").
Pair with WithCaller (which carries the effective identity); downstream code reads via ProxyByFromContext.
Types ¶
type Action ¶
type Action int
Action enumerates the authorization decisions the multi-session attach layer makes. The matrix is intentionally small in α.1; finer scoping (per-tool, per-MCP-server, per-session-sub-area) is deferred per docs/multi-session-design.md §"Out of scope".
Handlers don't enforce these in α.1 — enforcement wiring is α.2. The function is here so the type surface is settled before the handlers wrap on top.
const ( // ActionSessionList is the GET /sessions endpoint. Always // permitted; the handler filters results to sessions the Caller // can actually read. ActionSessionList Action = iota // ActionSessionRead covers reading session state — events // stream, status, tools, memory, permissions, etc. ActionSessionRead // ActionSessionWrite covers mutating endpoints — inject, // wake, interrupt, slash commands. ActionSessionWrite // ActionSessionAdmin covers ACL / metadata mutations on the // session — modifying SessionACL, deleting the session. ActionSessionAdmin // ActionDaemonAdmin covers daemon-scoped read/write — peer // registry, global metrics, anything not bound to a single // session. Admin-only. ActionDaemonAdmin )
type AnonymousAuth ¶
type AnonymousAuth struct {
Caller Caller
}
AnonymousAuth resolves every request to the same Caller. It is the default Authenticator wired into pkg/attach when multi-session is disabled — every request is "anon" (or whatever default identity the operator configured) and downstream code sees a Caller-on-context just like in multi-session deployments.
Zero value resolves to the package-level Anonymous Caller. Set Caller explicitly to override the identity (the operator-facing knob is attach.multi_session.default_identity).
func (AnonymousAuth) Authenticate ¶
func (a AnonymousAuth) Authenticate(_ *http.Request) (Caller, error)
Authenticate ignores the request and returns the configured Caller. Never returns an error.
type Authenticator ¶
Authenticator extracts a Caller from an inbound HTTP request, or returns ErrUnauthenticated when no valid credential is present.
Implementations shipped in α.1:
- AnonymousAuth — single fixed Caller; the default for single-user deployments and any deployment with multi-session disabled.
- BearerTokenAuth — token → Caller lookup against a static table loaded from users.json (see LoadUsersFile).
Future implementations (designed but not in α.1): OIDC/JWT, mTLS (subject DN → Caller), K8s ServiceAccount (TokenReview).
type AuthenticatorWithProxy ¶
type AuthenticatorWithProxy interface {
Authenticator
CanProxyAs(c Caller) bool
}
AuthenticatorWithProxy is the optional extension implemented by authenticators that support the proxy pattern (a Caller authorized to assert other Callers via the X-Asserted-Caller header).
The bot integration use case: a Slack/GChat bot authenticates as itself, then asserts the human user's identity per request so audit logs and per-caller MCP credentials attribute to the human, not the bot. CanProxyAs reports whether the resolved Caller is on the configured proxy allowlist.
Authenticators that don't implement this interface implicitly deny all proxy assertions.
type BearerTokenAuth ¶
type BearerTokenAuth struct {
// contains filtered or unexported fields
}
BearerTokenAuth validates the request's bearer token against a static table loaded from users.json. Returns the matched Caller, or ErrUnauthenticated when no token is presented or the token is unknown.
Comparison is of SHA-256 digests, constant-time (subtle.ConstantTimeCompare) to avoid leaking match prefixes through response timing; see Authenticate. Identities are not exposed by the lookup path.
Accepted headers, in order:
- X-Attach-Token (matches the existing daemon-level side-channel header used when an identity gateway owns Authorization)
- Authorization: Bearer <token>
Proxy semantics: a Caller resolved here is permitted to assert other identities via X-Asserted-Caller only if it appears in the ProxyIdentities allowlist. See CanProxyAs.
The authenticator holds digests, never tokens (#1213). Every row — a token_sha256 row, or a legacy plaintext row hashed here at construction — is reduced to the SHA-256 of its token, and a request is matched by hashing the presented token and comparing digests. One comparison path serves both row shapes, so a plaintext row can't authenticate anything its hashed form wouldn't.
func NewBearerTokenAuth ¶
func NewBearerTokenAuth(users []User, adminIdentities, proxyIdentities []string) *BearerTokenAuth
NewBearerTokenAuth builds an authenticator from a parsed user table (typically the result of LoadUsersFile). adminIdentities marks the listed identities as Admin Callers; proxyIdentities marks them as permitted to use X-Asserted-Caller.
Rows without an identity, or without exactly one usable credential (a plaintext token, or a well-formed token_sha256), are skipped — a misconfigured row shouldn't authenticate every credential-less request. Duplicates are last-write-wins; the loader rejects them upstream but the authenticator is defensive.
func (*BearerTokenAuth) Authenticate ¶
func (b *BearerTokenAuth) Authenticate(r *http.Request) (Caller, error)
Authenticate resolves the request's bearer token against the table. Returns ErrUnauthenticated when no token is presented or the token is not in the table.
The presented token is hashed and its digest compared against every row with subtle.ConstantTimeCompare, with no early exit: the time taken depends on the table size, which the operator controls and is not secret, and not on which row matched or how much of a digest agreed.
func (*BearerTokenAuth) CanProxyAs ¶
func (b *BearerTokenAuth) CanProxyAs(c Caller) bool
CanProxyAs reports whether c is on the operator-configured proxy allowlist. Returns false for callers not in the allowlist and for the zero-value Caller (defense against accidental authorization).
func (*BearerTokenAuth) HasIdentity ¶
func (b *BearerTokenAuth) HasIdentity(identity string) bool
HasIdentity reports whether the named identity exists in the user table. Used by the proxy path: a bot can only assert identities the operator has provisioned (see ErrAssertedCallerUnknown).
func (*BearerTokenAuth) LookupIdentity ¶
func (b *BearerTokenAuth) LookupIdentity(identity string) (Caller, bool)
LookupIdentity returns the Caller registered for the given identity, or zero-Caller + false when the identity is not in the table. Used by the proxy path to materialize the asserted Caller (preserving Labels and Admin flag from the user table entry).
type Caller ¶
Caller is the opaque identity attached to every authenticated request entering the daemon. Subsequent code uses it for authorization (see Authorize) and audit (see eventlog metadata, layered in α.2).
Identity is a stable opaque ID — typically an email ("alice@example.com"), a service-account marker ("sa:platform-agent"), or "anon" for unauthenticated requests when anonymous access is allowed.
Labels carry free-form metadata from the auth source (e.g., {"team": "platform", "issuer": "https://oidc.example.com"}). Available to authorization logic and audit consumers; not part of the Identity equality check.
Admin grants the see-everything role; set per configuration (attach.multi_session.admin_identities). Admin Callers pass every Authorize check.
type SessionACL ¶
SessionACL captures who can do what to a session. Owner is the creator (full access). Viewers can read; Contributors can read + write but not modify the ACL itself.
Owner may be a synthetic identity like "channel:#incident-response" for shared-session deployments where the session belongs to a group rather than a single user.
Zero value (empty Owner, nil slices) grants nothing to any non-Admin Caller — this is the safe default when a session was created before multi-session was enabled (legacy sessions become admin-only-accessible until the operator assigns an Owner).
func (SessionACL) Normalized ¶
func (a SessionACL) Normalized() SessionACL
Normalized returns a copy of the ACL with the identity lists cleaned up: each entry space-trimmed, empties dropped, duplicates removed (first occurrence wins, so the caller's order survives), and the slices freshly allocated so the result shares no backing array with the receiver.
Applied wherever an ACL crosses a trust boundary — the registry's register/amend entrypoints, and through them the HTTP surface that feeds them. The cleanup is not cosmetic: containsIdentity matches exactly, so a trailing space on a pasted identity produces an ACL that reads correct and denies anyway, and a denial here surfaces as 404 rather than 403 (deliberately — see Authorize), which is the hardest possible shape to debug from the client side. Dropping empties matters more: an ACL is compared against Caller.Identity, and while Authorize refuses an empty identity outright, a "" in a list is still a rule that can never match and would sit in the persisted row looking like a grant.
Owner is left exactly as supplied. It is one value rather than a list, its caller-facing errors are direct, and it may legitimately be a synthetic identity whose spelling is the operator's business.
Nil-preserving: a nil list normalizes to nil rather than an empty slice, so a round-trip through the store's JSON encoding doesn't flip between `null` and `[]`.
type User ¶
type User struct {
Identity string `json:"identity"`
Token string `json:"token,omitempty"`
TokenSHA256 string `json:"token_sha256,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
}
User is one row in users.json. Identity is the stable opaque ID the daemon stamps onto audit log entries. Labels are free-form metadata available to downstream authorization / observability.
The credential is one of two fields, never both:
- TokenSHA256 (`token_sha256`) is the hex SHA-256 of the bearer token clients present (see HashToken). The file then holds nothing a request can authenticate with: reading the table, as an agent whose bash reaches it can, yields only digests (#1213).
- Token (`token`) is the legacy plaintext form. It still loads, and the daemon warns at startup naming every identity still stored this way (see UsersFile.PlaintextIdentities).
A row missing Identity, or carrying neither or both credential fields, is rejected at load time (silently skipping it would hide misconfiguration from the operator).
type UsersFile ¶
UsersFile is the on-disk shape of attach.multi_session.auth.table_file. Operators populate this directly today; an OIDC / IDP-backed loader is layered in later (see docs/multi-session-design.md §"Migration story").
func LoadUsersFile ¶
LoadUsersFile reads + validates a users.json file from disk.
Validation:
- File mode must be 0600 on POSIX, or 0640 when the owning group is one this process belongs to — the shape a Kubernetes Secret volume with fsGroup produces. Every other group or other bit is a configuration error, not a tolerable laxity. See validateUsersFileMode for the argument. Skipped on Windows where Unix mode bits don't map cleanly.
- Schema version must match UsersFileSchemaVersion.
- Every row must carry an identity and exactly one of token_sha256 or token; a token_sha256 must be 64 hex characters.
- Credentials must be unique across rows, compared as digests, so a plaintext row and a hashed row for the same token collide too (duplicate tokens would produce nondeterministic identity resolution).
- Identity values must be unique across rows.
No error quotes a credential value, plaintext or digest: a value in the wrong field may be a plaintext token, and errors reach logs.
func (*UsersFile) PlaintextIdentities ¶
PlaintextIdentities returns, in file order, the identities whose row still stores its bearer token in plaintext. The daemon warns about them at startup; an empty result means reading the file yields nothing that authenticates.