oidc

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: AGPL-3.0 Imports: 39 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 sign-in through an OpenID Connect identity provider (C-03): the OIDC settings with their write-only client secret, proxy, warnings and connection check, the back channel to the identity provider through the outbound HTTP package, and the redirect flow with PKCE that creates users on their first sign-in, maps their groups to a Role and opens their sessions, linking an identity to an account from its web session, and the offline token with the background re-checks of OIDC users at the identity provider.

Index

Constants

View Source
const (
	// LinkCallbackPath is the redirect URI of linking below MUSTER_PUBLIC_URL.
	LinkCallbackPath = "api/v1/me/oidc-identity/callback"
	// ProfilePage is the page of the SPA a link returns to, with ?error=<code> after a failure.
	ProfilePage = "/profile"

	// ErrorIdentityLinkedElsewhere is the callback error of a link whose identity belongs to another user.
	ErrorIdentityLinkedElsewhere = "identity_linked_elsewhere"

	// The Audit log actions of linking.
	ActionLinked      = "user.oidc_linked"
	ActionLinkRefused = "user.oidc_link_refused"
)
View Source
const (
	// RecheckInterval is auth.oidc_recheck_interval: a user who holds an offline token is re-checked this often.
	RecheckInterval = 15 * time.Minute
	// RecheckPoll is how often every replica looks for due re-checks.
	RecheckPoll = 2 * time.Second
	// RecheckBudget bounds the attempts of one refresh at the identity provider.
	RecheckBudget = 10 * time.Second
	// RecheckLease is how long a claimed re-check is held on the real clock; it outlasts the budget, so that no other
	// replica refreshes a token that a refresh in flight is about to rotate.
	RecheckLease = time.Minute

	// ActionUserRefused is the Audit log action of a user the identity provider refused at a re-check.
	ActionUserRefused = "user.oidc_refused"
)

The background re-checks (C-03.FR-30). The interval is a setting; the poll, the budget and the lease are constants of the worker, like the Leader's intervals.

View Source
const (
	CheckOK          = "ok"
	CheckRefused     = "refused"
	CheckUnavailable = "unavailable"
	CheckSkipped     = "skipped"
)

The outcomes of a re-check, as muster_oidc_checks_total and oidc_checks.last_outcome name them.

View Source
const (
	// SecretExpiryLead is oidc.secret_expiry_lead: the settings warn this long before the client secret expires.
	SecretExpiryLead = 14 * 24 * time.Hour
	// DefaultGroupsClaim and DefaultScopes are what a read shows before an Admin saves the settings.
	DefaultGroupsClaim = "groups"

	// The roles for users whose groups map to none (oidc.unmatched_role).
	UnmatchedNone      = "none"
	UnmatchedViewer    = auth.RoleViewer
	UnmatchedResponder = auth.RoleResponder
)
View Source
const (
	ActionSettingsUpdated   = "oidc_settings.updated"
	ActionSignInRefused     = "session.oidc_refused"
	ActionRoleSyncKeptAdmin = "user.role_sync_kept_admin"
	ResourceSettings        = "oidc_settings"
)

The Audit log actions and resource type of OIDC.

View Source
const (
	WarningNobodyCanSignIn    = "nobody_can_sign_in"
	WarningGroupsClaimMissing = "groups_claim_missing"
	WarningSecretExpiring     = "secret_expiring"
	WarningLastAdminKept      = "last_admin_kept"
)

The warning kinds of the settings (C-03.FR-5, FR-6, FR-32).

View Source
const (
	// AuthRequestTTL is oidc.auth_request_ttl: an OIDC redirect must come back to the callback within it.
	AuthRequestTTL = 10 * time.Minute
	// AuthRequestPruneAfter is how long after its expiry a request is deleted by short-lived pruning.
	AuthRequestPruneAfter = time.Hour
	// FallbackSessionLifetime is auth.oidc_fallback_session_lifetime: an OIDC session of a user without an offline
	// token ends this long after sign-in, since no background re-check can end it earlier.
	FallbackSessionLifetime = 12 * time.Hour

	// MaxPendingRequests bounds the OIDC redirects in flight per Organization: a start needs no credentials, and each
	// writes a row that lives until AuthRequestTTL after it plus AuthRequestPruneAfter.
	MaxPendingRequests = 10_000

	// CallbackPath is the redirect URI of sign-in below MUSTER_PUBLIC_URL.
	CallbackPath = "api/v1/sessions/oidc/callback"
	// SignInPage is the page of the SPA a failed sign-in returns to, with ?error=<code>.
	SignInPage = "/sign-in"
)
View Source
const (
	ErrorNoAccess        = "no_access"
	ErrorLoginTaken      = "login_taken"
	ErrorAccountDisabled = "account_disabled"
	ErrorOIDCDisabled    = "oidc_disabled"
	ErrorInvalidRequest  = "invalid_request"
	ErrorIDPError        = "idp_error"
)

