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
- Variables
- func BearerToken(r *http.Request) string
- func ClaimAt(claims map[string]any, path string) (any, bool)
- func ContextError(operation string, err error) error
- func ExtractRoles(claims map[string]any, rolesClaim string) []string
- func HasAnyRole(have, required []string) bool
- func IsSensitiveField(name string, extraKeys ...string) bool
- func IsSensitiveHeader(name string) bool
- func ParseBool(s string) (bool, error)
- func ParseDuration(s string) (time.Duration, error)
- func ParseRetryAfter(value string, now time.Time) (time.Duration, bool)
- func PollUntil[T any](ctx context.Context, operation string, timeout, interval time.Duration, ...) (T, error)
- func RedactFields(m map[string]any, extraKeys ...string) map[string]any
- func RedactHeaderMap(h map[string]string) map[string]string
- func RedactHeaders(h http.Header) http.Header
- func RedactText(text string, knownSecrets []string) string
- func RedactURL(raw string) string
- func RelativeEndpoint(base, endpoint string) string
- func RequireRoles(roles ...string) func(http.Handler) http.Handler
- func WithUser(ctx context.Context, user *User) context.Context
- type Client
- type CommonConfig
- type Config
- type EnvReader
- func (r *EnvReader) Bool(name string, vendorNames ...string) (value, ok bool, err error)
- func (r *EnvReader) Duration(name string, vendorNames ...string) (time.Duration, bool, error)
- func (r *EnvReader) Int(name string, vendorNames ...string) (int, bool, error)
- func (r *EnvReader) String(name string, vendorNames ...string) (string, bool)
- type Error
- func ConfigError(message string) *Error
- func NewError(code ErrorCode, message string, cause error) *Error
- func NotFoundError(operation, reason string) *Error
- func StatusError(operation string, status int, requestID, vendorText string, ...) *Error
- func UnsupportedError(operation, reason string) *Error
- func ValidationError(operation, reason string) *Error
- type ErrorCode
- type ErrorInfo
- type HealthStatus
- type Hooks
- type Options
- type RequestInfo
- type ResponseInfo
- type RetryPolicy
- type Secret
- func (s Secret) Format(f fmt.State, _ rune)
- func (s Secret) GoString() string
- func (s Secret) IsZero() bool
- func (s Secret) LogValue() slog.Value
- func (s Secret) MarshalJSON() ([]byte, error)
- func (s Secret) MarshalText() ([]byte, error)
- func (s Secret) Reveal() string
- func (s Secret) String() string
- type TLSConfig
- type User
- type VendorEnv
- type Verifier
- func (v *Verifier) Audience() string
- func (v *Verifier) ClearCache()
- func (v *Verifier) ClockSkew() time.Duration
- func (v *Verifier) Issuer() string
- func (v *Verifier) Middleware(next http.Handler) http.Handler
- func (v *Verifier) OptionalMiddleware(next http.Handler) http.Handler
- func (v *Verifier) RolesClaim() string
- func (v *Verifier) Verify(ctx context.Context, token string) (*User, error)
Constants ¶
const ( DefaultConnectTimeout = 10 * time.Second DefaultRequestTimeout = 30 * time.Second DefaultTotalTimeout = 120 * time.Second )
Defaults of the common configuration fields (SPEC §2.2).
const ( DefaultMaxRetries = 3 DefaultInitialBackoff = 100 * time.Millisecond DefaultMaxBackoff = 10 * time.Second DefaultMultiplier = 2.0 DefaultMaxRetryAfter = 60 * time.Second )
Retry policy defaults (SPEC §2.3).
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.
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).
const DefaultURL = "http://127.0.0.1:8000"
DefaultURL is the default endpoint of OIDC.
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).
const EnvPrefix = "GROW_OIDC_"
EnvPrefix is the prefix of this package's environment variables.
const Redacted = "[REDACTED]"
Redacted replaces every sensitive value.
const UserAgent = "grow-codes-oidc/" + Version + " (go)"
UserAgent is the standard User-Agent of this package.
const Version = "0.1.2" // x-release-please-version
Version is the package version (updated by release-please).
Variables ¶
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"} 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.
var DefaultAlgorithms = []string{RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512, EdDSA}
DefaultAlgorithms is the default algorithm allow-list: every supported algorithm.
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 ¶
BearerToken returns the bearer token of the Authorization header ("" when there is none). The scheme is matched case-insensitively.
func ClaimAt ¶
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 ¶
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 ¶
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 ¶
HasAnyRole reports whether have contains at least one of required (case-insensitive). An empty required list means any authenticated user.
func IsSensitiveField ¶
IsSensitiveField reports whether a field or query name is sensitive. extraKeys are additional case-insensitive substrings.
func IsSensitiveHeader ¶
IsSensitiveHeader reports whether a header name carries credentials.
func ParseDuration ¶
ParseDuration accepts integer milliseconds ("1500") or Go-style units ("500ms", "10s", "2m", "1h", "1m30s").
func ParseRetryAfter ¶
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 ¶
RedactFields returns a deep copy of m with sensitive values replaced, recursing into nested maps and slices.
func RedactHeaderMap ¶
RedactHeaderMap is RedactHeaders for a plain map.
func RedactHeaders ¶
RedactHeaders returns a copy of h with sensitive header values replaced.
func RedactText ¶
RedactText replaces every known secret value (length ≥ 4) in text.
func RedactURL ¶
RedactURL removes user info and replaces every query value with Redacted when its name is sensitive. Unparsable input is fully redacted.
func RelativeEndpoint ¶
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 ¶
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.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the OIDC client. It is safe for concurrent use.
func NewClientFromEnv ¶
NewClientFromEnv builds a client from the environment (see ConfigFromEnv).
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.
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 ¶
ConfigFromEnv reads the configuration from the process environment.
func ConfigFromEnvWith ¶
ConfigFromEnvWith resolves explicit values > GROW_OIDC_* > vendor variables > defaults. env replaces the process environment when non-nil.
func (Config) MarshalJSON ¶
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.
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 ¶
NewEnvReader returns a reader over env. A nil env reads the process environment.
func (*EnvReader) Bool ¶
Bool parses a boolean variable (true/false/1/0/yes/no/on/off, case-insensitive).
func (*EnvReader) Duration ¶
Duration parses a duration variable (integer milliseconds or Go units such as 1m30s).
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 ¶
ConfigError returns a CONFIG error. The message must never contain a value.
func NotFoundError ¶
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 ¶
UnsupportedError returns an UNSUPPORTED error.
func ValidationError ¶
ValidationError returns a VALIDATION error for bad input caught client side.
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" ErrorCodeTimeout ErrorCode = "TIMEOUT" ErrorCodeUnsupported ErrorCode = "UNSUPPORTED" ErrorCodeCancelled ErrorCode = "CANCELLED" )
Canonical error codes (SPEC §2.1).
func CodeForStatus ¶
CodeForStatus maps an HTTP status to a canonical code (SPEC §2.1).
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 (Secret) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (Secret) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
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.
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 ¶
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 (*Verifier) ClearCache ¶
func (v *Verifier) ClearCache()
ClearCache drops the cached JWKS so the next verification refetches it.
func (*Verifier) Middleware ¶
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 ¶
OptionalMiddleware is Middleware that lets requests without a token through anonymously (an invalid token is still 401).
func (*Verifier) RolesClaim ¶
RolesClaim returns the roles claim path.
Source Files
¶
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. |