Documentation
¶
Overview ¶
Package authserver is steward's OAuth 2.1 authorization server (Path B): a service mounts it at an issuer URL in front of Google sign-in, so MCP clients that expect to discover an authorization server and register with it (Claude Code, gemini-cli, IDEs) can sign people in, and the service then acts as each person with their own Google access token.
Clients register as pre-registered (static) clients, by Dynamic Client Registration (RFC 7591) or by a Client ID Metadata Document, then run the authorization code flow with PKCE (S256 only) and a resource indicator (RFC 8707) naming the protected resource. The user signs in with Google; the allow-list is checked; a Custody backend holds the user's Google grant (the Agent Identity credential vault, or the Google refresh token sealed inside steward's own refresh token). The client gets steward's own tokens, bound to the resource, with the user's Google access token sealed inside the access token. Pre-registered confidential clients may instead use the client-credentials grant, for workloads with no user.
Everything handed out is sealed (package seal), so nothing is stored and any replica holding the keyring verifies any token. The one piece of state is a ReplayCache that spends authorization codes and tracks refresh-token families; the default is in memory, per replica.
The protected resource verifies access tokens with Server.Verify, or with the purser authenticator from Server.Authenticator; an httpauth.Protector with Options.AuthServer does that, beside Google's own tokens (Path A), and hands the handler the person's Google token. Nothing here imports the MCP SDK.
Taken from gke-demos/kode-gopher internal/oauth at 8b53617b7d4d0b08b158de64ab7416dc84a1281e (docs/design-in-cluster.md section 3), generalized: service-defined scopes instead of one fixed scope, a configurable resource and Google scopes, an optional service account for client-credentials clients, steward's allow.Admitter, a pluggable replay cache and key provider, and slog. kode-gopher will not import steward; port fixes by hand in both directions.
Index ¶
- Constants
- Variables
- func SSRFSafeClient(timeout time.Duration) *http.Client
- func WorkloadSubject(clientID string) string
- type Authenticator
- type Config
- type Custody
- type GoogleClient
- type GraceReplayCache
- type MemoryReplayCache
- func (c *MemoryReplayCache) Claim(_ context.Context, id string, exp time.Time) (bool, error)
- func (c *MemoryReplayCache) Release(_ context.Context, id string) error
- func (c *MemoryReplayCache) Rotate(_ context.Context, fam string, gen uint64, exp time.Time) (bool, error)
- func (c *MemoryReplayCache) RotateGrace(_ context.Context, fam string, gen uint64, exp, graceUntil time.Time) (RotateResult, error)
- func (c *MemoryReplayCache) RotateWithID(_ context.Context, fam string, gen uint64, exp, graceUntil time.Time, ...) (RotateResult, error)
- func (c *MemoryReplayCache) Unrotate(_ context.Context, fam string, gen uint64) error
- func (c *MemoryReplayCache) UnrotateWithID(_ context.Context, fam string, gen uint64, rotation string) error
- type Principal
- type ReplayCache
- type RotateResult
- type RotationIDReplayCache
- type SealedCustody
- type Server
- func (s *Server) Authenticator() *Authenticator
- func (s *Server) CallbackURL() string
- func (s *Server) ContinueURL() string
- func (s *Server) DefaultScopes() []string
- func (s *Server) Handler() http.Handler
- func (s *Server) Issuer() string
- func (s *Server) MetadataURL() string
- func (s *Server) Paths() []string
- func (s *Server) Register(mux *http.ServeMux)
- func (s *Server) Resource() string
- func (s *Server) Scopes() []string
- func (s *Server) Verify(ctx context.Context, token string) (Principal, error)
- type ServiceTokens
- type StaticClient
- type User
- type VaultCustody
Constants ¶
const ( ScopeOpenID = "openid" ScopeEmail = "https://www.googleapis.com/auth/userinfo.email" ScopeCloudPlatform = "https://www.googleapis.com/auth/cloud-platform" )
Google's canonical scope names. The vault stores grants under these exact spellings ("email" does not match), so they are used everywhere.
const ( GoogleAuthURL = "https://accounts.google.com/o/oauth2/v2/auth" GoogleTokenURL = "https://oauth2.googleapis.com/token" //nolint:gosec // G101: an endpoint, not a credential GoogleTokenInfoURL = "https://oauth2.googleapis.com/tokeninfo" //nolint:gosec // G101: an endpoint, not a credential )
Google's endpoints.
const ( // AuthRequestTTL bounds a sign-in, from the authorization request to // Google's callback (and the vault's consent leg). AuthRequestTTL = 10 * time.Minute // CodeTTL is an authorization code's life. CodeTTL = time.Minute // AccessTTL is an access token's longest life; it is shorter when the // Google token inside it expires sooner. AccessTTL = 15 * time.Minute // RefreshTTL is a refresh token's life, renewed by every refresh. RefreshTTL = 30 * 24 * time.Hour )
Lifetimes.
const ( PathAuthorize = "/authorize" PathCallback = "/callback" PathConsentContinue = "/consent/continue" PathToken = "/token" PathRegister = "/register" )
Paths below the issuer.
const ( // LabelSubject is Google's stable account ID (sub) for a person; the // same label googletoken sets for Path A. LabelSubject = googletoken.LabelSubject // LabelHD is a person's Workspace domain, absent for a consumer // account; the same label googletoken sets for Path A. LabelHD = googletoken.LabelHD // LabelClientID is the OAuth client the token was issued to. LabelClientID = "steward.client_id" // LabelScope is the token's granted service scopes, space-separated. LabelScope = "steward.scope" // LabelKind is KindUser or KindWorkload. LabelKind = "steward.kind" // LabelServiceAccount is a workload's service account, if it has one. LabelServiceAccount = "steward.service_account" )
Labels set on the purser.Caller for an access token.
const ( KindUser = "user" KindWorkload = "workload" )
Values of LabelKind.
const VaultEndpoint = "https://agentidentitycredentials.googleapis.com/v1/"
VaultEndpoint is the Agent Identity credential vault's REST endpoint.
Variables ¶
var ErrInvalidToken = fmt.Errorf("authserver: invalid access token: %w", purser.ErrUnauthenticated)
ErrInvalidToken is an access token that is not one of this server's, is expired, is bound to another resource, or belongs to a workload whose configuration has changed. It wraps purser.ErrUnauthenticated.
ErrUnavailable is the sealing keys being unavailable, so no token can be checked right now. It wraps purser.ErrUnavailable and not purser.ErrUnauthenticated, so purser's enforced middleware answers 503 with Retry-After rather than 401.
Functions ¶
func SSRFSafeClient ¶
SSRFSafeClient is an HTTP client for client-supplied URLs: it dials only public unicast addresses (checked on the resolved IP, so DNS cannot smuggle in a private one), uses no proxy, and follows no redirects.
func WorkloadSubject ¶
WorkloadSubject is a client-credentials token's subject: MCP sessions bind to it, and it is the workload's purser.Caller identity. The prefix keeps it apart from Google subs, which are numeric, and from emails.
Types ¶
type Authenticator ¶
type Authenticator struct {
// contains filtered or unexported fields
}
Authenticator is a purser authenticator for access tokens. Its verdict is purser.AuthSourceOIDC for every token, a person's or a workload's: the token is verified locally against the issuer's keys, audience and expiry included, as an OIDC token is. (purser has no source for "an authorization server's own sealed token"; OIDC is the nearest that is true, and a source is fixed per authenticator.) The verdict does not say whether a person is behind the request: branch on the Caller's LabelKind, or Principal.Workload, never on the source.
func (*Authenticator) Authenticate ¶
Authenticate implements authn.Authenticator.
func (*Authenticator) GatesCredentials ¶
func (*Authenticator) GatesCredentials() bool
GatesCredentials implements authn.CredentialGate.
func (*Authenticator) Source ¶
func (*Authenticator) Source() purser.AuthSource
Source implements authn.Authenticator.
type Config ¶
type Config struct {
// Issuer is the server's public base URL, exactly as clients reach it,
// for example "https://svc.example.com" (a path is allowed). https is
// required, except for a loopback host. The endpoints sit below it:
// Issuer+PathAuthorize, and so on. Required.
Issuer string
// Resource is the protected resource every token is bound to (RFC
// 8707), for example "https://svc.example.com/mcp". A client may name
// it in the resource parameter, or leave it out. Required.
Resource string
// Scopes are the service's own scopes, for example "svc:read" and
// "svc:write". A client is granted the ones it asks for that exist (and
// that a static client is allowed), others being dropped as RFC 6749
// section 3.3 allows. At least one is required.
Scopes []string
// DefaultScopes are granted when a client asks for none of Scopes.
// Empty means all of Scopes.
DefaultScopes []string
// Google is the service's own OAuth client at Google. Its redirect
// URIs must include CallbackURL (and, under vault custody, the auth
// provider's oauthcallback URL). Required.
Google GoogleClient
// GoogleScopes are the Google scopes held for each user beyond openid
// and userinfo.email, spelled as Google's canonical URLs (the vault
// matches stored grants by exact spelling). Empty means
// ScopeCloudPlatform.
GoogleScopes []string
// Custody holds users' Google grants: *VaultCustody or SealedCustody.
// Required.
Custody Custody
// Admit decides who may sign in, and is asked again at every refresh.
// Required.
Admit *allow.Admitter
// Keys seals every token, code, sign-in state and DCR client ID.
// Required.
Keys seal.KeyProvider
// Clients are pre-registered. They skip the consent page.
Clients []StaticClient
// ServiceTokens mints Google access tokens for client-credentials
// clients that name a ServiceAccount. Required if any does.
ServiceTokens ServiceTokens
// OpenRegistration accepts DCR and CIMD clients. Off: only Clients.
OpenRegistration bool
// Replay remembers spent authorization codes and rotated refresh
// tokens. Nil means an in-memory cache, which is per replica: with
// several replicas, a code or a rotated refresh token could be used
// once on each. Supply a shared one to close that, implementing
// RotationIDReplayCache too, or a refresh can give back a concurrent
// refresh's rotation (see ReplayCache.Unrotate).
Replay ReplayCache
// RefreshReuseGrace tolerates a refresh token presented again just
// after it was rotated, as clients whose processes share one token
// store present it when two of them refresh at once. Within it, the
// generation a family has just moved away from is refused
// (invalid_grant) without revoking the family, so the token the first
// refresh issued stays valid and the client can re-read it from its
// store. Any older generation, or the same one later, still revokes
// the family, and nothing is ever issued for a rotated token. Only a
// Replay that implements GraceReplayCache or RotationIDReplayCache (the
// in-memory one implements both) can tell the difference; with any
// other, every reuse revokes. Zero, the
// default, means no grace: every reuse revokes. A grace weakens theft
// detection, so set one only for clients that need it; 10 seconds
// covers a concurrent refresh's round trip (admission, a Google or
// vault call or two, the response). Under VaultCustody a refresh may
// first wait out a nearly spent Google token (up to 78 seconds), but
// before the family is rotated: refreshes that arrive together wait
// together and still rotate moments apart, so the grace need not
// cover the wait, unless the vault renews tokens before they expire
// (not seen; see docs/DESIGN.md, Vault renewal), when a later arrival
// may rotate while an earlier one still waits. At most a minute: the
// window is time in which a stolen token's reuse is not detected.
RefreshReuseGrace time.Duration
// ServiceName names the service on the consent page. Empty means the
// issuer's host.
ServiceName string
// HTTPClient calls Google's token and tokeninfo endpoints. Nil means a
// client with a 30 s timeout.
HTTPClient *http.Client
// CIMDClient fetches Client ID Metadata Documents. Nil means
// SSRFSafeClient. Tests on loopback replace it.
CIMDClient *http.Client
// Logger receives sign-ins, refusals and backend failures (never a
// token). Nil means slog.Default().
Logger *slog.Logger
}
Config is one deployment's authorization server. Nothing about the Google side is built in.
type Custody ¶
type Custody interface {
// Name is "vault" or "sealed", for logs.
Name() string
// contains filtered or unexported methods
}
Custody holds users' Google grants and mints Google access tokens from them. The implementations are *VaultCustody (the Agent Identity credential vault, the default in kode-gopher) and SealedCustody (the Google refresh token travels inside steward's own sealed refresh token). The interface is sealed: its methods beyond Name are unexported, so only this package implements it.
type GoogleClient ¶
type GoogleClient struct {
ClientID string
ClientSecret string
AuthURL string
TokenURL string
TokenInfoURL string
}
GoogleClient is the service's own confidential OAuth client at Google, and Google's endpoints. Zero endpoint fields take Google's defaults; tests point them at fakes.
func LoadGoogleClient ¶
func LoadGoogleClient(path string) (GoogleClient, error)
LoadGoogleClient reads the client ID and secret from the JSON file the Cloud console downloads for an OAuth client ({"web": {...}}).
type GraceReplayCache ¶ added in v0.4.0
type GraceReplayCache interface {
ReplayCache
// RotateGrace is Rotate, except that:
//
// - a rotation (to gen+1, from any starting point Rotate allows)
// records graceUntil with the family;
// - presenting gen when the family is at gen+1, before the graceUntil
// that rotation recorded, is RotateRefused: the family is left as
// it is, not revoked;
// - any older generation, the same one at or after graceUntil, or any
// generation of a revoked family, is RotateRevoked, and the family
// is revoked as Rotate revokes it.
//
// graceUntil, like exp, is an absolute time from the server's clock;
// the zero time grants no grace. An error is reported as by Rotate.
RotateGrace(ctx context.Context, family string, gen uint64, exp, graceUntil time.Time) (RotateResult, error)
}
GraceReplayCache is a ReplayCache that tells a concurrent refresh from a replay. Clients whose processes share one token store can present the same refresh token twice within milliseconds; with Rotate alone the second presentation revokes the family, and the first one's new token with it. When Config.Replay implements GraceReplayCache, the server calls RotateGrace instead of Rotate (when Config.RefreshReuseGrace is set; by default it is not), and a second presentation within the grace is refused without revoking, so the client can re-read its store and find the new token. Nothing is ever issued for a rotated generation either way. A cache that implements RotationIDReplayCache gets the grace through RotateWithID instead, and the server calls that.
A shared implementation keeps one more value per family, the grace deadline of its last rotation, under the guarantees ReplayCache states: checked and set atomically with the generation, kept until the family's exp. Its Rotate neither records nor honours a grace.
A wrapper that embeds a GraceReplayCache (a *MemoryReplayCache, say) and overrides Rotate must override RotateGrace too, or the server calls the embedded RotateGrace and skips the override (and RotateWithID and UnrotateWithID, as RotationIDReplayCache says, for a *MemoryReplayCache).
type MemoryReplayCache ¶
type MemoryReplayCache struct {
// contains filtered or unexported fields
}
MemoryReplayCache is the in-memory ReplayCache: per process, and forgotten on restart. With several replicas each keeping its own, reuse detection is per replica: a stolen refresh token can go on being used on a replica that never saw the family revoked, and a code can be exchanged once on each (PKCE still binds it to its client's verifier). A service running replicas supplies a shared ReplayCache.
func NewMemoryReplayCache ¶
func NewMemoryReplayCache() *MemoryReplayCache
NewMemoryReplayCache returns an empty in-memory ReplayCache. It is a GraceReplayCache and a RotationIDReplayCache.
func (*MemoryReplayCache) Release ¶
func (c *MemoryReplayCache) Release(_ context.Context, id string) error
Release implements ReplayCache.
func (*MemoryReplayCache) Rotate ¶
func (c *MemoryReplayCache) Rotate(_ context.Context, fam string, gen uint64, exp time.Time) (bool, error)
Rotate implements ReplayCache. It grants no grace and honours none a RotateGrace recorded: every reuse revokes, as ReplayCache states.
func (*MemoryReplayCache) RotateGrace ¶ added in v0.4.0
func (c *MemoryReplayCache) RotateGrace(_ context.Context, fam string, gen uint64, exp, graceUntil time.Time) (RotateResult, error)
RotateGrace implements GraceReplayCache.
func (*MemoryReplayCache) RotateWithID ¶ added in v0.4.0
func (c *MemoryReplayCache) RotateWithID(_ context.Context, fam string, gen uint64, exp, graceUntil time.Time, rotation string) (RotateResult, error)
RotateWithID implements RotationIDReplayCache.
func (*MemoryReplayCache) Unrotate ¶
Unrotate implements ReplayCache: whichever rotation moved the family to gen+1 is given back.
func (*MemoryReplayCache) UnrotateWithID ¶ added in v0.4.0
func (c *MemoryReplayCache) UnrotateWithID(_ context.Context, fam string, gen uint64, rotation string) error
UnrotateWithID implements RotationIDReplayCache.
type Principal ¶
type Principal struct {
// Subject is Google's sub for a person, or WorkloadSubject(client)
// for a workload.
Subject string
// Email is a person's verified address, lower-cased. Empty for a
// workload (see ServiceAccount).
Email string
// HD is a person's Workspace domain, empty for a consumer account or a
// workload.
HD string
// ClientID is the OAuth client the token was issued to.
ClientID string
// Scopes are the granted service scopes.
Scopes []string
// Expiry is when this access token expires.
Expiry time.Time
// Workload is set for a client-credentials token: there is no person.
Workload bool
// ServiceAccount is a workload's Google service account, if it has
// one; TokenSource then gives that account's token.
ServiceAccount string
// GoogleScopes are the scopes of the Google token inside, as Google
// reported them (empty when unknown, or for a workload).
GoogleScopes []string
// contains filtered or unexported fields
}
Principal is who a verified access token belongs to.
It holds the Google access token sealed inside the token, but only behind TokenSource: the field is unexported, and formatting a Principal prints a pointer, never the token.
func (Principal) Caller ¶
Caller is the purser.Caller for p. A person's Identity is their email, with LabelSubject and LabelHD as on Path A; a workload's is its WorkloadSubject. Both carry LabelClientID, LabelScope and LabelKind.
func (Principal) TokenSource ¶
func (p Principal) TokenSource() (oauth2.TokenSource, bool)
TokenSource returns the Google access token sealed in the access token: the person's own, or a workload's service account's. It does not refresh; the client refreshes steward's token, which mints a new Google one. ok is false for a workload with no service account.
type ReplayCache ¶
type ReplayCache interface {
// Claim spends a single-use ID until exp. It reports false if the ID
// was already spent (and that claim has not expired).
Claim(ctx context.Context, id string, exp time.Time) (bool, error)
// Release gives back a claim, after a use that failed for a transient
// reason, so the client's retry is not refused as a replay.
Release(ctx context.Context, id string) error
// Rotate moves family from generation gen to gen+1 and sets its exp.
// It reports false, and revokes the family until its current exp, if
// the family is past gen; false also for a revoked family. An unknown
// (or expired) family is created at gen+1. A family at an earlier
// generation is moved to gen+1: with a cache that loses state (one per
// replica, or one that restarts), another replica may have rotated it.
Rotate(ctx context.Context, family string, gen uint64, exp time.Time) (bool, error)
// Unrotate moves family back from gen+1 to gen, leaving its exp, after
// a refresh that failed for a transient reason. It does nothing for a
// family that has moved on, been revoked, expired or is unknown. A
// GraceReplayCache also forgets the grace the undone rotation recorded.
//
// It cannot tell whose rotation it gives back. With a cache shared
// between replicas, a request whose Rotate failed without applying,
// while a concurrent refresh with the same token applied, moves the
// family back from that refresh's rotation, and the client's retry
// then rotates it again: two refresh tokens of the next generation are
// live. The server calls RotationIDReplayCache's UnrotateWithID instead
// when the cache implements it.
Unrotate(ctx context.Context, family string, gen uint64) error
}
ReplayCache is the server's one piece of state: it spends authorization codes, and tracks refresh-token families so that a rotated refresh token is never accepted again (OAuth 2.1 section 4.3.1).
Every refresh token belongs to a family, started when its sign-in's code was exchanged, and carries a generation number. A refresh moves the family from the presented token's generation to the next. Presenting a generation the family has already moved past is a replay: one of the two holders of the token is not the client it was issued to, so the family is revoked and every token in it refused, and the user signs in again. Storage grows with live families (one per sign-in per client), not with refreshes. When Config.RefreshReuseGrace is set (by default it is not), a cache that also implements GraceReplayCache spares the generation a family has only just moved away from: presented again within the grace, it is refused without revoking the family.
A shared implementation (for a service running several replicas) must:
- be safe for concurrent use, and atomic per ID and per family (a compare-and-set, a transaction or a script);
- keep every claim and every family until its exp, never evicting one early: a forgotten family accepts any generation, which turns reuse detection off, and a forgotten claim lets a code be used twice;
- keep a revocation until the family's exp;
- make an error mean "not applied", as far as it can tell; the server follows a Rotate error with an Unrotate (UnrotateWithID, with a RotationIDReplayCache) in case it was applied anyway.
It should also implement RotationIDReplayCache. Unrotate is conditional only on the generation, so under sharing it can give back another request's rotation (as can an Unrotate delivered twice), and a rotated refresh token then yields tokens again.
An error is a cache that could not answer; the token endpoint then answers server_error and spends nothing.
type RotateResult ¶ added in v0.4.0
type RotateResult int
RotateResult is a GraceReplayCache's or RotationIDReplayCache's answer to a refresh.
const ( // RotateRevoked refuses the refresh: the family was past the presented // generation and is now revoked, or was revoked already. It is the zero // value, so a result left unset refuses. RotateRevoked RotateResult = iota // RotateApplied moved the family to the next generation. RotateApplied // RotateRefused refuses the refresh and leaves the family as it is, // not revoked: the presented generation is the one the family last // moved away from, within that move's grace. RotateRefused )
type RotationIDReplayCache ¶ added in v0.4.0
type RotationIDReplayCache interface {
ReplayCache
// RotateWithID is RotateGrace, recording rotation with the family when
// it applies (RotateApplied, from any starting point Rotate allows);
// a refusal leaves the recorded ID as it is. It is idempotent: when
// the family is at gen+1 by the rotation that recorded rotation (the
// same call delivered again, after a lost reply), it reports
// RotateApplied and changes nothing. With a zero graceUntil it is
// Rotate: it neither records nor honours a grace. An error is reported
// as by Rotate.
RotateWithID(ctx context.Context, family string, gen uint64, exp, graceUntil time.Time, rotation string) (RotateResult, error)
// UnrotateWithID is Unrotate, done only if the family is at gen+1 by
// the rotation that recorded rotation: it does nothing when another
// rotation (with another ID, or with none) moved the family there, or
// for an empty rotation, so delivering it twice is harmless. Like
// Unrotate, it forgets the undone rotation's grace, and it forgets the
// ID, which named a rotation that no longer exists.
UnrotateWithID(ctx context.Context, family string, gen uint64, rotation string) error
}
RotationIDReplayCache is a ReplayCache whose rotations carry an identity, so that a refresh gives back its own rotation and never another's.
A refresh rotates its family first and gives the rotation back if it then fails for a transient reason, so the client's retry is not taken for a replay. Unrotate is conditional only on the generation, which is not enough when replicas share the cache: a request whose Rotate failed without applying (or with an outcome it cannot know, such as a timeout) while a concurrent refresh with the same token applied gives back that refresh's rotation, and the client's retry rotates again. A rotated token has then yielded tokens, and two refresh tokens of the next generation are live, so the holder who refreshes second is not caught presenting a rotated token.
When Config.Replay implements RotationIDReplayCache, the server calls RotateWithID, with a fresh random ID per refresh, instead of Rotate and RotateGrace, and gives a rotation back with UnrotateWithID and that ID instead of Unrotate. Giving back a rotation that never applied, or that another rotation has since replaced, does nothing. So after a RotateWithID error, whose outcome is unknown, the server gives the rotation back and answers server_error: either its rotation is undone and the retry works, or it never applied, any concurrent rotation stands, and the retry is refused as a replay. (A write that lands after the UnrotateWithID meant to undo it either rotates the family with no token issued for it, or, if another refresh rotated it meanwhile, is a replay that revokes it or is refused in the grace. Either way the retry is refused and the user signs in again: a sign-out, never a second branch.)
The fix holds once every server sharing the cache calls the ID methods: during a rolling upgrade, a replica still calling Unrotate after a Rotate error can give back a newer replica's rotation.
A shared implementation keeps one more value per family, the ID of the rotation that moved it to its current generation, under the guarantees ReplayCache states: set atomically with the generation by every rotation (Rotate and RotateGrace set none, which no ID matches), and kept until the family's exp; a give-back (Unrotate or UnrotateWithID) should clear it. An ID is an opaque string of at most 64 bytes, unique per refresh; it is not a credential.
A wrapper that embeds a RotationIDReplayCache (a *MemoryReplayCache, say) and overrides Rotate, RotateGrace or Unrotate must override RotateWithID and UnrotateWithID too, or the server calls the embedded ones and skips the overrides.
type SealedCustody ¶
type SealedCustody struct{}
SealedCustody is the fallback: the Google refresh token travels inside steward's own sealed refresh token, held by the client. Sign-in asks Google for offline access and every configured Google scope.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the authorization server. It is immutable after New and safe for concurrent use.
func (*Server) Authenticator ¶
func (s *Server) Authenticator() *Authenticator
Authenticator returns a purser authn.Authenticator for this server's access tokens presented as "Authorization: Bearer <token>". Use it with httpmw.CallerOptions{Enforce: true} and no Fallback, as for Path A.
func (*Server) CallbackURL ¶
CallbackURL is where Google returns the browser after sign-in. Register it as a redirect URI of the Google OAuth client.
func (*Server) ContinueURL ¶
ContinueURL is where the vault's consent leg returns the browser.
func (*Server) DefaultScopes ¶
DefaultScopes are the scopes granted to a client that asks for none of Scopes: Config.DefaultScopes, or all of Scopes.
func (*Server) Handler ¶
Handler serves every endpoint. Mount it at the root of the issuer's host (it matches full paths), or use Register.
func (*Server) MetadataURL ¶
MetadataURL is the RFC 8414 authorization server metadata document's URL.
func (*Server) Paths ¶
Paths lists the URL paths the server answers, for a service that routes them onto its own mux one by one. Handler and Register cover them all.
func (*Server) Register ¶
Register mounts the server's endpoints on mux, at the paths the issuer implies.
type ServiceTokens ¶
type ServiceTokens interface {
Token(ctx context.Context, serviceAccount string) (*oauth2.Token, error)
}
ServiceTokens mints Google access tokens for service accounts, for client-credentials clients that name one (for example by the IAM Credentials API's generateAccessToken, as the service's own identity).
type StaticClient ¶
type StaticClient struct {
// ID is the client_id: a plain string, not a URL and not an envelope.
ID string `json:"client_id"`
// Secret makes the client confidential: it must authenticate at the
// token endpoint (client_secret_basic or client_secret_post).
Secret string `json:"client_secret,omitempty"`
// Name is shown in logs, cleaned like any client's name: control and
// format characters dropped, whitespace collapsed, at most 100 bytes.
Name string `json:"client_name,omitempty"`
// RedirectURIs are where the client may receive codes. A user-facing
// client needs at least one.
RedirectURIs []string `json:"redirect_uris,omitempty"`
// ClientCredentials makes this a client-credentials client (RFC 6749
// section 4.4): a workload with no user, which gets access tokens with
// its secret alone. It needs a secret and no redirect URIs, so it
// cannot sign users in.
ClientCredentials bool `json:"client_credentials,omitempty"`
// ServiceAccount, for a client-credentials client, is a Google service
// account whose access token (from Config.ServiceTokens) is sealed into
// the client's access tokens, so the resource can act as that account.
// Setting it implies ClientCredentials. Empty: the workload's tokens
// carry no Google token, and the resource acts as itself.
ServiceAccount string `json:"service_account,omitempty"`
// Scopes limits the service scopes this client may be granted. Empty
// means any of Config.Scopes.
Scopes []string `json:"scopes,omitempty"`
}
StaticClient is a pre-registered client, for example from a clients file (LoadStaticClients).
func LoadStaticClients ¶
func LoadStaticClients(path string) ([]StaticClient, error)
LoadStaticClients reads a JSON array of StaticClient.
type User ¶
type User struct {
// Sub is Google's stable account ID.
Sub string `json:"sub"`
// Email is the account's verified address, lower-cased.
Email string `json:"email"`
// Domain is the ID token's hd claim: the user's Workspace domain,
// empty for a consumer account.
Domain string `json:"hd,omitempty"`
}
User is a signed-in Google user, from a verified ID token.
type VaultCustody ¶
type VaultCustody struct {
// AuthProvider is the full resource name,
// projects/<p>/locations/<l>/authProviders/<name>. Required.
AuthProvider string
// Client calls the vault as the service's own identity (with
// roles/agentidentity.user on the auth provider). Required.
Client *http.Client
// Endpoint replaces VaultEndpoint (tests).
Endpoint string
// contains filtered or unexported fields
}
VaultCustody keeps users' Google grants in the Agent Identity credential vault (agentidentitycredentials.googleapis.com). Sign-in only identifies the user (openid, email, online); the vault runs its own consent leg for the configured Google scopes.
The vault trusts whatever user ID it is given and stores whichever account consented, so every token it returns is checked against the signed-in user's sub with Google's tokeninfo before use, and must carry every configured scope. Scopes are always sent in Google's canonical spelling, which the vault matches exactly. The vault's expireTime is ignored in favour of tokeninfo's. A token tokeninfo refuses is force-refreshed once; one Google still accepts never is, and one too close to expiry to use is waited out (up to 78 seconds at refresh and 93 at sign-in, plus the vault and tokeninfo calls, during the token request, the sign-in callback or the consent return) and retrieved again. At refresh the wait runs before the refresh token's family is rotated (prepare), so it never holds the family rotated. It moves the server's WriteTimeout deadline past itself, unless the ResponseWriter is wrapped without Unwrap. Give the front end a timeout of at least 2 minutes on those paths; a shorter one turns that request into a retry.