The callback errors of a failed sign-in (C-03.FR-25), as /sign-in?error=<code> carries them.

Variables

View Source
var (
	// ErrVersionMismatch is an If-Match that names another version of the settings.
	ErrVersionMismatch = errors.New("the OIDC settings changed since they were read")
	// ErrNotEnabled is a sign-in or link while OIDC is off.
	ErrNotEnabled = errors.New("OIDC sign-in is switched off")
	// ErrTooManyRequests is a start while MaxPendingRequests redirects of the Organization are in flight.
	ErrTooManyRequests = errors.New("too many OIDC sign-ins are in flight")
	// ErrAlreadyLinked is a link started by an account that signs in through OIDC already, or has no password.
	ErrAlreadyLinked = errors.New("the account already signs in through OIDC")
)
View Source
var DefaultScopes = []string{"profile", "email"}

DefaultScopes are the configured scopes before an Admin saves the settings; openid is always added, and offline_access when the provider offers it (Discovery.OffersOfflineAccess).

View Source
var ErrNonce = errors.New("the ID token carries another nonce")

ErrNonce is an ID token whose nonce is not the one of its request.

Functions

func Challenge

func Challenge(verifier string) string

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

func MapRole

func MapRole(groups []string, mappings []GroupMapping, unmatched string) (string, bool)

MapRole maps groups to a Role: the highest Role of the mappings that name one of the groups, else the Role for unmatched users; ok is false when that is none.

func SafeReturnTo

func SafeReturnTo(returnTo string) string

SafeReturnTo is returnTo when it is a relative path that starts with a single / — never //host, /\host, a scheme or a control character — and the empty string otherwise, so the flow is no open redirect (C-03.FR-25).

func Scopes

func Scopes(configured []string, offline bool) []string

Scopes are the scopes a sign-in requests: openid, offline_access when offline, then the configured ones, as the Admin set them, without repeats.

Types

type AuthRequest

type AuthRequest struct {
	RedirectURI string
	Scopes      []string
	State       string
	Nonce       string
	// Verifier is the PKCE code verifier; the URL carries its S256 challenge.
	Verifier string
}

AuthRequest is what the authorization URL carries.

type BackChannelError

type BackChannelError struct {
	Step string

	// Blocked is the rule of the outbound address policy that refused the call, if one did.
	Blocked string
	// Status is the status code of the answer, 0 without one.
	Status int
	// Code is the OAuth error code of a token endpoint answer, such as invalid_grant.
	Code string
	// Outcome is the classified outcome of the outbound call.
	Outcome outbound.Outcome
	// contains filtered or unexported fields
}

BackChannelError is a failed call to the identity provider; its text is masked and names no secret.

func (*BackChannelError) Error

func (e *BackChannelError) Error() string

func (*BackChannelError) Unwrap

func (e *BackChannelError) Unwrap() error

type Callback

type Callback struct {
	Code        string
	State       string
	Error       string
	CookieState string
	Address     netip.Addr
	UserAgent   string
}

Callback is what the identity provider sent the browser back with, and the browser's binding cookie.

type CheckResult

type CheckResult struct {
	OK        bool
	ViaProxy  bool
	Latency   time.Duration
	Discovery Discovery
	// RequestedScopes are the scopes a sign-in requests from this provider; OfflineAccess is whether it offers
	// offline_access, so that users are re-checked in the background. Both are set when discovery was read.
	RequestedScopes []string
	OfflineAccess   bool
	// Error is what failed, masked; it names the blocking rule when the outbound address policy refused the call.
	Error    string
	Warnings []Warning
}

CheckResult is the result of the connection check (C-03.FR-8).

type Claimer

type Claimer func(ctx context.Context, orgID int64, limit int32) ([]int64, error)

