Documentation
¶
Overview ¶
Package oidc authenticates sqi web UI logins against an OAuth2/OIDC identity provider.
It provides the login-time half of the authorization-code flow with PKCE:
- Provider (provider.go) — lazy, retried discovery; AuthCodeURL to start a login; Exchange to redeem the code and return a verified Identity with signature, issuer, audience, expiry, and nonce all checked; EndSessionURL for RP-initiated logout.
- FlowState (state.go) — the HMAC-signed state cookie carrying the state value, nonce, and PKCE verifier across the redirect to the provider.
- Config and Identity (config.go) — the package-side configuration shape and the claim-mapped result of a successful login, including role mapping.
- The mode constants below, describing reauth, logout, and role-source policy.
The package holds no HTTP routes and no persistence: it verifies a login and hands back an Identity, leaving session issuance and account provisioning to internal/api.
Config is defined here rather than reused from internal/config so that this package and internal/api can depend on it without importing the config loader; internal/server converts between the two, as it does for LDAP.
Index ¶
Constants ¶
const ( // ReauthAfterLogout re-prompts only on the login that follows an // explicit logout, so "log out" means the next person at a shared // workstation must authenticate. This is the default. ReauthAfterLogout = "after_logout" // ReauthAlways re-prompts on every login. A hard guarantee, at the cost // of SSO's silent-login convenience. ReauthAlways = "always" // ReauthNever never re-prompts; silent re-login is always permitted. ReauthNever = "never" )
Reauth modes control when the provider is asked to re-prompt for credentials (prompt=login) on login.
const ( // LogoutLocal ends only the local sqi session. This is the default — // provider logout signs the user out of every company tool sharing that // provider, so it is off unless asked for. LogoutLocal = "local" // LogoutProvider also redirects through the provider's end-session // endpoint, ending the session everywhere it is trusted. LogoutProvider = "provider" )
Logout modes control whether logging out of sqi also ends the session at the identity provider.
const ( // RoleSourceDirectory recomputes the role from claims on every login; // the users API rejects role edits on an SSO account. RoleSourceDirectory = rolemap.SourceDirectory // RoleSourceLocal has claims seed the role at provisioning only; // admins own it afterwards and the API allows edits. RoleSourceLocal = rolemap.SourceLocal )
Role sources decide who owns an SSO user's role after provisioning. They are the shared internal/auth/rolemap values under OIDC-facing names; the enum has exactly one definition so OIDC and LDAP cannot drift.
const StateTTL = 10 * time.Minute
StateTTL bounds a login attempt. It lives beside OpenState, which enforces it, and internal/api reads it for the state cookie's MaxAge, so the browser-side and server-side bounds cannot disagree.
Generous enough for a slow human at an MFA prompt, short enough that a stolen cookie is near-worthless.
Variables ¶
var ( // ErrDiscovery means the provider's discovery document could not be // fetched or parsed — an infrastructure fault, not a bad login. The next // attempt retries. ErrDiscovery = errors.New("oidc: provider discovery failed") // ErrTokenInvalid means the authorization code exchange returned no ID // token, or one that failed signature, issuer, audience, expiry, or nonce // validation. ErrTokenInvalid = errors.New("oidc: id token invalid") )
Errors returned by a Provider. Callers must not distinguish them in what they show the user: an ID token that fails any check is a failed login, and saying which check failed helps only an attacker probing the deployment.
var ErrNoSigningKey = errors.New("oidc: state signing key is empty")
ErrNoSigningKey means SealState was handed no key. An HMAC keyed with nothing is one an attacker can compute, so this is refused outright rather than producing a signature that only looks like a defense.
Only SealState returns it. OpenState answers ErrStateInvalid for the same condition (see the comment there): every rejection on the verify side must be indistinguishable.
var ErrStateInvalid = errors.New("oidc: state cookie invalid or expired")
ErrStateInvalid means the state cookie was missing, malformed, expired, or not signed by this server. Callers must not distinguish these in what they show a user: an expired state and a forged one are the same answer.
Functions ¶
func NewSigningKey ¶
NewSigningKey returns a random per-boot HMAC key for SealState/OpenState.
Types ¶
type Config ¶
type Config struct {
// Issuer is the provider's discovery root. Discovery is performed lazily
// on first use, never in New: a briefly unreachable identity provider must
// not stop the scheduler from starting.
Issuer string
// ClientID is the application's registered identifier. It is also the
// audience every ID token must carry.
ClientID string
// ClientSecret is the application's secret, sent only to the token
// endpoint. Never logged.
ClientSecret string
// RedirectURL is the absolute callback URL registered with the provider.
RedirectURL string
// Scopes requested at authorization. "openid" is added if absent — the
// flow returns no ID token without it.
Scopes []string
// UsernameClaim names the claim holding the login name. Used for display
// and uniqueness only; accounts are matched on "sub".
UsernameClaim string
// DisplayNameClaim names the claim holding the human-facing name.
DisplayNameClaim string
// GroupsClaim names the claim holding group memberships, fed to MapRole.
GroupsClaim string
// RoleSource is RoleSourceDirectory or RoleSourceLocal.
RoleSource string
// DefaultRole applies when no mapping matches. Empty rejects the login.
DefaultRole string
// RoleMap maps group claims to roles, first match wins; order is
// precedence.
RoleMap []rolemap.Mapping
// ReauthMode is one of ReauthAfterLogout, ReauthAlways, ReauthNever.
ReauthMode string
// LogoutMode is LogoutLocal or LogoutProvider.
LogoutMode string
// PostLogoutRedirectURL is where the provider returns the browser after a
// provider-side logout. Only read when LogoutMode is LogoutProvider.
PostLogoutRedirectURL string
// ButtonLabel is the login page's SSO button text.
ButtonLabel string
// Logger receives the warnings for a failed discovery attempt, which a
// user otherwise sees only as an unexplained login failure, and for
// unreadable extra discovery claims. Optional: nil disables that logging.
Logger *slog.Logger
}
Config configures OAuth2/OIDC single sign-on. It mirrors config.OIDCConfig; the server converts between them so this package stays independent of the config loader, exactly as internal/auth/ldap does.
type FlowState ¶
type FlowState struct {
State string `json:"s"`
Nonce string `json:"n"`
Verifier string `json:"v"`
// IssuedAt is Unix seconds. It is inside the signed payload, so a holder of
// a captured cookie cannot extend its life without the key; OpenState
// rejects anything older than StateTTL. Without it the TTL would be only
// the browser's cookie expiry, which an attacker replaying a captured
// value ignores.
IssuedAt int64 `json:"t"`
}
FlowState is the set of one-time values bound to a single login attempt.
func NewFlowState ¶
NewFlowState mints independently-random values for one login attempt.
type Identity ¶
type Identity struct {
// Subject is the provider's stable, non-reusable identifier for the user
// ("sub"). This is what accounts are matched on — never the username,
// which providers allow people to change.
Subject string
// Username is the login name, read from Config.UsernameClaim.
Username string
// DisplayName is the human-facing label, read from
// Config.DisplayNameClaim. Consumed only at provisioning.
DisplayName string
// Groups are the memberships read from Config.GroupsClaim.
Groups []string
}
Identity is what a successful Exchange reports about the authenticated user.
type Provider ¶
type Provider interface {
// AuthCodeURL builds the URL the browser is redirected to in order to
// start a login. forceReauth adds prompt=login. ctx bounds the lazy
// discovery this may have to perform, so a caller that gives up (a
// browser that navigated away) is not left pinning a goroutine for the
// full discovery timeout.
AuthCodeURL(ctx context.Context, state, nonce, codeChallenge string, forceReauth bool) (string, error)
// Exchange redeems an authorization code and returns the verified
// identity. Every ID-token check — signature, issuer, audience, expiry,
// nonce — must pass or it returns an error.
Exchange(ctx context.Context, code, codeVerifier, nonce string) (Identity, error)
// EndSessionURL returns the provider's RP-initiated logout URL, or false
// when discovery advertised no end_session_endpoint so the caller degrades
// to local logout rather than emitting a broken URL. The post-logout
// redirect comes from the Config this Provider was built with. ctx bounds
// discovery, as in AuthCodeURL.
EndSessionURL(ctx context.Context) (string, bool)
}
Provider is the login-time half of OIDC: build an authorization URL, redeem the code the browser comes back with, and (optionally) build the provider's end-session URL.