Documentation
¶
Overview ¶
Package sdk is the ergonomic Go SDK for IAM resource servers.
Server applications use this package to verify tokens received from clients. The SDK calls IAM's token verification endpoint with the server's own service/admin credential and stores the verified principal in request contexts for downstream handlers.
Index ¶
- Variables
- func BearerToken(r *http.Request) (string, bool)
- func HTTPMiddleware(auth Authenticator, next http.Handler) http.Handler
- func HTTPMiddlewareWithOptions(auth Authenticator, opts HTTPMiddlewareOptions) func(http.Handler) http.Handler
- func Refresh(ctx context.Context, auth Authenticator) error
- func RequireAAL(minAAL int, opts ...GuardOption) func(http.Handler) http.Handler
- func RequireAnyScope(scopes []string, opts ...GuardOption) func(http.Handler) http.Handler
- func RequireScopes(scopes []string, opts ...GuardOption) func(http.Handler) http.Handler
- func Warm(ctx context.Context, auth Authenticator) error
- func WithPrincipal(ctx context.Context, principal *Principal) context.Context
- type Authenticator
- type AuthenticatorConfig
- type Claims
- type Client
- type Config
- type GuardOption
- type HTTPErrorHandler
- type HTTPMiddlewareOptions
- type HTTPTokenExtractor
- type HybridVerifier
- func (v *HybridVerifier) Authenticate(ctx context.Context, token string) (*Principal, error)
- func (v *HybridVerifier) Middleware(next http.Handler) http.Handler
- func (v *HybridVerifier) MiddlewareWithOptions(opts HTTPMiddlewareOptions) func(http.Handler) http.Handler
- func (v *HybridVerifier) Refresh(ctx context.Context) error
- func (v *HybridVerifier) Verify(ctx context.Context, token string) (*VerifyResult, error)
- func (v *HybridVerifier) Warm(ctx context.Context) error
- type LocalConfig
- type LocalVerifier
- func (v *LocalVerifier) Authenticate(ctx context.Context, token string) (*Principal, error)
- func (v *LocalVerifier) Middleware(next http.Handler) http.Handler
- func (v *LocalVerifier) MiddlewareWithOptions(opts HTTPMiddlewareOptions) func(http.Handler) http.Handler
- func (v *LocalVerifier) Refresh(ctx context.Context) error
- func (v *LocalVerifier) Verify(ctx context.Context, token string) (*VerifyResult, error)
- func (v *LocalVerifier) Warm(ctx context.Context) error
- type Principal
- func (p *Principal) HasAMR(method string) bool
- func (p *Principal) HasAllScopes(scopes ...string) bool
- func (p *Principal) HasAnyScope(scopes ...string) bool
- func (p *Principal) HasScope(scope string) bool
- func (p *Principal) InAnyGroup(groups ...string) bool
- func (p *Principal) InGroup(group string) bool
- func (p *Principal) MeetsAAL(minAAL int) bool
- type Refresher
- type SessionRevokedData
- type ValidationMode
- type Verifier
- func (v *Verifier) Authenticate(ctx context.Context, token string) (*Principal, error)
- func (v *Verifier) Introspect(ctx context.Context, token string) (*VerifyResult, error)
- func (v *Verifier) Middleware(next http.Handler) http.Handler
- func (v *Verifier) MiddlewareWithOptions(opts HTTPMiddlewareOptions) func(http.Handler) http.Handler
- func (v *Verifier) Refresh(context.Context) error
- func (v *Verifier) Verify(ctx context.Context, token string) (*VerifyResult, error)
- func (v *Verifier) Warm(context.Context) error
- type VerifierOption
- type VerifyResult
- type Warmer
- type WebhookEvent
- type WebhookVerifier
- type WebhookVerifierConfig
Constants ¶
This section is empty.
Variables ¶
var ( // ErrProjectIDRequired is returned when a local JWKS URL must be derived // but no project id was configured. ErrProjectIDRequired = errors.New("iam sdk: project id is required for local jwks url") // ErrEnvironmentRequired is returned when a local JWKS URL must be derived // but no environment was configured. ErrEnvironmentRequired = errors.New("iam sdk: environment is required for local jwks url") // ErrLocalBaseURLRequired is returned when building a local JWKS URL with // no base URL configured. ErrLocalBaseURLRequired = errors.New("iam sdk: base url is required for local jwks url") // ErrInvalidTokenType, ErrInvalidIssuer, ErrInvalidProject, // ErrInvalidEnvironment, ErrInvalidAudience are validateClaims' rejection // reasons; VerifyResult.Error carries err.Error() verbatim as the // machine-readable code a caller sees. ErrInvalidTokenType = errors.New("invalid_token_type") ErrInvalidIssuer = errors.New("invalid_issuer") ErrInvalidProject = errors.New("invalid_project") ErrInvalidEnvironment = errors.New("invalid_environment") ErrInvalidAudience = errors.New("invalid_audience") )
var ( // ErrMissingToken is returned when an incoming request has no bearer token. ErrMissingToken = errors.New("iam sdk: missing bearer token") // ErrInvalidToken is returned when IAM rejects the incoming bearer token. ErrInvalidToken = errors.New("iam sdk: invalid bearer token") // ErrBaseURLRequired is returned by New when Config.BaseURL is empty. ErrBaseURLRequired = errors.New("iam sdk: base url is required") // ErrCredentialRequired is returned by New when Config.Credential is empty. ErrCredentialRequired = errors.New("iam sdk: credential is required") )
var ( ErrWebhookMalformedHeaders = errors.New("iam sdk: malformed webhook headers") ErrWebhookStaleTimestamp = errors.New("iam sdk: webhook timestamp outside allowed skew") ErrWebhookInvalidSignature = errors.New("iam sdk: invalid webhook signature") ErrWebhookMalformedBody = errors.New("iam sdk: malformed webhook body") // ErrWebhookMaxSkewNegative is returned when WebhookVerifierConfig.MaxSkew // is negative. ErrWebhookMaxSkewNegative = errors.New("iam sdk: webhook max skew must not be negative") // ErrWebhookSecretRequired is returned when the webhook signing secret is // empty. ErrWebhookSecretRequired = errors.New("iam sdk: webhook signing secret is required") // ErrWebhookSecretInvalid is returned when a whsec_-prefixed signing // secret does not decode to a non-empty value. ErrWebhookSecretInvalid = errors.New("iam sdk: invalid webhook signing secret") )
var ErrForbidden = errors.New("iam sdk: forbidden")
ErrForbidden is returned when an authenticated principal lacks a required claim (scope or assurance level).
var ErrUnsupportedValidationMode = errors.New("iam sdk: unsupported validation mode")
ErrUnsupportedValidationMode is returned by NewAuthenticator for an AuthenticatorConfig.Mode that names none of the ValidationMode constants.
Functions ¶
func BearerToken ¶
BearerToken extracts an Authorization: Bearer token from an HTTP request.
func HTTPMiddleware ¶
func HTTPMiddleware(auth Authenticator, next http.Handler) http.Handler
HTTPMiddleware authenticates requests and stores Principal in request context.
func HTTPMiddlewareWithOptions ¶
func HTTPMiddlewareWithOptions(auth Authenticator, opts HTTPMiddlewareOptions) func(http.Handler) http.Handler
HTTPMiddlewareWithOptions returns configurable HTTP authentication middleware.
func Refresh ¶
func Refresh(ctx context.Context, auth Authenticator) error
Refresh forces authenticator verification state refresh when supported.
func RequireAAL ¶ added in v1.1.0
RequireAAL admits a request only when the principal's assurance level is at least minAAL (e.g. RequireAAL(2) demands a step-up/MFA session). Chain after an authentication middleware.
func RequireAnyScope ¶ added in v1.1.0
RequireAnyScope admits a request when the principal holds at least one of the listed scopes. Chain after an authentication middleware.
func RequireScopes ¶ added in v1.1.0
RequireScopes admits a request only when the principal holds every listed scope. Chain after an authentication middleware.
Types ¶
type Authenticator ¶
type Authenticator interface {
Authenticate(ctx context.Context, token string) (*Principal, error)
}
Authenticator verifies a bearer token and returns a Principal on success.
func NewAuthenticator ¶
func NewAuthenticator(config AuthenticatorConfig) (Authenticator, error)
NewAuthenticator builds a remote, local, or hybrid Authenticator from config.
type AuthenticatorConfig ¶
type AuthenticatorConfig struct {
Mode ValidationMode `default:"remote" mapstructure:"mode" validate:"oneof=remote local hybrid"` //nolint:lll
BaseURL string `default:"" mapstructure:"base_url" validate:"omitempty,url"`
Credential string `default:"" mapstructure:"credential"`
ProjectID string `default:"" mapstructure:"project_id"`
Environment string `default:"live" mapstructure:"environment"`
Issuer string `default:"" mapstructure:"issuer"`
Audience string `default:"" mapstructure:"audience"`
JWKSURL string `default:"" mapstructure:"jwks_url"`
JWKSCacheTTLSec int `default:"300" mapstructure:"jwks_cache_ttl_sec" validate:"min=1"`
TokenType string `default:"access" mapstructure:"token_type" validate:"omitempty,oneof=access id_token"` //nolint:lll
HTTPClient *http.Client `mapstructure:"-" validate:"-"`
}
AuthenticatorConfig is the high-level SDK wiring config for resource servers. It is intentionally tagged like internal/config service structs, so callers can load it with the same structconf/mapstructure pipeline.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client wraps the generated IAM OpenAPI client with server-side conveniences.
type Config ¶
type Config struct {
// BaseURL is the IAM API base URL, for example https://iam.example.com.
BaseURL string
// Credential is the server's IAM credential used to call verification APIs.
// In production this is usually a service token or project-admin token.
Credential string
// HTTPClient optionally overrides the HTTP client used for IAM API calls.
HTTPClient *http.Client
}
Config configures a server-side IAM SDK client.
type GuardOption ¶ added in v1.1.0
type GuardOption func(*guardConfig)
GuardOption customizes a claim guard's failure handlers.
func WithForbiddenHandler ¶ added in v1.1.0
func WithForbiddenHandler(h HTTPErrorHandler) GuardOption
WithForbiddenHandler overrides the response when the Principal lacks a required claim (defaults to 403).
func WithUnauthenticatedHandler ¶ added in v1.1.0
func WithUnauthenticatedHandler(h HTTPErrorHandler) GuardOption
WithUnauthenticatedHandler overrides the response when no Principal is present in the request context (defaults to 401).
type HTTPErrorHandler ¶
type HTTPErrorHandler func(http.ResponseWriter, *http.Request, error)
HTTPErrorHandler handles middleware authentication failures.
type HTTPMiddlewareOptions ¶
type HTTPMiddlewareOptions struct {
TokenExtractor HTTPTokenExtractor
ErrorHandler HTTPErrorHandler
}
HTTPMiddlewareOptions customizes HTTP middleware behavior.
type HTTPTokenExtractor ¶
HTTPTokenExtractor extracts an IAM token from an HTTP request.
type HybridVerifier ¶
type HybridVerifier struct {
// contains filtered or unexported fields
}
HybridVerifier verifies locally first and falls back to remote verification when the local path cannot authenticate a token.
func NewHybridVerifier ¶
func NewHybridVerifier(local *LocalVerifier, remote *Verifier) *HybridVerifier
NewHybridVerifier wires local and remote verification paths together.
func (*HybridVerifier) Authenticate ¶
Authenticate verifies token and returns a Principal on success.
func (*HybridVerifier) Middleware ¶
func (v *HybridVerifier) Middleware(next http.Handler) http.Handler
Middleware authenticates HTTP requests with hybrid verification.
func (*HybridVerifier) MiddlewareWithOptions ¶
func (v *HybridVerifier) MiddlewareWithOptions(opts HTTPMiddlewareOptions) func(http.Handler) http.Handler
MiddlewareWithOptions returns configurable HTTP authentication middleware.
func (*HybridVerifier) Refresh ¶
func (v *HybridVerifier) Refresh(ctx context.Context) error
Refresh forces local JWKS refresh.
func (*HybridVerifier) Verify ¶
func (v *HybridVerifier) Verify(ctx context.Context, token string) (*VerifyResult, error)
Verify tries local JWKS verification first, then falls back to IAM remote verification when local verification fails with a generic invalid_token.
type LocalConfig ¶
type LocalConfig struct {
// BaseURL is the IAM public base URL. It is used to build JWKSURL when
// JWKSURL is not provided.
BaseURL string
// JWKSURL optionally overrides the public JWKS endpoint.
JWKSURL string
// ProjectID scopes verification to a single IAM project.
ProjectID string
// Environment scopes verification to a single IAM environment.
Environment string
// Issuer optionally overrides the expected iss claim. When empty and
// ProjectID/Environment are set, it defaults to /p/{project_id}/e/{env}.
Issuer string
// Audience optionally validates aud/client_id.
Audience string
// TokenType validates typ. Empty defaults to access.
TokenType string
// CacheTTL controls how long fetched JWKS keys are reused.
CacheTTL time.Duration
// HTTPClient optionally overrides the HTTP client used for JWKS fetches.
HTTPClient *http.Client
}
LocalConfig configures local JWT verification using IAM's public JWKS.
type LocalVerifier ¶
type LocalVerifier struct {
// contains filtered or unexported fields
}
LocalVerifier verifies IAM JWTs locally using the project's JWKS.
func NewLocalVerifier ¶
func NewLocalVerifier(config LocalConfig) (*LocalVerifier, error)
NewLocalVerifier creates a local JWT verifier that does not call IAM token verification APIs.
func (*LocalVerifier) Authenticate ¶
Authenticate verifies token and returns a Principal on success.
func (*LocalVerifier) Middleware ¶
func (v *LocalVerifier) Middleware(next http.Handler) http.Handler
Middleware authenticates HTTP requests with local JWT verification.
func (*LocalVerifier) MiddlewareWithOptions ¶
func (v *LocalVerifier) MiddlewareWithOptions(opts HTTPMiddlewareOptions) func(http.Handler) http.Handler
MiddlewareWithOptions returns configurable HTTP authentication middleware.
func (*LocalVerifier) Refresh ¶
func (v *LocalVerifier) Refresh(ctx context.Context) error
Refresh forces JWKS cache refresh.
func (*LocalVerifier) Verify ¶
func (v *LocalVerifier) Verify(ctx context.Context, token string) (*VerifyResult, error)
Verify verifies token locally against the cached JWKS.
type Principal ¶
type Principal struct {
Subject string
AccountID string
UserID string
ProjectID string
Environment string
SessionID string
ClientID string
Scopes []string
AAL int
AMR []string
// Groups are the subject's IAM roles, present when the token was issued with
// the `groups` scope. A resource server maps them onto its own permissions —
// it is the reason the claim exists, so it is surfaced here rather than left
// for every caller to dig out of Claims.
Groups []string
Claims Claims
}
Principal is the resource-server view of an authenticated IAM subject.
func PrincipalFrom ¶
PrincipalFrom returns the principal stored by SDK HTTP middleware or gRPC interceptors.
func (*Principal) HasAMR ¶ added in v1.1.0
HasAMR reports whether the principal authenticated with the given method (e.g. "pwd", "otp", "webauthn").
func (*Principal) HasAllScopes ¶ added in v1.1.0
HasAllScopes reports whether the principal holds every one of scopes.
func (*Principal) HasAnyScope ¶ added in v1.1.0
HasAnyScope reports whether the principal holds at least one of scopes. With no scopes it returns true (no constraint).
func (*Principal) HasScope ¶ added in v1.1.0
HasScope reports whether the principal was granted scope.
func (*Principal) InAnyGroup ¶ added in v1.6.0
InAnyGroup reports whether the principal holds at least one of groups. With no groups it returns true (no constraint).
type SessionRevokedData ¶ added in v1.5.0
type SessionRevokedData struct {
SessionID string `json:"session_id"`
UserID string `json:"user_id"`
ProjectID string `json:"project_id"`
}
SessionRevokedData is the stable data schema for a session.revoked event.
type ValidationMode ¶
type ValidationMode string
ValidationMode selects how resource-server tokens are verified.
const ( // ValidationModeRemote calls IAM /v1/tokens/verify for every token. It is the // only mode that sees a REVOCATION: IAM checks its denylist there, so a token // revoked through /oauth2/revoke (or by the session ending) stops working // immediately. ValidationModeRemote ValidationMode = "remote" // ValidationModeLocal verifies JWTs in-process using IAM's public JWKS. // // It never asks IAM anything, which is the point — and the cost: a revoked // token still verifies until it expires, because nothing tells this process // that it was revoked. Choose it when that window (the project's access_ttl, // 10 minutes by default) is acceptable, and shorten access_ttl if it is not. ValidationModeLocal ValidationMode = "local" // ValidationModeHybrid verifies locally first and falls back to remote verify // when local verification cannot authenticate the token. Local verification // SUCCEEDS for a revoked token, so this mode inherits the local window rather // than the remote guarantee. ValidationModeHybrid ValidationMode = "hybrid" )
type Verifier ¶
type Verifier struct {
// contains filtered or unexported fields
}
Verifier verifies end-user/client tokens received by a resource server.
func NewVerifier ¶
func NewVerifier(config Config, opts ...VerifierOption) (*Verifier, error)
NewVerifier creates a token verifier from Config.
func (*Verifier) Authenticate ¶
Authenticate verifies token and returns a Principal on success.
func (*Verifier) Introspect ¶
Introspect verifies token activity via IAM /v1/tokens/introspect.
func (*Verifier) Middleware ¶
Middleware authenticates requests and stores Principal in request context.
func (*Verifier) MiddlewareWithOptions ¶
func (v *Verifier) MiddlewareWithOptions(opts HTTPMiddlewareOptions) func(http.Handler) http.Handler
MiddlewareWithOptions returns configurable HTTP authentication middleware.
func (*Verifier) Refresh ¶
Refresh is a no-op for remote verification; IAM holds verification state.
type VerifierOption ¶
type VerifierOption func(*Verifier)
VerifierOption customizes a Verifier.
func WithAudience ¶
func WithAudience(audience string) VerifierOption
WithAudience asks IAM to validate the token audience.
type VerifyResult ¶
VerifyResult is IAM's token-verification response after decoding raw claims.
type WebhookEvent ¶ added in v1.5.0
type WebhookEvent struct {
ID string `json:"id"`
Type string `json:"type"`
Version int `json:"version"`
OccurredAt time.Time `json:"occurred_at"`
ProjectID string `json:"project_id"`
Environment string `json:"environment"`
Data json.RawMessage `json:"data"`
}
WebhookEvent is IAM's public webhook envelope. Data remains raw so callers can decode it into the type appropriate for Event.Type.
func (*WebhookEvent) DecodeData ¶ added in v1.5.0
func (e *WebhookEvent) DecodeData(dst any) error
DecodeData decodes the event data into dst after Verify has authenticated the envelope. dst is normally a pointer to an event-specific type.
func (*WebhookEvent) SessionRevokedData ¶ added in v1.5.0
func (e *WebhookEvent) SessionRevokedData() (SessionRevokedData, error)
SessionRevokedData decodes a session.revoked event and validates its required fields and project consistency with the envelope.
type WebhookVerifier ¶ added in v1.5.0
type WebhookVerifier struct {
// contains filtered or unexported fields
}
WebhookVerifier verifies IAM's Standard Webhooks request signatures.
func NewWebhookVerifier ¶ added in v1.5.0
func NewWebhookVerifier(config WebhookVerifierConfig) (*WebhookVerifier, error)
NewWebhookVerifier constructs a verifier for the signing secret returned by IAM. IAM emits Standard Webhooks whsec_ secrets; raw legacy secrets are also accepted so an existing subscription can migrate without a delivery gap.
func (*WebhookVerifier) Verify ¶ added in v1.5.0
func (v *WebhookVerifier) Verify(headers http.Header, body []byte) (*WebhookEvent, error)
Verify authenticates the Standard Webhooks headers before decoding body.
type WebhookVerifierConfig ¶ added in v1.5.0
type WebhookVerifierConfig struct {
SigningSecret string
MaxSkew time.Duration
Now func() time.Time
}
WebhookVerifierConfig configures Standard Webhooks verification. Replay storage intentionally belongs to the consumer: persist WebhookEvent.ID after Verify succeeds when a consumer needs one-time processing semantics.