Claimer claims up to limit due re-checks of the Organization orgID and returns the ids of their users, leased.

func NewClaimer

func NewClaimer(b db.Beginner, lease db.Lease) Claimer

NewClaimer is the Claimer over the main pool with the shared claim of internal/db: the due rows on the business clock, the lease on the real clock.

type Config

type Config struct {
	OrgID   int64
	Store   Store
	Keyring *keyring.Keyring
	Audit   *audit.Writer
	// Clocks: the business clock for domain times, the real clock for ID-token times.
	Clocks   clock.Clocks
	Network  Network
	Log      *logging.Logger
	Sessions Sessions
	// PublicURL is MUSTER_PUBLIC_URL, the base of the redirect URIs.
	PublicURL *url.URL
	// RecheckBudget bounds the refresh of a background re-check; zero is RecheckBudget, tests make it shorter.
	RecheckBudget time.Duration
}

Config is what the Service works with.

type Demo

type Demo struct {
	IssuerURL    string
	ClientID     string
	ClientSecret logging.Secret
	DisplayName  string
	// DisplayNameWas is the display name an earlier version gave the demo configuration, renamed to DisplayName.
	DisplayNameWas string
	Mappings       []GroupMapping
	// AllowNetwork is added to the Organization's allowed outbound networks, so that Muster may call the fakes.
	AllowNetwork string
}

Demo is the demo OIDC configuration of `muster dev`.

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"`
	ClaimsSupported       []string `json:"claims_supported"`
	ScopesSupported       []string `json:"scopes_supported"`
	TokenAuthMethods      []string `json:"token_endpoint_auth_methods_supported"`
}

Discovery is the part of the provider metadata Muster uses (OpenID Connect Discovery 1.0).

func FetchDiscovery

func FetchDiscovery(ctx context.Context, c Doer, issuer string) (Discovery, error)

FetchDiscovery reads the provider metadata of issuer through c and checks that it names the same issuer (OpenID Connect Discovery §4.3); a configured issuer with a trailing slash matches one without.

func (Discovery) AdvertisesClaim

func (d Discovery) AdvertisesClaim(claim string) bool

AdvertisesClaim reports whether discovery lists claim; a provider that lists no claims advertises none.

func (Discovery) OffersOfflineAccess added in v0.1.2

func (d Discovery) OffersOfflineAccess() bool

OffersOfflineAccess reports whether sign-in and linking request offline_access (C-03.FR-30): when discovery lists it in scopes_supported, or lists no scopes, since that list is optional. A provider whose list lacks it, as GitLab's does, refuses an authorization request that names it.

func (Discovery) RequestedScopes added in v0.1.2

func (d Discovery) RequestedScopes(configured []string) []string

RequestedScopes are the scopes a sign-in or a link requests from the provider of d.

type Doer

type Doer interface {
	Do(ctx context.Context, req outbound.Request) (outbound.Result, error)
}

Doer sends a request through an outbound client.

type ExpiryCheck

type ExpiryCheck struct {
	Store ExpiryStore
	// Business is the business clock: the expiry date is a domain date, compared as the settings warning compares it.
	Business clock.Clock
	Log      *logging.Logger
	// RunbookBase is MUSTER_RUNBOOK_BASE_URL.
	RunbookBase string
}

ExpiryCheck is the Leader task that raises MusterOIDCSecretExpiring while the OIDC client secret expires within oidc.secret_expiry_lead and resolves it when the date moves further out or is removed (C-19.FR-5). It raises and resolves only on transitions, which it reads from the database: the open Internal alert and its pending raise or resolve. So running it twice, on two Leaders at once or after a handover, writes nothing more; the lock of the settings row orders two runs.

func (ExpiryCheck) Check

func (c ExpiryCheck) Check(ctx context.Context, orgID int64) error

Check runs the check for the Organization orgID.

type ExpiryQueries

type ExpiryQueries interface {
	internalalerts.Store
	LockSettings(ctx context.Context, orgID int64) (int64, error)
	GetSettings(ctx context.Context, orgID int64) (dbgen.OidcSetting, error)
}

ExpiryQueries are what the OIDC client secret expiry check reads and writes in its transaction: the OIDC settings row, locked, and the Internal alerts of the built-in Integration.

type ExpiryStore

