oidc

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 35 Imported by: 1 module, 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.

Documentation

Overview

Package oidc is the Grow Codes SDK for OIDC.

Create a client from the environment (GROW_OIDC_URL, GROW_OIDC_TOKEN, ...) or from a Config literal:

client, err := oidc.NewClientFromEnv()
if err != nil {
	return err
}
defer client.Close()
status, err := client.Health(ctx)

Every error is an *Error; compare codes with errors.Is against the Err* sentinels (errors.Is(err, oidc.ErrNotFound)). Credentials are wrapped in Secret and never appear in errors, hooks or logs.

OIDC is a trademark of its owner (OpenID Foundation (specification); any OpenID Connect provider); this package is not affiliated with or endorsed by it.

Index

Constants

View Source
const (
	DefaultConnectTimeout = 10 * time.Second
	DefaultRequestTimeout = 30 * time.Second
	DefaultTotalTimeout   = 120 * time.Second
)

Defaults of the common configuration fields (SPEC §2.2).

View Source
const (
	DefaultMaxRetries     = 3
	DefaultInitialBackoff = 100 * time.Millisecond
	DefaultMaxBackoff     = 10 * time.Second
	DefaultMultiplier     = 2.0
	DefaultMaxRetryAfter  = 60 * time.Second
)

Retry policy defaults (SPEC §2.3).

View Source
const (
	// DefaultClockSkew is the tolerance applied to exp and nbf.
	DefaultClockSkew = 60 * time.Second
	// DefaultJWKSCacheTTL is how long a fetched JWKS is used before it is refetched.
	DefaultJWKSCacheTTL = 10 * time.Minute
	// DefaultJWKSRefreshCooldown is the minimum interval between two refetches caused by an unknown kid.
	DefaultJWKSRefreshCooldown = 30 * time.Second
	// DefaultHTTPTimeout bounds discovery and JWKS requests.
	DefaultHTTPTimeout = 10 * time.Second
	// DefaultRolesClaim is the claim that holds the roles.
	DefaultRolesClaim = "roles"
)

Defaults of a Verifier.

View Source
const (
	RS256 = "RS256" // RSASSA-PKCS1-v1_5 with SHA-256
	RS384 = "RS384" // RSASSA-PKCS1-v1_5 with SHA-384
	RS512 = "RS512" // RSASSA-PKCS1-v1_5 with SHA-512
	PS256 = "PS256" // RSASSA-PSS with SHA-256
	PS384 = "PS384" // RSASSA-PSS with SHA-384
	PS512 = "PS512" // RSASSA-PSS with SHA-512
	ES256 = "ES256" // ECDSA P-256 with SHA-256
	ES384 = "ES384" // ECDSA P-384 with SHA-384
	ES512 = "ES512" // ECDSA P-521 with SHA-512
	EdDSA = "EdDSA" // Ed25519
)

Supported signing algorithms (asymmetric only; "none" and HMAC are never accepted).

View Source
const DefaultURL = "http://127.0.0.1:8000"

DefaultURL is the default endpoint of OIDC.

View Source
const DiscoveryPath = ".well-known/openid-configuration"

