sdk

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2026 License: MIT Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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")
)

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 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 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.

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