sdk

package
v1.3.6 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2026 License: MIT Imports: 14 Imported by: 0

README

Go Server SDK

pkg/sdk is for resource servers that need to authenticate IAM bearer tokens.

Wiring

Load AuthenticatorConfig with the same config loader style used by the IAM service (mapstructure, default, validate tags), then build one authenticator:

auth, err := sdk.NewAuthenticator(sdk.AuthenticatorConfig{
	Mode:        sdk.ValidationModeHybrid,
	BaseURL:     "https://iam.example.com",
	Credential:  "service-token",
	ProjectID:   "proj_123",
	Environment: "live",
	Audience:    "api",
})
if err != nil {
	return err
}
if err := sdk.Warm(ctx, auth); err != nil {
	return err
}

remote calls IAM /v1/tokens/verify for every request. local verifies JWTs in-process from public JWKS. hybrid verifies locally first and falls back to remote verification when the local path cannot authenticate the token.

HTTP

handler := sdk.HTTPMiddleware(auth, protectedHandler)

Inside handlers:

principal, ok := sdk.PrincipalFrom(r.Context())

gRPC

Use the separate package so non-gRPC users do not import gRPC APIs:

server := grpc.NewServer(
	grpc.UnaryInterceptor(iamsdkgrpc.UnaryServerInterceptor(auth)),
	grpc.StreamInterceptor(iamsdkgrpc.StreamServerInterceptor(auth)),
)

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

Constants

This section is empty.

Variables

View Source
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")
)
View Source
var ErrForbidden = errors.New("iam sdk: forbidden")

ErrForbidden is returned when an authenticated principal lacks a required claim (scope or assurance level).

Functions

func BearerToken

func BearerToken(r *http.Request) (string, bool)

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

func RequireAAL(min int, opts ...GuardOption) func(http.Handler) http.Handler

RequireAAL admits a request only when the principal's assurance level is at least min (e.g. RequireAAL(2) demands a step-up/MFA session). Chain after an authentication middleware.

func RequireAnyScope added in v1.1.0

func RequireAnyScope(scopes []string, opts ...GuardOption) func(http.Handler) http.Handler

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

func RequireScopes(scopes []string, opts ...GuardOption) func(http.Handler) http.Handler

RequireScopes admits a request only when the principal holds every listed scope. Chain after an authentication middleware.

func Warm

func Warm(ctx context.Context, auth Authenticator) error

Warm initializes authenticator verification state when supported.

func WithPrincipal

func WithPrincipal(ctx context.Context, principal *Principal) context.Context

WithPrincipal stores principal in ctx.

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 `mapstructure:"mode" default:"remote" validate:"oneof=remote local hybrid"`
	BaseURL         string         `mapstructure:"base_url" default:"" validate:"omitempty,url"`
	Credential      string         `mapstructure:"credential" default:""`
	ProjectID       string         `mapstructure:"project_id" default:""`
	Environment     string         `mapstructure:"environment" default:"live"`
	Issuer          string         `mapstructure:"issuer" default:""`
	Audience        string         `mapstructure:"audience" default:""`
	JWKSURL         string         `mapstructure:"jwks_url" default:""`
	JWKSCacheTTLSec int            `mapstructure:"jwks_cache_ttl_sec" default:"300" validate:"min=1"`
	TokenType       string         `mapstructure:"token_type" default:"access" validate:"omitempty,oneof=access id_token"`
	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 Claims

type Claims map[string]any

Claims is the decoded claim set returned by IAM token verification.

type Client

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

Client wraps the generated IAM OpenAPI client with server-side conveniences.

func New

func New(config Config) (*Client, error)

New creates a server-side IAM SDK client.

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

type HTTPTokenExtractor func(*http.Request) (string, bool)

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

func (v *HybridVerifier) Authenticate(ctx context.Context, token string) (*Principal, error)

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.

func (*HybridVerifier) Warm

func (v *HybridVerifier) Warm(ctx context.Context) error

Warm fetches local JWKS immediately. Remote verification stays lazy.

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

func (v *LocalVerifier) Authenticate(ctx context.Context, token string) (*Principal, error)

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.

func (*LocalVerifier) Warm

func (v *LocalVerifier) Warm(ctx context.Context) error

Warm fetches JWKS immediately so startup can fail before serving traffic.

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
	Claims      Claims
}

Principal is the resource-server view of an authenticated IAM subject.

func PrincipalFrom

func PrincipalFrom(ctx context.Context) (*Principal, bool)

PrincipalFrom returns the principal stored by SDK HTTP middleware or gRPC interceptors.

func (*Principal) HasAMR added in v1.1.0

func (p *Principal) HasAMR(method string) bool

HasAMR reports whether the principal authenticated with the given method (e.g. "pwd", "otp", "webauthn").

func (*Principal) HasAllScopes added in v1.1.0

func (p *Principal) HasAllScopes(scopes ...string) bool

HasAllScopes reports whether the principal holds every one of scopes.

func (*Principal) HasAnyScope added in v1.1.0

func (p *Principal) HasAnyScope(scopes ...string) bool

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

func (p *Principal) HasScope(scope string) bool

HasScope reports whether the principal was granted scope.

func (*Principal) MeetsAAL added in v1.1.0

func (p *Principal) MeetsAAL(min int) bool

MeetsAAL reports whether the principal's authenticator assurance level is at least min (e.g. MeetsAAL(2) requires a step-up/MFA session).

type Refresher

type Refresher interface {
	Refresh(ctx context.Context) error
}

Refresher forces an authenticator to refresh cached verification state.

type ValidationMode

type ValidationMode string

ValidationMode selects how resource-server tokens are verified.

const (
	// ValidationModeRemote calls IAM /v1/tokens/verify for every token.
	ValidationModeRemote ValidationMode = "remote"
	// ValidationModeLocal verifies JWTs in-process using IAM's public JWKS.
	ValidationModeLocal ValidationMode = "local"
	// ValidationModeHybrid verifies locally first and falls back to remote verify
	// when local verification cannot authenticate the token.
	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

func (v *Verifier) Authenticate(ctx context.Context, token string) (*Principal, error)

Authenticate verifies token and returns a Principal on success.

func (*Verifier) Introspect

func (v *Verifier) Introspect(ctx context.Context, token string) (*VerifyResult, error)

Introspect verifies token activity via IAM /v1/tokens/introspect.

func (*Verifier) Middleware

func (v *Verifier) Middleware(next http.Handler) http.Handler

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

func (v *Verifier) Refresh(context.Context) error

Refresh is a no-op for remote verification; IAM holds verification state.

func (*Verifier) Verify

func (v *Verifier) Verify(ctx context.Context, token string) (*VerifyResult, error)

Verify verifies token via IAM /v1/tokens/verify.

func (*Verifier) Warm

func (v *Verifier) Warm(context.Context) error

Warm is a no-op for remote verification; IAM is contacted on Verify.

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

type VerifyResult struct {
	Valid     bool
	Error     string
	Claims    Claims
	Principal Principal
}

VerifyResult is IAM's token-verification response after decoding raw claims.

type Warmer

type Warmer interface {
	Warm(ctx context.Context) error
}

Warmer can verify that an authenticator's external dependencies are ready.

Directories

Path Synopsis
Package grpc contains IAM authentication interceptors for gRPC servers.
Package grpc contains IAM authentication interceptors for gRPC servers.

Jump to

Keyboard shortcuts

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