DiscoveryPath is the discovery document path, relative to the provider URL (realm prefixes such as Keycloak's are kept).

View Source
const EnvPrefix = "GROW_OIDC_"

EnvPrefix is the prefix of this package's environment variables.

View Source
const Redacted = "[REDACTED]"

Redacted replaces every sensitive value.

View Source
const UserAgent = "grow-codes-oidc/" + Version + " (go)"

UserAgent is the standard User-Agent of this package.

View Source
const Version = "0.1.2" // x-release-please-version

Version is the package version (updated by release-please).

Variables

View Source
var (
	ErrConfig           = &Error{Code: ErrorCodeConfig, Message: "configuration error"}
	ErrAuthentication   = &Error{Code: ErrorCodeAuthentication, Message: "authentication failed"}
	ErrPermissionDenied = &Error{Code: ErrorCodePermissionDenied, Message: "permission denied"}
	ErrNotFound         = &Error{Code: ErrorCodeNotFound, Message: "not found"}
	ErrConflict         = &Error{Code: ErrorCodeConflict, Message: "conflict"}
	ErrRateLimited      = &Error{Code: ErrorCodeRateLimited, Message: "rate limited", Retryable: true}
	ErrValidation       = &Error{Code: ErrorCodeValidation, Message: "validation failed"}
	ErrUnavailable      = &Error{Code: ErrorCodeUnavailable, Message: "service unavailable", Retryable: true}
	ErrTimeout          = &Error{Code: ErrorCodeTimeout, Message: "timeout", Retryable: true}
	ErrUnsupported      = &Error{Code: ErrorCodeUnsupported, Message: "unsupported"}
	ErrCancelled        = &Error{Code: ErrorCodeCancelled, Message: "cancelled"}
)

Sentinels for errors.Is; (*Error).Is compares codes only.

View Source
var DefaultAlgorithms = []string{RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512, EdDSA}

DefaultAlgorithms is the default algorithm allow-list: every supported algorithm.

View Source
var DefaultSensitiveFields = []string{
	"password", "passwd", "secret", "token", "authorization", "cookie", "api_key", "apikey", "api-key",
	"access_key", "private_key", "client_secret", "credential", "session", "signature",
}

DefaultSensitiveFields are the case-insensitive substrings that mark a field or query parameter name as sensitive.

Functions

func BearerToken

func BearerToken(r *http.Request) string

BearerToken returns the bearer token of the Authorization header ("" when there is none). The scheme is matched case-insensitively.

func ClaimAt

func ClaimAt(claims map[string]any, path string) (any, bool)

ClaimAt returns the value at a claim path: a claim name ("roles") or a dotted path into nested objects ("realm_access.roles"). An exact top-level match wins, so claim names containing dots ("https://example.com/roles") keep working.

func ContextError

func ContextError(operation string, err error) error

ContextError maps a context error to CANCELLED (context.Canceled) or TIMEOUT (context.DeadlineExceeded); errors.Is(err, context.Canceled) stays true. It returns nil when err is nil and passes *Error values through.

func ExtractRoles

func ExtractRoles(claims map[string]any, rolesClaim string) []string

ExtractRoles returns the role names of the claim at rolesClaim (default "roles"): a string is split on commas and whitespace; an array yields each string, or each object's name (Casdoor), code, role or value; anything else yields no roles. Duplicates are removed.

func HasAnyRole

func HasAnyRole(have, required []string) bool

HasAnyRole reports whether have contains at least one of required (case-insensitive). An empty required list means any authenticated user.

func IsSensitiveField

func IsSensitiveField(name string, extraKeys ...string) bool

IsSensitiveField reports whether a field or query name is sensitive. extraKeys are additional case-insensitive substrings.

func IsSensitiveHeader

func IsSensitiveHeader(name string) bool

IsSensitiveHeader reports whether a header name carries credentials.

func ParseBool

func ParseBool(s string) (bool, error)

ParseBool accepts true/false/1/0/yes/no/on/off (case-insensitive).

func ParseDuration

func ParseDuration(s string) (time.Duration, error)

ParseDuration accepts integer milliseconds ("1500") or Go-style units ("500ms", "10s", "2m", "1h", "1m30s").

func ParseRetryAfter

func ParseRetryAfter(value string, now time.Time) (time.Duration, bool)

ParseRetryAfter parses a Retry-After header (delta seconds or HTTP-date).

func PollUntil

func PollUntil[T any](ctx context.Context, operation string, timeout, interval time.Duration,
	fn func(ctx context.Context) (T, bool, error),
) (T, error)

PollUntil calls fn every interval until it reports done, the timeout passes (TIMEOUT error wrapping the last error) or ctx is cancelled (CANCELLED). Retryable errors from fn keep the poll going; other errors are returned at once.

func RedactFields

func RedactFields(m map[string]any, extraKeys ...string) map[string]any

RedactFields returns a deep copy of m with sensitive values replaced, recursing into nested maps and slices.

func RedactHeaderMap

func RedactHeaderMap(h map[string]string) map[string]string

RedactHeaderMap is RedactHeaders for a plain map.

func RedactHeaders

func RedactHeaders(h http.Header) http.Header

RedactHeaders returns a copy of h with sensitive header values replaced.

func RedactText

func RedactText(text string, knownSecrets []string) string

RedactText replaces every known secret value (length ≥ 4) in text.

func RedactURL

func RedactURL(raw string) string

RedactURL removes user info and replaces every query value with Redacted when its name is sensitive. Unparsable input is fully redacted.

func RelativeEndpoint

func RelativeEndpoint(base, endpoint string) string

RelativeEndpoint returns an endpoint's path relative to the provider URL: the part after the provider URL when the endpoint starts with it (keeps realm prefixes out), else its path and query.

func RequireRoles

func RequireRoles(roles ...string) func(http.Handler) http.Handler

RequireRoles returns middleware (placed after Middleware) that answers 401 without a user and 403 unless the user has at least one of roles (case-insensitive). No roles = any user.

func WithUser

func WithUser(ctx context.Context, user *User) context.Context

WithUser returns a copy of ctx carrying user (used by Middleware; handy in tests).

Types

type Client

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

Client is the OIDC client. It is safe for concurrent use.

func NewClient

func NewClient(cfg Config) (*Client, error)

NewClient validates cfg and returns a client.

func NewClientFromEnv

func NewClientFromEnv() (*Client, error)

NewClientFromEnv builds a client from the environment (see ConfigFromEnv).

func (*Client) Close

func (c *Client) Close() error

Close releases resources. It is idempotent.

func (*Client) Config

func (c *Client) Config() Config

Config returns the effective configuration.

func (*Client) Health

func (c *Client) Health(ctx context.Context) (HealthStatus, error)

Health checks liveness without credentials: GET <url>/.well-known/openid-configuration. It reports an unreachable or unhealthy provider in the result; it fails only for CANCELLED and CONFIG.

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) (time.Duration, error)