type ExpiryStore interface {
	InTx(ctx context.Context, f func(ExpiryQueries) error) error
}

ExpiryStore runs the check in one transaction.

func NewExpiryStore

func NewExpiryStore(pool *pgxpool.Pool) ExpiryStore

NewExpiryStore is the ExpiryStore over the main pool.

type FieldError

type FieldError struct {
	Pointer string
	Code    string
	Detail  string
}

FieldError is a field of the settings that is not valid, at a JSON pointer of the request body.

func (*FieldError) Error

func (e *FieldError) Error() string

type GroupMapping

type GroupMapping struct {
	Group string `json:"group"`
	Role  string `json:"role"`
}

GroupMapping maps an IdP group to a Role.

type IDToken

type IDToken struct {
	Subject           string
	PreferredUsername string
	Email             string
	Name              string
	AMR               []string
	Claims            map[string]any
}

IDToken is a verified ID token: its standard claims and every claim by name.

type Input

type Input struct {
	Enabled               bool
	DisplayName           *string
	IssuerURL             string
	ClientID              string
	ClientSecret          keyring.SecretInput
	ClientSecretExpiresOn *time.Time
	ExpiresOnSet          bool
	Scopes                *[]string
	GroupsClaim           string
	GroupMappings         []GroupMapping
	UnmatchedRole         string
	SyncRole              bool
	SkipTOTPWithIDPMFA    bool
	Proxy                 proxyconf.Input
}

Input is an update of the settings. A nil DisplayName, Scopes or ExpiresOn with ExpiresOnSet false keeps the stored value; an empty display name returns to the default.

type LinkStart

type LinkStart struct {
	URL       string
	ExpiresAt time.Time
}

LinkStart is the authorization URL of a link and the time by which its callback must come back.

type Network

type Network struct {
	Policy outbound.PolicySource
	Log    *logging.Logger
	// Real is the real clock: ID-token times and the outbound metrics.
	Real clock.Clock
	// Resolver resolves host names; nil is the system resolver.
	Resolver outbound.Resolver
}

Network is what the back channel needs to build its outbound clients.

type Outcome

type Outcome struct {
	Session  *auth.Session
	Redirect string
	Error    string
}

Outcome is where a callback sends the browser: a session and its page, or the sign-in page with an error code.

type Provider

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

Provider is the back channel to the identity provider of one version of the OIDC settings: its clients carry the OIDC proxy and the client secret, and it keeps the provider metadata and the last good key set.

func NewProvider

func NewProvider(n Network, issuer, clientID string, clientSecret logging.Secret, proxy *outbound.Proxy) (*Provider,
	error)

NewProvider builds the back channel for the issuer and client, with the proxy (nil: direct).

func (*Provider) AuthURL

func (p *Provider) AuthURL(d Discovery, r AuthRequest) (string, error)

AuthURL is the authorization endpoint with the request: the authorization code flow with PKCE S256, state and nonce, and the scopes openid and, when the provider offers it, offline_access before the configured ones.

func (*Provider) Discover

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

Discover returns the provider metadata, read at most discoveryMaxAge ago; a failed read is not kept.

func (*Provider) Exchange

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

Exchange trades an authorization code and its PKCE verifier for tokens at the token endpoint.

func (*Provider) Interactive

func (p *Provider) Interactive() Doer

Interactive is the interactive client, for the connection check.

func (*Provider) Refresh

func (p *Provider) Refresh(ctx context.Context, d Discovery, refreshToken logging.Secret) (Tokens, error)

Refresh redeems an offline (refresh) token at the token endpoint through the background class, which retries transient answers until ctx ends: the budget of a background re-check (C-03.FR-30).

func (*Provider) UserInfo

func (p *Provider) UserInfo(ctx context.Context, d Discovery, accessToken logging.Secret) (map[string]any, error)

UserInfo reads the claims of the userinfo endpoint with the access token.

func (*Provider) Verify

func (p *Provider) Verify(ctx context.Context, d Discovery, raw logging.Secret, nonce string) (IDToken, error)

Verify checks an ID token: an accepted algorithm and a signature of a key of the provider's key set, the issuer of discovery, the client among the audiences (and as azp when there are several or azp is given), exp and iat present, and exp, nbf and iat on the real clock with leeway; then the nonce, which must be the one of the request.

func (*Provider) VerifyRefreshed

