oidc

package
v0.316.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: MIT Imports: 26 Imported by: 0 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.

Documentation

Overview

Package oidc is muster's OpenID Connect RELYING PARTY: muster signing people in through an outside identity provider ("Sign in with <provider>", docs/auth.md#single-sign-on). It is the protocol half only — discovery, the authorization-code flow with PKCE, the id_token check, userinfo, refresh and revocation. What a verified identity is allowed to become (an account, a session, a link) is internal/api's (oidc_signin.go), and where the link is stored is internal/users' (identities.go).

🔴 THE ISSUER IS PINNED, EXACTLY. The configured issuer is compared byte for byte with the discovery document's `issuer` and with every id_token's `iss`. No trailing-slash forgiveness, no case folding: a provider that answers with another issuer is a different provider (OIDC Discovery §4.3, OIDC Core §3.1.3.7 step 2). Discover refuses the mismatch (ErrIssuerMismatch), and the server (internal/cmd/server) refuses to boot on it.

🔴 ONLY ASYMMETRIC SIGNATURES, AND THE ALGORITHM IS CHOSEN BY MUSTER. The id_token's `alg` must be one of SupportedAlgs (ES256, RS256) AND one the discovery document lists, and the key that checks it must carry the same key type. `none` and every HMAC algorithm are refused before anything is computed: with HS256 the client secret — which muster holds — would be the key, so anyone holding it could mint an identity.

No JWT library is used, for the reason internal/gotrue gives: the format accepted is two algorithms and a handful of claims.

Index

Constants

View Source
const HTTPTimeout = 15 * time.Second

HTTPTimeout bounds every call to the provider.

View Source
const KeySize = 32

KeySize is the length of the master key NewSealer takes: the connector store's key (MUSTER_CONNECTOR_ENCRYPTION_KEY), which the refresh-token key is derived from.

View Source
const Skew = 2 * time.Minute

Skew is the clock tolerance applied to exp, iat and auth_time.

Variables

View Source
var (
	ErrTokenMalformed = errors.New("oidc: malformed id_token")
	ErrTokenAlg       = errors.New("oidc: id_token algorithm is not accepted")
	ErrTokenKey       = errors.New("oidc: no provider key matches the id_token")
	ErrTokenSignature = errors.New("oidc: id_token signature does not verify")
	ErrTokenIssuer    = errors.New("oidc: id_token issuer is not the configured issuer")
	ErrTokenAudience  = errors.New("oidc: id_token audience is not this client")
	ErrTokenExpired   = errors.New("oidc: id_token expired")
	ErrTokenIssuedAt  = errors.New("oidc: id_token issued-at is missing or in the future")
	ErrTokenNonce     = errors.New("oidc: id_token nonce does not match this sign-in")
	ErrTokenSubject   = errors.New("oidc: id_token names no subject")
)