Ping makes an authenticated round trip with the configured access token (Token): GET the provider's userinfo_endpoint from discovery. It returns the latency (AUTHENTICATION error on a rejected token, UNSUPPORTED when the provider has no userinfo endpoint).

func (*Client) ServerVersion

func (c *Client) ServerVersion(ctx context.Context) (string, error)

ServerVersion is UNSUPPORTED: OpenID Connect providers expose no version (CANCELLED once closed).

type CommonConfig

type CommonConfig struct {
	// URL is the endpoint base URL.
	URL string
	// ConnectTimeout bounds connection setup (default 10 s).
	ConnectTimeout time.Duration
	// RequestTimeout bounds one attempt including the body (default 30 s).
	RequestTimeout time.Duration
	// TotalTimeout bounds a whole call including retries and backoff (default 120 s).
	TotalTimeout time.Duration
	// Retry is the retry policy; nil means DefaultRetryPolicy().
	Retry *RetryPolicy
	// TLS settings.
	TLS TLSConfig
	// Proxy is an explicit proxy URL. Environment proxies are ignored.
	Proxy string
	// Headers are extra request headers.
	Headers map[string]string
	// UserAgentSuffix is appended after the standard User-Agent.
	UserAgentSuffix string
	// Hooks observe every attempt.
	Hooks *Hooks
	// Logger receives debug output; nil discards.
	Logger *slog.Logger
}

CommonConfig holds the fields every service config shares. Service configs embed it. Zero values mean "use the default".

type Config

type Config struct {
	CommonConfig

	// Token authenticates requests (env GROW_OIDC_TOKEN).
	Token Secret
}

Config configures a Client. Build it with a struct literal or ConfigFromEnv; zero values mean "use the default". Call Validate to check it.

func ConfigFromEnv

func ConfigFromEnv() (Config, error)

ConfigFromEnv reads the configuration from the process environment.