func (p *Provider) VerifyRefreshed(ctx context.Context, d Discovery, raw logging.Secret) (IDToken, error)

VerifyRefreshed checks the ID token of a refresh as Verify does, without a nonce: a refresh has no request of its own, and OpenID Connect Core §12.2 lets the token leave the nonce out.

type PruneQueries

type PruneQueries interface {
	PruneAuthRequests(ctx context.Context, arg dbgen.PruneAuthRequestsParams) (int64, error)
}

PruneQueries are the deletes of short-lived pruning; *dbgen.Queries implements them.

type Pruner

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

Pruner deletes the OIDC redirects that expired AuthRequestPruneAfter ago, for the short_lived_pruning Leader task.

func NewPruner

func NewPruner(q PruneQueries) Pruner

NewPruner returns the Pruner over q.

func (Pruner) AuthRequests

func (p Pruner) AuthRequests(ctx context.Context, orgID int64, now time.Time, limit int32) (int64, error)

AuthRequests deletes at most limit requests of the Organization that expired AuthRequestPruneAfter before now.

type Queries

type Queries interface {
	GetSettings(ctx context.Context, orgID int64) (dbgen.OidcSetting, error)
	LockSettings(ctx context.Context, orgID int64) (int64, error)
	InsertSettings(ctx context.Context, arg dbgen.InsertSettingsParams) (int64, error)
	UpdateSettings(ctx context.Context, arg dbgen.UpdateSettingsParams) (int64, error)
	RecordGroupsClaimSeen(ctx context.Context, arg dbgen.RecordGroupsClaimSeenParams) (int64, error)
	RecordGroupsClaimAdvertised(ctx context.Context, arg dbgen.RecordGroupsClaimAdvertisedParams) (int64, error)
	LatestKeptAdmin(ctx context.Context, orgID int64) (dbgen.LatestKeptAdminRow, error)
	InsertAuthRequest(ctx context.Context, arg dbgen.InsertAuthRequestParams) (int64, error)
	TakeAuthRequest(ctx context.Context, arg dbgen.TakeAuthRequestParams) (dbgen.TakeAuthRequestRow, error)
	GetIdentityUser(ctx context.Context, arg dbgen.GetIdentityUserParams) (dbgen.GetIdentityUserRow, error)
	LoginTaken(ctx context.Context, arg dbgen.LoginTakenParams) (bool, error)
	CreateIdentityUser(ctx context.Context, arg dbgen.CreateIdentityUserParams) (int64, error)
	LockActiveAdmins(ctx context.Context, orgID int64) ([]int64, error)
	LockUser(ctx context.Context, arg dbgen.LockUserParams) (dbgen.LockUserRow, error)
	SetRole(ctx context.Context, arg dbgen.SetRoleParams) (int64, error)
	EndUserSessions(ctx context.Context, arg dbgen.EndUserSessionsParams) (int64, error)
	RecordContact(ctx context.Context, arg dbgen.RecordContactParams) error
	TakeLinkRequest(ctx context.Context, arg dbgen.TakeLinkRequestParams) (dbgen.TakeLinkRequestRow, error)
	LockLinkUser(ctx context.Context, arg dbgen.LockLinkUserParams) (dbgen.LockLinkUserRow, error)
	LinkIdentity(ctx context.Context, arg dbgen.LinkIdentityParams) (int64, error)
	EndOtherUserSessions(ctx context.Context, arg dbgen.EndOtherUserSessionsParams) (int64, error)
	ContinueAsOIDCSession(ctx context.Context, arg dbgen.ContinueAsOIDCSessionParams) (int64, error)
	StoreOfflineToken(ctx context.Context, arg dbgen.StoreOfflineTokenParams) error
	WipeOfflineToken(ctx context.Context, arg dbgen.WipeOfflineTokenParams) error
	ScheduleCheck(ctx context.Context, arg dbgen.ScheduleCheckParams) error
	DeleteCheck(ctx context.Context, arg dbgen.DeleteCheckParams) error
	GetCheckUser(ctx context.Context, arg dbgen.GetCheckUserParams) (dbgen.GetCheckUserRow, error)
	LockCheckUser(ctx context.Context, arg dbgen.LockCheckUserParams) (dbgen.LockCheckUserRow, error)
	FinishCheck(ctx context.Context, arg dbgen.FinishCheckParams) (int64, error)
	DropCheck(ctx context.Context, arg dbgen.DropCheckParams) (int64, error)
	RefuseUser(ctx context.Context, arg dbgen.RefuseUserParams) error
	CapOIDCSessions(ctx context.Context, arg dbgen.CapOIDCSessionsParams) (int64, error)
	InsertDemoSettings(ctx context.Context, arg dbgen.InsertDemoSettingsParams) (int64, error)
	RenameDemoSettings(ctx context.Context, arg dbgen.RenameDemoSettingsParams) (int64, error)
	AllowNetwork(ctx context.Context, arg dbgen.AllowNetworkParams) (int64, error)
	audit.Store
}

