Documentation
¶
Overview ¶
Package authz is Agent GM's credential logic: what a scope is, how the admin bootstrap session of spec section 9.7 is minted and refreshed, how a presented token is authenticated, and every limiter that stands in front of those three (spec sections 9.6, 9.8, 12.1, 12.3).
Slice 2 mints exactly one kind of authorization -- the admin bootstrap -- but the shape is the OAuth one, because Slice 3 adds a second token SOURCE and not a second security model.
Two rules run through the whole package and are worth stating once:
- Every check of a caller-supplied value against a stored one is constant-time over fixed-length hashes, never `==` on strings and never bytes.Equal (spec section 12.1). See compare.go, which is the only file permitted to compare a secret-derived value, and comparison_audit_test.go, which enforces that by parsing this package's own source.
- Every timeout is measured on the injected clock (spec section 13.1). No function here calls time.Now, time.Sleep or time.After, and no test waits anything out.
Index ¶
- Constants
- Variables
- type AuditRecord
- type AuditWriter
- type Authorization
- type BucketSpec
- type CodeExchange
- type ConcurrencyLimiter
- type ConcurrencySpec
- type Config
- type Digest
- type DurableLimitSpec
- type DurableLimiter
- type MemorySettings
- type RateLimitedError
- type RecordingAudit
- type Scope
- type ScopeSet
- func (s ScopeSet) Clone() ScopeSet
- func (s ScopeSet) Empty() bool
- func (s ScopeSet) Equal(other ScopeSet) bool
- func (s ScopeSet) Has(sc Scope) bool
- func (s ScopeSet) Len() int
- func (s ScopeSet) List() []Scope
- func (s ScopeSet) String() string
- func (s ScopeSet) Strings() []string
- func (s ScopeSet) Subset(other ScopeSet) bool
- func (s ScopeSet) Widens(other ScopeSet) bool
- type Service
- func (s *Service) AllowRequest(auth *Authorization, spec BucketSpec) error
- func (s *Service) Audience() string
- func (s *Service) Authenticate(ctx context.Context, presentedAccessToken string) (*Authorization, error)
- func (s *Service) Authorizations(ctx context.Context, includeRevoked bool) ([]store.Authorization, error)
- func (s *Service) Clock() interface{ ... }
- func (s *Service) ExchangeAuthorizationCode(ctx context.Context, in CodeExchange) (*Session, error)
- func (s *Service) MintAdminSession(ctx context.Context, presentedSecret string, requestedScopes []string, ...) (*Session, error)
- func (s *Service) Refresh(ctx context.Context, presentedRefreshToken string, requestedScopes []string, ...) (*Session, error)
- func (s *Service) RefreshOAuth(ctx context.Context, presentedRefreshToken, clientID string, ...) (*Session, error)
- func (s *Service) RevokeAuthorization(ctx context.Context, id, reason, source string) error
- func (s *Service) RevokeSupersededAdminSessions(ctx context.Context) ([]string, error)
- func (s *Service) RevokeToken(ctx context.Context, presentedToken, clientID, source string) error
- func (s *Service) SettingDuration(ctx context.Context, key string) (time.Duration, error)
- func (s *Service) Store() *store.Store
- type Session
- type Settings
- type Source
- type SourceResolver
- type TokenBuckets
Constants ¶
const ( // AuditAdminSessionMinted carries source, granted scopes and whether the // mint was narrowed -- never the secret. AuditAdminSessionMinted = "auth.admin_session_minted" // AuditAdminSessionNarrowed is written when a refresh narrows the session. AuditAdminSessionNarrowed = "auth.admin_session_narrowed" // AuditAdminSessionRefreshed carries scopes before and after. AuditAdminSessionRefreshed = "auth.admin_session_refreshed" // AuditAdminSecretFailed carries source and the resulting cooldown state // -- never the presented value. AuditAdminSecretFailed = "auth.admin_secret_failed" // AuditRefreshTokenReuse is spec section 12.4's refresh-token reuse // detection. AuditRefreshTokenReuse = "auth.refresh_token_reuse_detected" // AuditRefreshTokenFailed records an unknown or invalid presented token at // POST /v1/auth/refresh, with the resulting durable cooldown state. AuditRefreshTokenFailed = "auth.refresh_token_failed" )
The audit kinds this package writes (spec section 12.4).
const ( AuditAuthorizationCreated = "authorization.created" AuditAuthorizationApproved = "authorization.approved" AuditAuthorizationDenied = "authorization.denied" AuditAuthorizationRevoked = "authorization.revoked" AuditEnrollmentCreated = "enrollment.created" AuditEnrollmentConsumed = "enrollment.consumed" AuditEnrollmentRevoked = "enrollment.revoked" AuditEnrollmentExpired = "enrollment.expired" AuditClientRevoked = "client.revoked" // AuditOAuthTokenIssued records one authorization-code exchange. AuditOAuthTokenIssued = "authorization.token_issued" // AuditOAuthTokenRefreshed records one rotation of an OAuth grant. AuditOAuthTokenRefreshed = "authorization.token_refreshed" // AuditOAuthTokenNarrowed records a refresh that narrowed the grant. AuditOAuthTokenNarrowed = "authorization.token_narrowed" // AuditOAuthTokenFailed records an unknown or invalid presented value at // /oauth/token or /oauth/revoke, with the resulting cooldown state and // nothing derived from what was presented. AuditOAuthTokenFailed = "authorization.token_failed" )
The audit kinds the OAuth half writes (spec section 12.4). They are the same strings `internal/audit` declares as typed constants; this package keeps them as plain strings so that the credential layer does not depend on the audit subsystem.
const ( SettingAdminAccessTokenTTL = "admin.access_token_ttl" SettingAdminRefreshTokenIdleTTL = "admin.refresh_token_idle_ttl" SettingAdminRefreshTokenAbsoluteTL = "admin.refresh_token_absolute_ttl" // The OAuth grant's own three, with the same defaults and the same // bounds. They are separate keys because an owner may want a connector's // session to outlive (or not outlive) their own admin session, and one // key for both would make that choice impossible to express. SettingOAuthAccessTokenTTL = "oauth.access_token_ttl" SettingOAuthRefreshTokenIdleTTL = "oauth.refresh_token_idle_ttl" SettingOAuthRefreshTokenAbsoluteTTL = "oauth.refresh_token_absolute_ttl" // The three lifetimes of the authorization flow itself (section 9.6). SettingOAuthAuthorizationCodeTTL = "oauth.authorization_code_ttl" SettingOAuthAuthorizationRequestTTL = "oauth.authorization_request_ttl" SettingOAuthEnrollmentDefaultTTL = "oauth.enrollment_default_ttl" )
The three TTL settings this package reads, with the defaults of spec section 15.1 and the bounds of section 9.6.
Admin sessions expire on the same schedule as OAuth ones. The credential that outranks everything else does not get a longer life than the ones it outranks (spec section 9.6).
const ( SourceModeSocketPeer = "socket_peer" SourceModeTrustedProxy = "trusted_proxy" )
Startup log values for client_source_mode (spec section 12.3).
const MinAdminSecretLength = 43
MinAdminSecretLength is spec section 12.1's floor: AGENT_GM_ADMIN_SECRET is at least 43 characters and the server refuses shorter. Forty-three base64url characters is 256 bits, which is the point.
const SourceUnknown = "unknown"
SourceUnknown is the source of a request whose TCP peer could not be parsed at all. It exists so that rule 6 -- the resolved source is never the empty string -- holds even for a malformed RemoteAddr, and so that such requests share one bucket rather than each getting their own.
Variables ¶
var ( // ErrInvalidScope is spec section 7.2 `invalid_request`-adjacent // `invalid_scope`: a requested scope set that widens, or names a scope // outside the four of section 9.7. ErrInvalidScope = errors.New("invalid_scope") // ErrTokenAbsent is `invalid_token` (401): no bearer was presented. ErrTokenAbsent = errors.New("invalid_token: absent") // ErrTokenUnknown is `invalid_token` (401): the presented value resolves // to no row. A token minted under a previous AGENT_GM_PUBLIC_URL lands // here, because the audience is inside the hash (spec sections 9.6, 15.6). ErrTokenUnknown = errors.New("invalid_token: unknown") // ErrTokenExpired is `invalid_token` (401), measured on the injected clock. ErrTokenExpired = errors.New("invalid_token: expired") // ErrTokenRevoked is `invalid_token` (401). ErrTokenRevoked = errors.New("invalid_token: revoked") // ErrTokenReused is `invalid_token` (401) and, uniquely, has a side // effect: presenting a spent refresh token revokes the whole family and // its authorization (spec section 9.6). ErrTokenReused = errors.New("invalid_token: refresh token reused") // ErrInvalidSecret is the wrong AGENT_GM_ADMIN_SECRET. It is deliberately // indistinguishable from ErrTokenUnknown at the HTTP surface. ErrInvalidSecret = errors.New("invalid_token: admin secret") // ErrInsufficientScope is `insufficient_scope` (403): a valid credential // on a route it does not cover. This is the exit-4 case of the section // 11.2 matrix. ErrInsufficientScope = errors.New("insufficient_scope") )
The typed refusals of this package. Each maps to exactly one spec section 7.2 error code, named in its comment, so the HTTP layer translates rather than decides.
var ( // BucketReads covers every read route and read tool. BucketReads = BucketSpec{Name: "reads", PerMinute: 300, Burst: 100} // BucketMutations covers send, start, mark read, reactions, uploads and // the two delete routes -- messages:write and messages:delete together, // one budget, not one each. BucketMutations = BucketSpec{Name: "mutations", PerMinute: 120, Burst: 30} // BucketAdmin covers /v1/admin/*. BucketAdmin = BucketSpec{Name: "admin", PerMinute: 120, Burst: 30} // BucketUnauthenticated covers POST /v1/auth/refresh, and in Slice 3 the // /oauth/token refresh grant and /oauth/revoke. It is keyed by SOURCE, // because the caller is by definition not yet authenticated (spec // section 9.8). BucketUnauthenticated = BucketSpec{Name: "unauthenticated", PerMinute: 60, Burst: 20} )
The buckets of spec section 12.3.
Note what is NOT a parameter anywhere below: an account. Holding several scopes does not multiply the allowance, and neither does holding several accounts -- the buckets are per authorization and per source, never per account (spec section 12.3, D29). One authorization sending to three accounts shares one 120/min mutation budget. That is deliberate: the limits protect the server and the phones from a runaway agent, and an agent is no less runaway for spreading itself across accounts.
var ( ConcurrencyUploads = ConcurrencySpec{Name: "uploads", PerAuthorization: 4, Global: 16} ConcurrencyDownloads = ConcurrencySpec{Name: "downloads", PerAuthorization: 8, Global: 32} )
The concurrency limits of spec section 12.3. Per authorization and global, never per account.
var ( // LimitAdminSecret is spec section 12.3's admin-secret failure row: 5 per // 15 minutes per source, 20 per 15 minutes globally, exponential // cooldown. POST /v1/auth/admin-session is budgeted more tightly than // anything else because a success there yields more than a success // anywhere else. LimitAdminSecret = DurableLimitSpec{ Kind: store.AttemptKindAdminSecret, Surface: "admin_secret", PerSource: 5, Global: 20, Window: 15 * time.Minute, BaseCooldown: time.Minute, MaxCooldown: 24 * time.Hour, } // LimitRefreshToken is spec section 9.8's durable half for // POST /v1/auth/refresh: 30 unknown or invalid presented tokens per 15 // minutes, cooldown doubling per further failure in the window, capping at // 24 hours. It has no global half; section 9.8 states only a per-source // figure, and inventing a global one would refuse honest callers on the // strength of a number the spec does not give. LimitRefreshToken = DurableLimitSpec{ Kind: store.AttemptKindRefresh, Surface: "refresh_token", PerSource: 30, Global: 0, Window: 15 * time.Minute, BaseCooldown: time.Minute, MaxCooldown: 24 * time.Hour, } )
The two durable limiters Slice 2 needs.
var ( // ErrInvalidGrant is RFC 6749 `invalid_grant`: an unknown, expired, // consumed or replayed authorization code, a refresh token that resolves // to nothing, or a credential from the other path (section 9.6). ErrInvalidGrant = errors.New("invalid_grant") // ErrGrantReplayed is `invalid_grant` with a side effect: presenting a // code that has already been exchanged revokes the tokens the first // exchange produced. ErrGrantReplayed = errors.New("invalid_grant: authorization code replayed") )
The typed OAuth refusals. Each maps to exactly one RFC 6749 `error` value at /oauth/token, named in its comment, so `internal/oauth` translates rather than decides.
var ( LimitEnrollmentSource = DurableLimitSpec{ Kind: store.AttemptKindEnrollmentSource, Surface: "enrollment_code", PerSource: 10, Global: 0, Window: 15 * time.Minute, BaseCooldown: time.Minute, MaxCooldown: 24 * time.Hour, } LimitEnrollmentContext = DurableLimitSpec{ Kind: store.AttemptKindEnrollmentContext, Surface: "enrollment_code", PerSource: 10, Global: 0, Window: 15 * time.Minute, BaseCooldown: time.Minute, MaxCooldown: 24 * time.Hour, } )
LimitEnrollmentSource and LimitEnrollmentContext are section 9.4's enrollment-code budget: **the eleventh failed attempt within 15 minutes is 429**, per source and per signed context alike.
PerSource is therefore 10, not 11. The limiter records a failure and then refuses the NEXT request that arrives while the cooldown is running, so a limit of 10 makes the tenth failure set the cooldown and the eleventh attempt the one that is refused -- which is what section 9.4 asks for. A limit of 11 would let the eleventh through and refuse the twelfth, and the difference is exactly one free guess.
var ErrRateLimited = errors.New("rate_limited")
ErrRateLimited is the sentinel every RateLimitedError matches.
var LimitOAuthToken = DurableLimitSpec{ Kind: store.AttemptKindOAuthToken, Surface: "oauth_token", PerSource: 30, Global: 0, Window: 15 * time.Minute, BaseCooldown: time.Minute, MaxCooldown: 24 * time.Hour, }
LimitOAuthToken is spec section 9.8's durable half for the /oauth/token refresh grant and for /oauth/revoke: 30 unknown or invalid presented tokens per 15 minutes per source, a cooldown that doubles per further failure in the window and caps at 24 hours. It is a SEPARATE bucket from LimitRefreshToken so that exhausting one endpoint does not lock an owner out of the other, which is the honest reading of section 9.8's "all three carry" -- three budgets of the same size, not one shared one.
Functions ¶
This section is empty.
Types ¶
type AuditRecord ¶
AuditRecord is one appended row, as a test sees it.
type AuditWriter ¶
type AuditWriter interface {
Append(ctx context.Context, kind string, fields map[string]any) error
}
AuditWriter is the minimal view of the audit log this package needs. The audit subsystem itself lives elsewhere; this package only ever appends, and only ever appends metadata.
A payload carries IDs, counts, codes and outcomes. It never carries a token, a secret, a message body or a phone number (spec section 12.4) -- and the tests of section 16 Slice 2 test 24 assert that for every row this package writes, by scanning the rendered payload for the presented value.
type Authorization ¶
type Authorization struct {
ID string
Kind string
Scopes ScopeSet
MintedScopes ScopeSet
Source string
ExpiresAt time.Time
}
Authorization is an authenticated caller, as the rest of the server sees it.
func (*Authorization) Require ¶
func (a *Authorization) Require(scope Scope) error
Require is the scope check every route makes. A valid credential on a route it does not cover is insufficient_scope (403), never invalid_token and never not_found -- this is the exit-4 case of the section 11.2 matrix.
type BucketSpec ¶
type BucketSpec struct {
// Name is the surface, and the prefix of every key in this bucket. Two
// surfaces never share a bucket, so exhausting reads does not refuse a
// mutation.
Name string
// PerMinute is the sustained refill rate.
PerMinute float64
// Burst is the bucket's capacity.
Burst float64
}
BucketSpec is one row of spec section 12.3's table.
type CodeExchange ¶
type CodeExchange struct {
// CodeHash is the stored form of the presented code. The value never
// reaches this package.
CodeHash string
ClientID string
Source string
// Verify is the caller's binding check: PKCE, the exact redirect URI, the
// client, and the resource. It runs AFTER the code is known to exist and
// to be unconsumed, and BEFORE the tokens are minted -- and a failure
// consumes the code, which is section 9.6's rule that a verifier cannot
// be guessed by retrying.
//
// It lives in `internal/oauth` because PKCE and redirect matching are
// protocol policy; it runs here because "and consumes the code" is only
// true if the consumption commits with the refusal.
Verify func(code store.AuthorizationCode) error
}
CodeExchange is one `grant_type=authorization_code` request, after `internal/oauth` has parsed it and before anything has been decided.
type ConcurrencyLimiter ¶
type ConcurrencyLimiter struct {
// contains filtered or unexported fields
}
ConcurrencyLimiter bounds simultaneous work.
func NewConcurrencyLimiter ¶
func NewConcurrencyLimiter(spec ConcurrencySpec) *ConcurrencyLimiter
NewConcurrencyLimiter builds a limiter for one spec.
func (*ConcurrencyLimiter) Acquire ¶
func (c *ConcurrencyLimiter) Acquire(key string) (func(), error)
Acquire takes one slot for the given authorization. On success it returns a release function that must be called exactly once; on refusal it returns a *RateLimitedError and a no-op release, so a caller that defers the release unconditionally is still correct.
Retry-After on a concurrency refusal is one second: the wait is bounded by somebody else finishing, which is not a duration this limiter can know, and a second is the smallest honest answer.
type ConcurrencySpec ¶
ConcurrencySpec is one concurrency row of spec section 12.3.
type Config ¶
type Config struct {
// AdminSecret is AGENT_GM_ADMIN_SECRET. It lives in the environment only
// and is never written to the database, a log or an audit payload.
AdminSecret string
// PublicURL is AGENT_GM_PUBLIC_URL. Access tokens are audience-bound to
// PublicURL + "/mcp" (spec section 9.6).
PublicURL string
// TrustedProxyCIDRs is AGENT_GM_TRUSTED_PROXY_CIDRS. An invalid value
// makes New fail, which is spec section 12.3's "refuses to start".
TrustedProxyCIDRs string
}
Config is what a Service needs from the environment.
type Digest ¶
Digest is a fixed-length SHA-256 hash. Every secret comparison in this package is between two of these.
type DurableLimitSpec ¶
type DurableLimitSpec struct {
// Kind is the `kind` half of oauth_attempts' primary key.
Kind string
// Surface names the bucket in a RateLimitedError.
Surface string
// PerSource is how many failures inside Window a single source may
// accumulate before a cooldown starts. The limiter trips ON reaching it,
// not after exceeding it: spec section 16 Slice 2 test 25 says thirty
// invalid presented tokens trips the cooldown, so the thirtieth is the one
// that does.
PerSource int
// Global is the same, summed across every source. Zero disables the
// global half.
Global int
// Window is the rolling window failures are counted in.
Window time.Duration
// BaseCooldown is the first cooldown; it doubles per further failure in
// the window and caps at MaxCooldown.
BaseCooldown time.Duration
MaxCooldown time.Duration
}
DurableLimitSpec is one credential-failure limiter.
type DurableLimiter ¶
type DurableLimiter struct {
// contains filtered or unexported fields
}
DurableLimiter is the `oauth_attempts`-backed limiter.
func NewDurableLimiter ¶
func NewDurableLimiter(st *store.Store, clk clock.Clock) *DurableLimiter
NewDurableLimiter builds one.
func (*DurableLimiter) Check ¶
func (l *DurableLimiter) Check(ctx context.Context, spec DurableLimitSpec, source string) error
Check reports whether a source is currently cooled down, READ-ONLY.
It runs on the read pool and opens no write transaction, which is spec section 9.8's rule: a caller presenting a value that belongs to nobody must not be able to take the single writer's lock and queue every other writer behind itself.
func (*DurableLimiter) RecordFailure ¶
func (l *DurableLimiter) RecordFailure(ctx context.Context, spec DurableLimitSpec, source string) (store.Attempt, error)
RecordFailure counts one credential failure against the source and, where the spec gives one, against the global budget. It returns the source's resulting row so the caller can audit the cooldown state (spec section 12.4 requires `auth.admin_secret_failed` to carry it).
A successful presentation deliberately does NOT clear the counter (spec section 9.8): there is no RecordSuccess.
type MemorySettings ¶
type MemorySettings struct {
// contains filtered or unexported fields
}
MemorySettings is the in-memory implementation, seeded with the defaults of spec section 15.1.
func NewMemorySettings ¶
func NewMemorySettings() *MemorySettings
NewMemorySettings returns the documented defaults: 15m, 30d, 90d.
func (*MemorySettings) Set ¶
func (m *MemorySettings) Set(key string, d time.Duration) error
Set overrides one setting, refusing a value outside spec section 9.6's bounds. Bounds are enforced here rather than at read time so a bad value is refused when it is written, not silently clamped when it is used.
type RateLimitedError ¶
type RateLimitedError struct {
// Surface names the bucket, for logs and metrics. It is the same string
// for a real token and for a guess.
Surface string
// RetryAfter is rounded up to whole seconds, the granularity the
// Retry-After header has.
RetryAfter time.Duration
}
RateLimitedError is spec section 7.2 `rate_limited` (429). It always carries RetryAfter, and it carries nothing else: a 429 must never distinguish a real token from a guess (spec section 9.8), so two RateLimitedError values raised for the same surface and the same wait are indistinguishable by construction, whatever provoked them.
func (*RateLimitedError) Error ¶
func (e *RateLimitedError) Error() string
func (*RateLimitedError) Is ¶
func (e *RateLimitedError) Is(target error) bool
Is makes errors.Is(err, ErrRateLimited) work.
type RecordingAudit ¶
type RecordingAudit struct {
// contains filtered or unexported fields
}
RecordingAudit is the in-memory AuditWriter used by tests.
func NewRecordingAudit ¶
func NewRecordingAudit() *RecordingAudit
NewRecordingAudit returns an empty recorder.
func (*RecordingAudit) JSON ¶
func (r *RecordingAudit) JSON() (string, error)
JSON renders every appended row as JSON, which is what the sentinel scan of spec section 12.2 greps.
func (*RecordingAudit) OfKind ¶
func (r *RecordingAudit) OfKind(kind string) []AuditRecord
OfKind returns every appended row of one kind.
func (*RecordingAudit) Records ¶
func (r *RecordingAudit) Records() []AuditRecord
Records returns every appended row, in order.
type Scope ¶
type Scope string
Scope is one entry of spec section 9.7's table.
const ( // ScopeMessagesRead grants every read route and read tool, whoami, logout // and download-ticket redemption. ScopeMessagesRead Scope = "messages:read" // ScopeMessagesWrite grants send, start, mark read, reactions, uploads, // get_operation and upload-ticket redemption. ScopeMessagesWrite Scope = "messages:write" // ScopeMessagesDelete grants delete_message and delete_conversation, and // nothing else. ScopeMessagesDelete Scope = "messages:delete" // ScopeAdmin grants /v1/admin/* and all pairing routes. It is issued only // by the admin bootstrap, is never enrollable, and is invalid_scope at // /oauth/authorize. The only way to hold it is the admin secret. ScopeAdmin Scope = "admin" )
func (Scope) Enrollable ¶
Enrollable reports whether a scope may ever be granted by enrollment or at /oauth/authorize. `admin` never is.
type ScopeSet ¶
type ScopeSet struct {
// contains filtered or unexported fields
}
ScopeSet is an unordered set of scopes with a canonical rendering.
func AdminBootstrapScopes ¶
func AdminBootstrapScopes() ScopeSet
AdminBootstrapScopes is what POST /v1/auth/admin-session mints when no narrowing is asked for: `admin` plus all three messaging scopes.
The owner presenting AGENT_GM_ADMIN_SECRET is by definition the person the whole service belongs to, and a credential that could administer the server but not read a message would be useless (spec section 9.7).
func NewScopeSet ¶
NewScopeSet builds a set. Duplicates collapse.
func ParseScopeString ¶
ParseScopeString parses a stored space-joined column.
func ParseScopes ¶
ParseScopes builds a set from caller-supplied strings, refusing any scope outside the four of spec section 9.7. An unknown scope is invalid_scope rather than silently dropped: a caller who asks for `messages:reed` should find out, not receive a session quietly missing a permission.
func (ScopeSet) List ¶
List renders the set in canonical order. Any scope outside the four (which ParseScopes refuses, so this can only come from NewScopeSet) sorts after them, alphabetically, so the rendering is still total.
func (ScopeSet) String ¶
String renders the set space-joined in canonical order, which is exactly how authorizations.scopes and authorizations.minted_scopes store it.
type Service ¶
type Service struct {
// BeforeRefreshTx is a FAULT SEAM, nil in production, and it is placed
// exactly where the window is rather than anywhere convenient.
//
// Between the read-only lookup of a presented refresh token and the
// transaction that rotates it there is a window in which another caller
// can spend the same token. The transaction re-reads the row and treats
// a spent one as reuse; nothing else does, and no concurrent test can
// reliably land inside a window this narrow -- a reviewer's plant
// removing the re-read survived the whole suite. This hook lets a test
// stand in that window on purpose, which is the same argument
// HandlerDeps.AfterErase makes for the erasure crash window.
BeforeRefreshTx func()
Sources *SourceResolver
Buckets *TokenBuckets
Durable *DurableLimiter
Uploads *ConcurrencyLimiter
Downloads *ConcurrencyLimiter
// contains filtered or unexported fields
}
Service is the credential logic.
func New ¶
func New(st *store.Store, clk clock.Clock, settings Settings, audit AuditWriter, cfg Config) (*Service, error)
New builds the Service, validating everything that should stop a start.
func (*Service) AllowRequest ¶
func (s *Service) AllowRequest(auth *Authorization, spec BucketSpec) error
AllowRequest applies the ordinary-traffic bucket for one route class.
There is deliberately no account parameter and no scope parameter: the buckets are per authorization, so holding several scopes does not multiply the allowance and neither does holding several accounts (spec section 12.3, section 16 Slice 2 tests 30 and 40). Adding a parameter here is how that invariant would be lost, so the signature is the guardrail.
func (*Service) Authenticate ¶
func (s *Service) Authenticate(ctx context.Context, presentedAccessToken string) (*Authorization, error)
Authenticate resolves a presented bearer to its authorization, or to a typed refusal: absent, unknown, expired or revoked.
Access tokens are audience-bound to <AGENT_GM_PUBLIC_URL>/mcp. The binding is inside the hash, so a token minted under a previous origin resolves to nothing and is refused as unknown (spec sections 9.6, 15.6).
func (*Service) Authorizations ¶
func (s *Service) Authorizations(ctx context.Context, includeRevoked bool) ([]store.Authorization, error)
Authorizations lists the grants an owner may revoke.
func (*Service) Clock ¶
Clock exposes the injected clock, so `internal/oauth` measures every timeout on the same one and no test waits anything out.
func (*Service) ExchangeAuthorizationCode ¶
ExchangeAuthorizationCode mints an OAuth grant from an authorization code (spec section 9.6).
The order below is the contract:
- the durable budget, before the presented value is examined at all;
- a READ-ONLY lookup, before any write transaction opens (section 9.8), so a caller presenting a value that belongs to nobody cannot take the single writer's lock;
- expiry and replay, replay being the one that revokes;
- the caller's Verify, whose failure consumes the code;
- the mint, the consumption and the audit row, in ONE transaction.
func (*Service) MintAdminSession ¶
func (s *Service) MintAdminSession(ctx context.Context, presentedSecret string, requestedScopes []string, source string) (*Session, error)
MintAdminSession is POST /v1/auth/admin-session (spec sections 9.7, 16 Slice 2 test 24).
It mints `admin messages:read messages:write messages:delete`, honouring an optional narrowing to a subset of those four. A widening beyond them is invalid_scope. The presented secret never reaches the database, a log or an audit payload.
func (*Service) Refresh ¶
func (s *Service) Refresh(ctx context.Context, presentedRefreshToken string, requestedScopes []string, source string) (*Session, error)
Refresh is POST /v1/auth/refresh (spec sections 9.6, 9.8, 16 Slice 2 tests 22 and 25).
Admin refresh tokens rotate on every use, and reuse of a spent one revokes the session. An admin refresh may never widen: `scopes` may only narrow, relative BOTH to the scopes the session was minted with and to the scopes it holds now. Widening -- including back to the full set after a narrowing -- is invalid_scope, does not spend the presented token, and leaves the session's scopes unchanged. Re-widening requires presenting AGENT_GM_ADMIN_SECRET again (spec section 9.6).
The two budgets of section 9.8 are checked before the presented token is examined at all, so a 429 never distinguishes a real token from a guess.
func (*Service) RefreshOAuth ¶
func (s *Service) RefreshOAuth(ctx context.Context, presentedRefreshToken, clientID string, requestedScopes []string, source string) (*Session, error)
RefreshOAuth is the `refresh_token` grant at POST /oauth/token.
It is the SAME implementation as the admin refresh, with the OAuth TTLs, the OAuth budget, the OAuth audit kinds, the client binding and -- the security-relevant difference -- a guard that the presented token belongs to an OAuth authorization. An admin refresh token here is `invalid_grant` and revokes nothing (section 9.6, section 16 Slice 3 test 13).
func (*Service) RevokeAuthorization ¶
RevokeAuthorization is the owner's revocation, from DELETE /v1/admin/authorizations/{id} and from `agm admin authorizations revoke`. Unlike RevokeToken it reports whether the authorization existed, because the caller here is the owner and there is nothing to hide from them.
func (*Service) RevokeSupersededAdminSessions ¶
RevokeSupersededAdminSessions revokes every admin bootstrap authorization minted by a different AGENT_GM_ADMIN_SECRET, and every token belonging to them. It runs at startup, before any listener binds.
This is spec section 12.1's "changing it revokes every previous admin bootstrap authorization on next start". It is a startup step rather than a check at authentication time so that the revocation is recorded once, in the audit log, instead of being re-decided on every request.
func (*Service) RevokeToken ¶
RevokeToken is POST /oauth/revoke (RFC 7009, spec section 9.6).
It ALWAYS returns nil. A token belonging to another client, or to nobody, is ignored without confirming that it exists -- so the caller cannot use this endpoint as an oracle. Revoking any token of a grant revokes the whole grant.
The two budgets still apply, and a rate-limited caller still gets a 429: section 9.8 makes the budget the one thing this endpoint may say no to, precisely because it never says anything else.
func (*Service) SettingDuration ¶
SettingDuration reads one duration setting through the same view this package uses, so the OAuth layer cannot end up reading a different settings source than the credential layer.
func (*Service) Store ¶
Store exposes the store to `internal/oauth`, which owns the protocol tables (clients, enrollment codes, authorization requests, authorization codes) while this package owns the credential ones. Sharing one Store rather than opening a second is what lets an approval and the token it eventually mints be read from the same database with the same single writer.
type Session ¶
type Session struct {
AuthorizationID string
AccessToken string
RefreshToken string
Scopes ScopeSet
MintedScopes ScopeSet
AccessTokenExpiresAt time.Time
RefreshTokenExpiresAt time.Time
// Narrowed reports whether this call narrowed the scope set: at a mint,
// relative to the full admin bootstrap grant; at a refresh, relative to
// the session's previous scopes.
Narrowed bool
}
Session is the result of a mint or a refresh. The two token values are returned here exactly once and are never stored; only their hashes reach the database.
type Settings ¶
type Settings interface {
// Duration returns the effective value of one duration setting. An
// unknown key is an error, never a zero duration: a TTL that silently
// became zero would expire every credential the instant it was minted.
Duration(ctx context.Context, key string) (time.Duration, error)
}
Settings is the minimal view of the runtime settings table this package needs (spec section 15.1). It is an interface, and a small one, so that `internal/settings` supplies it without this package depending on the shape of the settings subsystem, and so that a test can move a TTL without a database.
type Source ¶
type Source struct {
// Value is the source itself: an IP address, or SourceUnknown. Never
// empty.
Value string
// Mode is SourceModeSocketPeer or SourceModeTrustedProxy: which rule
// produced Value. GET /v1/health reports it, so a misconfiguration where
// every caller collapses to one source is visible.
Mode string
// ForwardedProto and ForwardedHost are recorded for diagnosis and NEVER
// used to build a URL.
ForwardedProto string
ForwardedHost string
}
Source is one resolved client source.
type SourceResolver ¶
type SourceResolver struct {
// contains filtered or unexported fields
}
SourceResolver resolves a request's client source. The zero value is not usable; construct it with NewSourceResolver.
func NewSourceResolver ¶
func NewSourceResolver(cidrList string) (*SourceResolver, error)
NewSourceResolver parses AGENT_GM_TRUSTED_PROXY_CIDRS.
The list is comma-separated. An entry may be a CIDR (`10.0.0.0/8`, `::1/128`) or a bare address, which is read as a host route. An invalid entry is an error, and the caller is expected to refuse to start on it.
func (*SourceResolver) Mode ¶
func (r *SourceResolver) Mode() string
Mode is the startup value of client_source_mode.
func (*SourceResolver) Resolve ¶
func (r *SourceResolver) Resolve(remoteAddr string, headers http.Header) Source
Resolve resolves the source of one request from its TCP peer (http.Request.RemoteAddr) and its headers.
func (*SourceResolver) Trusts ¶
func (r *SourceResolver) Trusts() bool
Trusts reports whether the resolver has any trusted proxies configured.
type TokenBuckets ¶
type TokenBuckets struct {
// contains filtered or unexported fields
}
TokenBuckets is the in-memory limiter for ordinary traffic.
func NewTokenBuckets ¶
func NewTokenBuckets(clk clock.Clock) *TokenBuckets
NewTokenBuckets builds an empty limiter on the injected clock.
func (*TokenBuckets) Allow ¶
func (b *TokenBuckets) Allow(spec BucketSpec, key string) error
Allow consumes one token from the bucket named by spec and key, returning nil if the request may proceed and a *RateLimitedError carrying Retry-After if it may not.
key is an authorization ID for the first three buckets and a client source for the fourth. It is never an account ID and never a scope.