func ConfigFromEnvWith

func ConfigFromEnvWith(explicit Config, env map[string]string) (Config, error)

ConfigFromEnvWith resolves explicit values > GROW_OIDC_* > vendor variables > defaults. env replaces the process environment when non-nil.

func (Config) GoString

func (c Config) GoString() string

GoString renders the configuration with every credential redacted.

func (Config) MarshalJSON

func (c Config) MarshalJSON() ([]byte, error)

MarshalJSON encodes the configuration with credentials redacted, the same way String() does:

  • URL and Proxy lose user info, and sensitive query values become "[REDACTED]";
  • sensitive Headers values (Authorization, Cookie, *token*, ...) become "[REDACTED]";
  • Secret fields encode as "[REDACTED]";
  • Hooks and Logger (code, not data) encode as null.

The service's own fields are encoded as declared, with the same rules applied by name: string fields named like a URL or endpoint (…URL, …Endpoint, …Addr) lose user info and sensitive query values, string fields with a sensitive name (…Password, …Token, …APIKey; not …Path, …File, …Name, …ID) become "[REDACTED]", map[string]string fields named …Headers get sensitive values replaced, and function, channel and interface fields (callbacks, credential providers, SDK clients) encode as null.

Fields are encoded like encoding/json would (declaration order, embedded structs inlined, json tag names, "-" and omitempty), except that function and channel fields encode as null instead of failing the whole call.

func (Config) String

func (c Config) String() string

String renders the configuration with every credential redacted.

func (Config) Validate

func (c Config) Validate() error

Validate checks the configuration and returns a CONFIG error.

type EnvReader

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

EnvReader reads configuration variables: GROW_<KEY>_<NAME> first, then the vendor variables in the order given. Empty values count as unset. A present but invalid value yields a CONFIG error naming the variable, never its value.

func NewEnvReader

func NewEnvReader(prefix string, env map[string]string) *EnvReader

NewEnvReader returns a reader over env. A nil env reads the process environment.

func (*EnvReader) Bool

func (r *EnvReader) Bool(name string, vendorNames ...string) (value, ok bool, err error)

Bool parses a boolean variable (true/false/1/0/yes/no/on/off, case-insensitive).

func (*EnvReader) Duration

func (r *EnvReader) Duration(name string, vendorNames ...string) (time.Duration, bool, error)

Duration parses a duration variable (integer milliseconds or Go units such as 1m30s).

func (*EnvReader) Int

func (r *EnvReader) Int(name string, vendorNames ...string) (int, bool, error)

Int parses an integer variable.

func (*EnvReader) String

func (r *EnvReader) String(name string, vendorNames ...string) (string, bool)

String returns the value of GROW_<KEY>_<name> or the first set vendor variable.

type Error

type Error struct {
	// Code is the canonical error code.
	Code ErrorCode
	// Message is human text in the form "<operation>: <reason> (HTTP <status>)".
	// It never contains secrets, tokens, request bodies or unfiltered response bodies.
	Message string
	// HTTPStatus is the HTTP status when the error came from a response (0 otherwise).
	HTTPStatus int
	// RequestID is the vendor request id header when present.
	RequestID string
	// Retryable reports whether retrying the same call may succeed.
	Retryable bool
	// RetryAfter is the server-requested wait (RATE_LIMITED / UNAVAILABLE), 0 when unknown.
	RetryAfter time.Duration
	// Err is the underlying cause (already redacted).
	Err error
}

Error is the single error type returned by this package. Compare codes with errors.Is against the Err* sentinels, or extract it with errors.As.

func ConfigError

func ConfigError(message string) *Error

ConfigError returns a CONFIG error. The message must never contain a value.

func NewError

func NewError(code ErrorCode, message string, cause error) *Error

NewError returns an *Error with the code's default retryability.

func NotFoundError

func NotFoundError(operation, reason string) *Error

NotFoundError returns a NOT_FOUND error.

func StatusError