Queries are the queries of the package, with the insert of the Audit log.

type Rechecker

type Rechecker struct {
	Claim Claimer
	// Owner names this replica in lease_owner.
	Owner         string
	Organizations func(ctx context.Context) ([]int64, error)
	// Service is the OIDC service of an Organization; false skips the Organization.
	Service func(orgID int64) (*Service, bool)
	Log     *logging.Logger
	// Poller paces the rounds; its zero value polls every RecheckPoll.
	Poller db.Poller
}

Rechecker is the worker of the background re-checks on every replica: every RecheckPoll it goes through the Organizations and runs the re-checks due in each.

func (Rechecker) Round

func (r Rechecker) Round(ctx context.Context) error

Round runs the due re-checks of every Organization once; a failure is logged as oidc_check_failed and returned, so that the next round backs off.

func (Rechecker) Run

func (r Rechecker) Run(ctx context.Context)

Run runs rounds until ctx ends.

type Requester

type Requester struct {
	Actor     audit.Actor
	Transport audit.Transport
	Address   netip.Addr
}

Requester is who asks for a change and how.

type Service

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

Service holds the OIDC settings and the sign-in flow of the Organization.

func NewService

func NewService(cfg Config) *Service

NewService returns the Service.

func (*Service) Check

func (s *Service) Check(ctx context.Context) (CheckResult, error)

Check fetches discovery with the saved settings through the interactive class and the OIDC proxy, says which scopes a sign-in requests and whether the provider offers offline_access — neither is a warning — and records whether discovery advertises the groups claim: while no sign-in has seen the claim, a claim it does not list raises groups_claim_missing and a listed one clears it; once a sign-in has seen it, discovery's list, which is optional, changes nothing.

func (s *Service) CompleteLink(ctx context.Context, sess auth.Session, cb Callback) Outcome

CompleteLink finishes a link in the web session sess (C-03.FR-29, FR-30): it takes the link request of the state only when sess started it, exchanges the code, verifies the ID token and adds the identity to the account, wiping the password in the same update; the TOTP enrolment stays. The user's other sessions end (oidc_linked) and sess continues as an OIDC session; an offline token is kept as at a sign-in. An identity that another user holds is refused with identity_linked_elsewhere, and one whose groups map to no Role with no_access. Every outcome is a redirect to the profile; a failure of the identity provider or of Muster itself is idp_error and is logged as oidc_sign_in_failed.

func (*Service) CompleteSignIn

func (s *Service) CompleteSignIn(ctx context.Context, cb Callback) Outcome

CompleteSignIn finishes a sign-in (C-03.FR-25, FR-28, FR-7, FR-10): it takes the request of the state once, exchanges the code, verifies the ID token, reads the groups and resolves the account, then opens the session. Every outcome is a redirect; a failure of the identity provider or of Muster itself is idp_error and is logged as oidc_sign_in_failed.

func (*Service) EnsureDemo

func (s *Service) EnsureDemo(ctx context.Context, d Demo) error

EnsureDemo is the start-up step of `muster dev`: when the Organization has no OIDC settings it stores the demo configuration, enabled, and records it in the Audit log as done by the system; it then allows the demo's network. Settings that still carry the demo's earlier display name, kept in a development database from an earlier version, get its current one; any other settings stay as they are. It never runs outside development mode.

func (*Service) Get

func (s *Service) Get(ctx context.Context) (Settings, error)

Get reads the settings with their warnings; before an Admin saves them it returns the defaults with OIDC off and the version 0.

func (*Service) Recheck

func (s *Service) Recheck(ctx context.Context, claim Claimer, owner string) (int, error)