The id_token refusals. Each is its own value so a test can say which check refused (and a mutant that removes one check fails that check's own test).

View Source
var (
	// ErrIssuerMismatch: the discovery document names another issuer than the
	// one configured. A configuration error: muster refuses to boot on it.
	ErrIssuerMismatch = errors.New("oidc: the provider's discovery document names a different issuer")
	// ErrDiscovery: the discovery document could not be fetched or lacks what
	// muster needs (a transient failure is retried on the next use).
	ErrDiscovery = errors.New("oidc: discovery failed")
	// ErrNoIDToken: the token response carried no id_token. Refused: without
	// it nothing ties the code to the nonce this browser was given.
	ErrNoIDToken = errors.New("oidc: the token response has no id_token")
	// ErrInvalidGrant: the provider refused the code or the refresh token
	// (invalid_grant) — definitive, unlike a network failure.
	ErrInvalidGrant = errors.New("oidc: the provider refused the grant")
	// ErrUserInfoRefused: userinfo answered 401 or 403 to a token the
	// provider just issued — the account is banned, deleted or otherwise
	// refused there.
	ErrUserInfoRefused = errors.New("oidc: the provider refused userinfo for this token")
)

The refusals.

View Source
var DefaultScopes = []string{"openid", "profile", "email", "offline_access"}

DefaultScopes is what muster asks for: an id_token (openid), the profile and email claims, and a refresh token (offline_access), which the daily role re-check uses.

View Source
var ErrDecrypt = errors.New("oidc: the stored refresh token could not be decrypted with the configured key")

ErrDecrypt: a stored refresh token does not open with the configured key and its row's binding (another key, or a ciphertext moved to another row).

View Source
var SupportedAlgs = []string{"ES256", "RS256"}

SupportedAlgs are the id_token algorithms muster accepts, at most: the provider's discovery document narrows them further (usableAlgs).

Functions

func Challenge

func Challenge(verifier string) string

Challenge is the PKCE S256 challenge of verifier (RFC 7636 §4.2).

func RandomString

func RandomString(n int) (string, error)

RandomString is n random bytes, base64url without padding: a state, a nonce or a PKCE verifier (32 bytes gives the 43 characters RFC 7636 asks at least).

Types

type Config

type Config struct {
	// Issuer is the provider's issuer identifier, exactly as its discovery
	// document and its id_tokens spell it.
	Issuer       string
	ClientID     string
	ClientSecret string
	// RedirectURL is muster's callback, registered with the provider exactly.
	RedirectURL string
	// Scopes defaults to DefaultScopes.
	Scopes []string
	// HTTP is the client (nil: one with HTTPTimeout). It never follows a
	// redirect (noredirect): the token endpoint is sent the client secret.
	HTTP *http.Client
	// Now is the clock (nil: time.Now).
	Now func() time.Time
}

Config is one provider.

type Discovery

type Discovery struct {
	Issuer                string   `json:"issuer"`
	AuthorizationEndpoint string   `json:"authorization_endpoint"`
	TokenEndpoint         string   `json:"token_endpoint"`
	UserinfoEndpoint      string   `json:"userinfo_endpoint"`
	JWKSURI               string   `json:"jwks_uri"`
	RevocationEndpoint    string   `json:"revocation_endpoint"`
	IDTokenAlgs           []string `json:"id_token_signing_alg_values_supported"`
	CodeChallengeMethods  []string `json:"code_challenge_methods_supported"`
	TokenAuthMethods      []string `json:"token_endpoint_auth_methods_supported"`
}

Discovery is the part of the provider's discovery document muster reads.

type IDClaims

type IDClaims struct {
	Subject string
	// AuthTime is the provider's auth_time, zero when the token has none.
	AuthTime time.Time
	IssuedAt time.Time
}

IDClaims is what muster reads from a verified id_token.

type Provider

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

Provider is a discovered provider. Safe for concurrent use.

func New

func New(cfg Config) (*Provider, error)

New returns the provider for cfg without contacting it: Discover (or the first call that needs the document) fetches it.

func (*Provider) AuthCodeURL

func (p *Provider) AuthCodeURL(ctx context.Context, state, nonce, verifier string, reauth bool) (string, error)

AuthCodeURL is the authorization request this browser is sent to: the code flow, the state, the nonce and the PKCE S256 challenge of verifier. reauth also asks for a NEW authentication (max_age=0, OIDC Core §3.1.2.1): a provider that honours it makes the person enter a credential again and reports the new auth_time; one that ignores it is unaffected.

func (*Provider) ClientID

func (p *Provider) ClientID() string

ClientID is the configured client id.

func (*Provider) Discover

func (p *Provider) Discover(ctx context.Context) (Discovery, error)

Discover fetches and checks the discovery document, once: later calls return the cached one. ErrIssuerMismatch is permanent; any other failure is retried by a later call (no sooner than discoveryRetry).

func (*Provider) Exchange

func (p *Provider) Exchange(ctx context.Context, code, verifier string) (Tokens, error)

Exchange redeems an authorization code with its PKCE verifier. A response with no id_token is ErrNoIDToken (see its doc).

func (*Provider) Issuer

func (p *Provider) Issuer() string

Issuer is the configured issuer.

func (*Provider) Refresh

func (p *Provider) Refresh(ctx context.Context, refresh string) (Tokens, error)

Refresh exchanges a refresh token. The provider may rotate it: a non-empty Tokens.RefreshToken replaces the one sent.

func (*Provider) Revoke

func (p *Provider) Revoke(ctx context.Context, refresh string) error

Revoke revokes a refresh token at the provider (RFC 7009), best effort: a provider without a revocation endpoint is no error.

func (*Provider) UserInfo

func (p *Provider) UserInfo(ctx context.Context, accessToken string) (UserInfo, error)

UserInfo reads the userinfo endpoint with an access token. 401 and 403 are ErrUserInfoRefused.

func (*Provider) VerifyIDToken

func (p *Provider) VerifyIDToken(ctx context.Context, raw, nonce string) (IDClaims, error)

VerifyIDToken checks raw as OIDC Core §3.1.3.7 asks, in this order: the header's algorithm (one muster accepts and the provider lists), the signature against the provider's published key, then iss (exactly the configured issuer), aud (contains this client; azp, when there are several audiences, is this client), exp, iat, the subject and the nonce (exactly the one this browser's flow was given).

🔴 THE NONCE IS REQUIRED, NEVER "CHECKED IF PRESENT". A provider that drops it (one that keeps the code's nonce in a best-effort cache, say) yields a token that is refused here: nothing else ties the id_token to this browser's request.

type Sealer

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

Sealer encrypts the provider refresh tokens muster keeps for the daily role re-check: AES-256-GCM under a key derived (HKDF-SHA256) from the master key, a random nonce prepended, and the row's user, issuer and subject bound in as associated data — internal/credentials' construction.

🔴 THE BINDING IS THE ROW. A token copied onto another user's identity row (a bad UPDATE, a restore into the wrong place) does not open (ErrDecrypt), so it can never be used to re-check, and so keep enabled, someone else.

func NewSealer

func NewSealer(master []byte) (*Sealer, error)

NewSealer derives the sealer's key from master.

func (*Sealer) Open

func (s *Sealer) Open(user int64, issuer, subject string, blob []byte) (string, error)

Open decrypts a sealed token for the identity row (user, issuer, subject).

func (*Sealer) Seal

func (s *Sealer) Seal(user int64, issuer, subject, token string) ([]byte, error)

Seal encrypts token for the identity row (user, issuer, subject).

type Tokens

type Tokens struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	RefreshToken string `json:"refresh_token"`
	IDToken      string `json:"id_token"`
	ExpiresIn    int64  `json:"expires_in"`
}

Tokens is a token endpoint answer.

type UserInfo

type UserInfo struct {
	Subject           string `json:"sub"`
	Email             string `json:"email"`
	EmailVerified     bool   `json:"email_verified"`
	PreferredUsername string `json:"preferred_username"`
	Name              string `json:"name"`
	Raw               map[string]json.RawMessage
}

UserInfo is the userinfo response. Raw keeps every claim, so a configured roles claim other than "roles" can be read (Roles).

func (UserInfo) HasRole

func (u UserInfo) HasRole(claim, role string) bool

HasRole reports whether role is exactly one of the strings under claim.

func (UserInfo) Roles

func (u UserInfo) Roles(claim string) []string

Roles is the string array under claim name in the userinfo response, nil when it is absent or not an array of strings.

Directories

Path Synopsis
Package oidctest is an in-memory OpenID Connect provider for tests: an httptest server with discovery, the token endpoint (authorization code with PKCE, refresh with rotation), userinfo, JWKS and revocation, signing id_tokens with ES256.
Package oidctest is an in-memory OpenID Connect provider for tests: an httptest server with discovery, the token endpoint (authorization code with PKCE, refresh with rotation), userinfo, JWKS and revocation, signing id_tokens with ES256.

Jump to

Keyboard shortcuts

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