func StatusError(operation string, status int, requestID, vendorText string, knownSecrets []string) *Error

StatusError builds the error for an HTTP response. vendorText is the error text extracted from the body; it is redacted with knownSecrets and truncated.

func UnsupportedError

func UnsupportedError(operation, reason string) *Error

UnsupportedError returns an UNSUPPORTED error.

func ValidationError

func ValidationError(operation, reason string) *Error

ValidationError returns a VALIDATION error for bad input caught client side.

func (*Error) Error

func (e *Error) Error() string

Error implements error.

func (*Error) Is

func (e *Error) Is(target error) bool

Is reports whether target is an *Error with the same code.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the cause so errors.Is(err, context.Canceled) keeps working.

type ErrorCode

type ErrorCode string

ErrorCode is the canonical, language-independent error code (wire value).

const (
	ErrorCodeConfig           ErrorCode = "CONFIG"
	ErrorCodeAuthentication   ErrorCode = "AUTHENTICATION"
	ErrorCodePermissionDenied ErrorCode = "PERMISSION_DENIED"
	ErrorCodeNotFound         ErrorCode = "NOT_FOUND"
	ErrorCodeConflict         ErrorCode = "CONFLICT"
	ErrorCodeRateLimited      ErrorCode = "RATE_LIMITED"
	ErrorCodeValidation       ErrorCode = "VALIDATION"
	ErrorCodeUnavailable      ErrorCode = "UNAVAILABLE"
	ErrorCodeTimeout          ErrorCode = "TIMEOUT"
	ErrorCodeUnsupported      ErrorCode = "UNSUPPORTED"
	ErrorCodeCancelled        ErrorCode = "CANCELLED"
)

Canonical error codes (SPEC §2.1).

func CodeForStatus

func CodeForStatus(status int) ErrorCode

CodeForStatus maps an HTTP status to a canonical code (SPEC §2.1).

func CodeOf

func CodeOf(err error) ErrorCode

CodeOf returns the code of err when it is (or wraps) an *Error, or "" otherwise.

func (ErrorCode) Retryable

func (c ErrorCode) Retryable() bool

Retryable reports whether errors with this code are retryable by default.

type ErrorInfo

type ErrorInfo struct {
	Method    string
	URL       string
	Err       error
	Attempt   int
	WillRetry bool
}

ErrorInfo describes a failed attempt.

type HealthStatus

type HealthStatus struct {
	// Healthy is true when the service answered and reports itself usable.
	Healthy bool `json:"healthy"`
	// Status is "ok", "degraded", "unhealthy", "unreachable" or the vendor's word.
	Status string `json:"status"`
	// Details holds extra vendor fields as strings.
	Details map[string]string `json:"details"`
}

HealthStatus is the result of Client.Health.

type Hooks

type Hooks struct {
	OnRequest  func(RequestInfo)
	OnResponse func(ResponseInfo)
	OnError    func(ErrorInfo)
}

Hooks observe every HTTP attempt. URLs and headers are redacted. Panics in hooks are recovered and ignored.

type Options

type Options struct {
	// Issuer is the expected "iss" (exact match, except that trailing slashes on either side are
	// ignored); discovery uses <Issuer without trailing slashes>/.well-known/openid-configuration.
	Issuer string
	// Audience is the expected "aud" (the token's aud must contain it).
	Audience string
	// JWKSURL skips discovery when set.
	JWKSURL string
	// RolesClaim is the claim (or dotted path such as realm_access.roles) with the roles. Default "roles".
	RolesClaim string
	// Algorithms is the allow-list, a subset of RS256/384/512, PS256/384/512, ES256/384/512, EdDSA.
	// Default all of them.
	Algorithms []string
	// ClockSkew is the exp/nbf tolerance. Default 60 s; a negative value means no tolerance.
	ClockSkew time.Duration
	// JWKSCacheTTL is the JWKS cache lifetime. Default 10 min.
	JWKSCacheTTL time.Duration
	// JWKSRefreshCooldown is the minimum interval between unknown-kid refetches. Default 30 s; negative = none.
	JWKSRefreshCooldown time.Duration
	// HTTPClient fetches discovery and the JWKS. Default: a client with DefaultHTTPTimeout.
	HTTPClient *http.Client
	// Now is the clock (tests). Default time.Now.
	Now func() time.Time
}