Recheck claims the due re-checks of the Organization and runs them at once, each within RecheckBudget; it returns how many it claimed.

func (*Service) SignInOptions

func (s *Service) SignInOptions(ctx context.Context) (bool, string, error)

SignInOptions says whether the sign-in page shows the OIDC button, and its provider name.

func (s *Service) StartLink(ctx context.Context, sess auth.Session) (LinkStart, error)

StartLink starts linking the account of the web session sess to an identity at the identity provider (C-03.FR-29): it stores a link request bound to the account and to the session — with the state, the nonce, the PKCE verifier encrypted and the scopes of a sign-in requested, offline_access when the provider offers it — and returns the authorization URL. OIDC that is off is ErrNotEnabled; an account that signs in through OIDC already, or has no password, is ErrAlreadyLinked.

func (*Service) StartSignIn

func (s *Service) StartSignIn(ctx context.Context, returnTo string) (Start, error)

StartSignIn stores a sign-in request — the hash of a new state, the nonce, the PKCE verifier encrypted and returnTo when it is a relative path — valid for AuthRequestTTL, and returns the redirect to the identity provider. OIDC that is off is ErrNotEnabled; a failed discovery is a *BackChannelError.

func (*Service) Update

func (s *Service) Update(ctx context.Context, r Requester, version *int64, in Input) (Settings, error)

Update replaces the settings at version, the version If-Match names, or at any version when version is nil; the first save names version 0. The client secret and the proxy password follow the rule of every Secret field. A change is recorded as oidc_settings.updated with its diff, in which the Secrets show only that they changed; an update that changes nothing writes nothing.

type Sessions

type Sessions interface {
	OpenOIDCSession(ctx context.Context, in auth.OIDCSignIn) (auth.Session, error)
}

Sessions opens the sessions of OIDC sign-ins; internal/auth implements it.

type Settings

type Settings struct {
	// Configured is false until an Admin saves the settings; the other fields are then the defaults.
	Configured            bool
	Enabled               bool
	DisplayName           string
	IssuerURL             string
	ClientID              string
	ClientSecret          keyring.SecretStatus
	ClientSecretExpiresOn *time.Time
	Scopes                []string
	GroupsClaim           string
	GroupMappings         []GroupMapping
	UnmatchedRole         string
	SyncRole              bool
	SkipTOTPWithIDPMFA    bool
	Proxy                 proxyconf.Config
	ProxyPassword         keyring.SecretStatus
	// GroupsClaimMissing says that no sign-in has seen the groups claim and the latest check found discovery not
	// advertising it.
	GroupsClaimMissing bool
	// GroupsClaimSeen says that a sign-in or a link found the groups claim in an ID token or in userinfo since the
	// groups claim, the issuer, the client ID or the scopes last changed.
	GroupsClaimSeen bool
	Warnings        []Warning
	Version         int64
	UpdatedAt       *time.Time
}

Settings are the OIDC settings as read: Secrets only as their status.

func (Settings) ButtonName

func (s Settings) ButtonName() string

ButtonName is the provider name of the sign-in button: the display name, or the host of the issuer URL.

type Start

type Start struct {
	URL   string
	State string
}

Start is the redirect that starts a sign-in: the authorization URL and the state, which the caller also sets in the browser-binding cookie.

type Store

type Store interface {
	Queries
	InTx(ctx context.Context, f func(Queries) error) error
}

Store runs the queries alone or in one transaction.

func NewStore

func NewStore(pool *pgxpool.Pool) Store

NewStore is the Store over the main pool.

type TokenError

type TokenError struct {
	Reason string
}

TokenError is an ID token that does not verify; it says why without the token.

func (*TokenError) Error

func (e *TokenError) Error() string

type Tokens

type Tokens struct {
	IDToken      logging.Secret
	AccessToken  logging.Secret
	RefreshToken logging.Secret
	// Scope is the granted scope, when the answer says it.
	Scope []string
}

Tokens is a successful answer of the token endpoint. The tokens are Secrets.

type UserRef

type UserRef struct {
	PublicID string
	Name     string
	Login    string
}

UserRef names a user in a warning.

type Warning

type Warning struct {
	Kind      string
	ExpiresOn *time.Time
	User      *UserRef
	Role      string
}

Warning is a warning of the settings; ExpiresOn goes with secret_expiring, User and Role with last_admin_kept.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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