Options configures a Verifier. Zero values select the defaults.

type RequestInfo

type RequestInfo struct {
	Method  string
	URL     string
	Headers http.Header
	// Attempt starts at 1.
	Attempt int
}

RequestInfo describes an attempt that is about to be sent.

type ResponseInfo

type ResponseInfo struct {
	Method    string
	URL       string
	Status    int
	Duration  time.Duration
	Attempt   int
	RequestID string
}

ResponseInfo describes a received response.

type RetryPolicy

type RetryPolicy struct {
	// MaxRetries is the number of retries after the first attempt.
	MaxRetries int
	// InitialBackoff is the backoff cap of the first retry.
	InitialBackoff time.Duration
	// MaxBackoff caps every backoff.
	MaxBackoff time.Duration
	// Multiplier grows the cap per retry.
	Multiplier float64
	// MaxRetryAfter is the longest server-requested wait honoured.
	MaxRetryAfter time.Duration
	// Rand returns a number in [0, 1); nil uses math/rand/v2. Inject it in tests.
	Rand func() float64 `json:"-"`
}

RetryPolicy controls retries. Start from DefaultRetryPolicy(); zero durations and multiplier fall back to the defaults, MaxRetries is used as is (0 disables retries).

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns the default policy.

func (RetryPolicy) Backoff

func (p RetryPolicy) Backoff(n int) time.Duration

Backoff returns the full-jitter backoff for retry n: random(0, BackoffCap(n)).

func (RetryPolicy) BackoffCap

func (p RetryPolicy) BackoffCap(n int) time.Duration

BackoffCap returns min(MaxBackoff, InitialBackoff * Multiplier^n) for retry n (0-based).

type Secret

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

Secret wraps a credential (token, password, key). Every printed, logged or JSON-encoded form is "[REDACTED]"; Reveal returns the value.

func NewSecret

func NewSecret(value string) Secret

NewSecret wraps value.

func (Secret) Format

func (s Secret) Format(f fmt.State, _ rune)

Format implements fmt.Formatter so every verb prints the redacted form.

func (Secret) GoString

func (s Secret) GoString() string

GoString implements fmt.GoStringer.

func (Secret) IsZero

func (s Secret) IsZero() bool

IsZero reports whether the secret is empty.

func (Secret) LogValue

func (s Secret) LogValue() slog.Value

LogValue implements slog.LogValuer.

func (Secret) MarshalJSON

func (s Secret) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Secret) MarshalText

func (s Secret) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Secret) Reveal

func (s Secret) Reveal() string

Reveal returns the wrapped value.

func (Secret) String

func (s Secret) String() string

String implements fmt.Stringer.

type TLSConfig

type TLSConfig struct {
	// CACertPath is a PEM bundle of trusted CAs (env CA_CERT).
	CACertPath string
	// CACertPEM is an inline PEM bundle of trusted CAs.
	CACertPEM string
	// ClientCertPath and ClientKeyPath enable mutual TLS; both or neither.
	ClientCertPath string
	ClientKeyPath  string
	// InsecureSkipVerify disables certificate checks (tests only; logs a warning once).
	InsecureSkipVerify bool
}

TLSConfig configures TLS for the HTTP transport.

type User

type User struct {
	// Sub is the "sub" claim.
	Sub string `json:"sub"`
	// Email is the "email" claim ("" when absent).
	Email string `json:"email,omitempty"`
	// Name is the "name" claim, else "preferred_username" ("" when absent).
	Name string `json:"name,omitempty"`
	// Roles are the role names from the roles claim.
	Roles []string `json:"roles"`
	// Claims holds every claim of the token (numbers as json.Number).
	Claims map[string]any `json:"claims"`
}

User is the authenticated user of a verified access token.

func UserFrom

func UserFrom(ctx context.Context) (*User, bool)

UserFrom returns the user stored by Middleware.

func (*User) HasRole

func (u *User) HasRole(roles ...string) bool

HasRole reports whether the user has at least one of roles (case-insensitive).

type VendorEnv

type VendorEnv struct {
	URL                []string
	CACert             []string
	ClientCert         []string
	ClientKey          []string
	InsecureSkipVerify []string
	Proxy              []string
}

VendorEnv lists vendor variable names consulted after GROW_<KEY>_* (in order).

type Verifier

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

Verifier verifies OIDC access tokens (JWT) against the issuer's JWKS. It is safe for concurrent use.

It checks the signature (RS256/384/512, PS256/384/512, ES256/384/512, EdDSA allow-list; the key must match the algorithm: RSA for RS and PS, the EC curve P-256/P-384/P-521 for ES256/384/512, Ed25519 for EdDSA), iss (exact, trailing slashes ignored), aud (contains), exp (required), nbf and sub with a clock skew (default 60 s). Keys come from JWKSURL or OIDC discovery, are cached (default 10 min) and refetched when a token names an unknown kid (key rotation, at most once per cooldown).

Errors are *Error: ErrAuthentication for every invalid token (the message names the failed check, never the token), ErrUnavailable when discovery or the JWKS cannot be fetched, ErrConfig for invalid options.

func FromEnv

func FromEnv(ctx context.Context) (*Verifier, error)

FromEnv builds a Verifier from GROW_AUTH_ISSUER (required), GROW_AUTH_AUDIENCE (default GROW_AUTH_CLIENT_ID), GROW_AUTH_JWKS_URL, GROW_AUTH_ROLES_CLAIM (default "roles") and GROW_AUTH_CLOCK_SKEW (duration, default 60s). ctx is reserved for future discovery at startup.

func FromEnvWith

func FromEnvWith(_ context.Context, overrides Options, getenv func(string) string) (*Verifier, error)

FromEnvWith is FromEnv with explicit option overrides (non-zero fields win) and a lookup function (os.Getenv, or a map lookup in tests).

func New

func New(opts Options) (*Verifier, error)

New validates opts and returns a Verifier. No network call is made.

func (*Verifier) Audience

func (v *Verifier) Audience() string

Audience returns the expected audience.

func (*Verifier) ClearCache

func (v *Verifier) ClearCache()

ClearCache drops the cached JWKS so the next verification refetches it.

func (*Verifier) ClockSkew

func (v *Verifier) ClockSkew() time.Duration

ClockSkew returns the exp/nbf tolerance.

func (*Verifier) Issuer

func (v *Verifier) Issuer() string

Issuer returns the expected issuer.

func (*Verifier) Middleware

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

Middleware verifies the bearer token of every request and stores the user in the request context (UserFrom). Missing or invalid token → 401, JWKS/discovery unreachable → 503. The response never says why a token was rejected.

func (*Verifier) OptionalMiddleware

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

OptionalMiddleware is Middleware that lets requests without a token through anonymously (an invalid token is still 401).

func (*Verifier) RolesClaim

func (v *Verifier) RolesClaim() string

RolesClaim returns the roles claim path.

func (*Verifier) Verify

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

Verify verifies a raw JWT access token and returns its user.

Directories

Path Synopsis
internal
tools/covergate command
Command covergate enforces the statement coverage gate on a Go cover profile and writes coverage/summary.json in the shared sdk-kit format:
Command covergate enforces the statement coverage gate on a Go cover profile and writes coverage/summary.json in the shared sdk-kit format:
Package oidctest is a local fake OpenID provider for tests: it serves /.well-known/openid-configuration and /jwks over httptest, mints signed tokens and rotates keys.
Package oidctest is a local fake OpenID provider for tests: it serves /.well-known/openid-configuration and /jwks over httptest, mints signed tokens and rotates keys.

Jump to

Keyboard shortcuts

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