sso

package
v0.0.0-...-fc82156 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 35 Imported by: ? 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 sso administers persisted enterprise OpenID Connect providers.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrDomainVerified   = &auth.APIError{Status: 409, Code: "DOMAIN_VERIFIED", Message: "Domain has already been verified"}
	ErrDomainUnverified = apiError(401, "Provider domain has not been verified")
	ErrNoChallenge      = &auth.APIError{Status: 404, Code: "NO_PENDING_VERIFICATION", Message: "No pending domain verification exists"}
	ErrDomainChanged    = &auth.APIError{Status: 409, Code: "SSO_PROVIDER_CHANGED", Message: "SSO provider changed while domain verification was in progress. Reload the provider and try again"}
	ErrInvalidDNSLabel  = &auth.APIError{Status: 400, Code: "INVALID_VERIFICATION_IDENTIFIER", Message: "The DNS verification identifier must be a single label using letters, digits, underscores and hyphens"}
	ErrLabelTooLong     = &auth.APIError{Status: 400, Code: "IDENTIFIER_TOO_LONG", Message: "Verification identifier exceeds the DNS label limit of 63 characters"}
)
View Source
var (
	ErrSAMLLogoutSession  = apiError(400, "This browser session has no available SAML logout record")
	ErrSAMLLogoutResponse = &auth.APIError{Status: 400, Code: "INVALID_LOGOUT_RESPONSE", Message: "Invalid LogoutResponse"}
)
View Source
var (
	ErrUnauthenticated = apiError(401, "Unauthorized")
	ErrLimit           = apiError(403, "You have reached the maximum number of SSO providers")
	ErrDisabled        = apiError(403, "SSO provider registration is disabled")
	ErrDuplicate       = apiError(422, "SSO provider with this providerId already exists")
	ErrForbidden       = apiError(403, "You don't have access to this provider")
	ErrNotMember       = apiError(400, "You are not a member of the organization")
	ErrOrgRole         = apiError(403, "You must be an organization owner or admin to register SSO providers")
	ErrMissing         = apiError(404, "Provider not found")
)
View Source
var ErrAssertionUsed = apiError(400, "SAML assertion has already been consumed")
View Source
var ErrChanged = &auth.APIError{Status: 409, Code: "SSO_PROVIDER_CHANGED", Message: "The enterprise provider changed during authentication"}
View Source
var ErrInvalidSAML = apiError(400, "Invalid or unsupported SAML configuration")
View Source
var ErrLinkedIdentity = &auth.APIError{Status: 409, Message: "Cannot change SSO provider identity fields while linked accounts exist"}
View Source
var ErrMetadataStorageSize = &auth.APIError{Status: 400, Message: "SAML configuration exceeds the database column capacity"}
View Source
var ErrMutationRejected = &auth.APIError{Status: 409, Code: "SSO_PROVIDER_MUTATION_REJECTED", Message: "SSO provider mutation is not allowed"}
View Source
var ErrSAMLLogoutRequest = &auth.APIError{Status: 400, Code: "INVALID_LOGOUT_REQUEST", Message: "Invalid LogoutRequest"}
View Source
var ErrUnclassifiedAccounts = &auth.APIError{Status: 409, Code: "SSO_ACCOUNT_ORIGIN_REQUIRED", Message: "An existing account link requires source reconciliation"}

ErrUnclassifiedAccounts requires a trusted operator to establish the origin of preexisting canonical account rows before a provider can be deleted.

Functions

func DomainMatch

func DomainMatch(domain, list string) int

DomainMatch returns the length of the most specific DNS suffix, or -1 for no match.

func DomainTargets

func DomainTargets(id, identifier, rawDomains string) ([]string, error)

DomainTargets returns the normalized domains for one well-formed challenge. Requiring one DNS label keeps proof under the registered domain.

func MutableProviderID

func MutableProviderID(id string) bool

MutableProviderID reports whether an identifier can belong to an enterprise directory. Host-configured social provider names are checked separately.

func New

func New(o Options) (auth.Plugin, error)

New registers the provider management routes under the auth mount.

func SAMLTrustChanged

func SAMLTrustChanged(current, next SAMLConfig) bool

SAMLTrustChanged compares the signing anchors and the IdP request-signing policy.

func SameSAMLIdentity

func SameSAMLIdentity(current, next SAMLConfig) bool

SameSAMLIdentity reports whether changing only IdP metadata preserves the authority that created previously linked accounts. Keys can rotate independently.

Types

type Actor

type Actor struct {
	UserID, SessionID string
	SessionToken      string `json:"-"`
}

type AssertionReceipt

type AssertionReceipt struct {
	Issuer, ID string
	Logout     *SAMLLogoutIdentity
}

type BrowserProvider

type BrowserProvider struct {
	Provider
	Reference string
}

type BrowserStore

type BrowserStore interface {
	auth.OAuthStore
	FindBrowserProvider(context.Context, Selector) (BrowserProvider, error)
	CompleteEnterpriseLogin(ctx context.Context, reference string, provision bool, provider, subject string, tokens auth.OAuthTokens, user auth.User, session auth.StoredSession, opts auth.OAuthLoginOptions) (auth.User, bool, error)
}

type Certificates

type Certificates []string

Certificates accepts either a PEM string or a list for certificate rotation.

func (Certificates) MarshalJSON

func (cs Certificates) MarshalJSON() ([]byte, error)

func (*Certificates) UnmarshalJSON

func (cs *Certificates) UnmarshalJSON(raw []byte) error

type Config

type Config struct {
	Issuer                      string         `json:"issuer,omitempty"`
	ClientID                    string         `json:"clientId"`
	ClientSecret                string         `json:"clientSecret"`
	AuthorizationEndpoint       string         `json:"authorizationEndpoint,omitempty"`
	TokenEndpoint               string         `json:"tokenEndpoint,omitempty"`
	JWKSEndpoint                string         `json:"jwksEndpoint,omitempty"`
	UserInfoEndpoint            string         `json:"userInfoEndpoint,omitempty"`
	DiscoveryEndpoint           string         `json:"discoveryEndpoint,omitempty"`
	TokenEndpointAuthentication string         `json:"tokenEndpointAuthentication,omitempty"`
	PKCE                        *bool          `json:"pkce,omitempty"`
	Scopes                      []string       `json:"scopes,omitempty"`
	Mapping                     map[string]any `json:"mapping,omitempty"`
	OverrideUserInfo            bool           `json:"overrideUserInfo"`
}

type DeletionStore

type DeletionStore interface {
	DeleteSSOProvider(ctx context.Context, actor Actor, providerID, recordID string, guard MutationGuard) error
}

DeletionStore performs a direct-session and tenant authorization check, then atomically deletes exactly the named record and its account links.

type DomainChallenge

type DomainChallenge struct{ ProviderID, Domain, Identifier, Token, Scope string }

DomainChallenge is a pending DNS challenge bound to the exact directory and domain set. Scope is an opaque store identifier. The token is public only to an authorized manager.

type DomainStore

type DomainStore interface {
	CheckSSODomainSchema(context.Context) error
	FindVerifiedBrowserProvider(context.Context, Selector) (BrowserProvider, error)
	CreateSSODomainProvider(ctx context.Context, actor Actor, provider Provider, limit int, identifier string) (string, error)
	SSODomainChallenge(ctx context.Context, actor Actor, providerID, identifier string, issue bool) (DomainChallenge, error)
	// ConfirmSSODomain is a trusted server operation. Its caller must first observe
	// the challenge token at every domain using the configured DNS resolver.
	ConfirmSSODomain(context.Context, Actor, DomainChallenge) error
	// SSODomainVerified matches the captured reference before authorization or token exchange.
	// An empty reference requests the latest management projection.
	SSODomainVerified(ctx context.Context, provider Provider, reference string) (bool, error)
	// SSODomainRequired reports a persisted opt-in across differently configured nodes.
	SSODomainRequired(context.Context, Provider) (bool, error)
	CompleteVerifiedEnterpriseLogin(ctx context.Context, ref string, provision bool, id, subject string, tokens auth.OAuthTokens, user auth.User, session auth.StoredSession, opts auth.OAuthLoginOptions) (auth.User, bool, error)
}

type DomainVerificationOptions

type DomainVerificationOptions struct {
	// TokenPrefix defaults to "plain-auth-token". A prefix is one DNS label fragment.
	TokenPrefix string
	// Resolver defaults to the system resolver.
	Resolver TXTResolver
}

type MutationGuard

type MutationGuard func(context.Context, ProviderMutation) error

MutationGuard runs inside a transaction and may be retried after a database conflict. Return an error to deny the operation. Keep the callback read-only.

type Options

type Options struct {
	// SAML enables service-provider initiated sign-in with signed assertions.
	SAML *SAMLOptions
	// DomainVerification enables DNS ownership checks for managed OIDC domains.
	DomainVerification *DomainVerificationOptions
	// GuardProviderMutation can reject a metadata update or deletion after the exact provider and
	// its authorization have been checked inside the store transaction.
	GuardProviderMutation MutationGuard
	// SharedCallback registers the same /sso/callback URL for every enterprise client.
	SharedCallback bool
	// DisableImplicitSignUp requires requestSignUp before creating an account.
	DisableImplicitSignUp bool
	// DisableOrganizationProvisioning leaves membership management to the application.
	DisableOrganizationProvisioning bool
	// A nil ProvidersLimit allows ten registrations per creator. Zero disables registration.
	ProvidersLimit *int
	// HTTPClient supplies discovery transport and optional TLS settings.
	HTTPClient *http.Client
}

type Provider

type Provider struct {
	ID             string      `json:"id"`
	ProviderID     string      `json:"providerId"`
	Issuer         string      `json:"issuer"`
	Domain         string      `json:"domain"`
	UserID         string      `json:"userId"`
	OrganizationID *string     `json:"organizationId,omitempty"`
	OIDC           *Config     `json:"oidcConfig"`
	SAML           *SAMLConfig `json:"samlConfig,omitempty"`
}

type ProviderMutation

type ProviderMutation struct {
	Action, ID, ProviderID, Reference string
	OrganizationID                    *string
	LinkedAccounts                    int
	AuthenticationBoundaryChanged     bool
}

ProviderMutation contains the locked provider identity and a snapshot of its exact provider namespace. Reference excludes the confidential client secret.

type PublicConfig

type PublicConfig struct {
	ClientIDLastFour            string   `json:"clientIdLastFour"`
	DiscoveryEndpoint           string   `json:"discoveryEndpoint,omitempty"`
	AuthorizationEndpoint       string   `json:"authorizationEndpoint,omitempty"`
	TokenEndpoint               string   `json:"tokenEndpoint,omitempty"`
	JWKSEndpoint                string   `json:"jwksEndpoint,omitempty"`
	UserInfoEndpoint            string   `json:"userInfoEndpoint,omitempty"`
	TokenEndpointAuthentication string   `json:"tokenEndpointAuthentication,omitempty"`
	PKCE                        *bool    `json:"pkce,omitempty"`
	Scopes                      []string `json:"scopes,omitempty"`
}

type PublicProvider

type PublicProvider struct {
	SAML           *PublicSAMLConfig `json:"samlConfig,omitempty"`
	ProviderID     string            `json:"providerId"`
	Type           string            `json:"type"`
	Issuer         string            `json:"issuer"`
	Domain         string            `json:"domain"`
	OrganizationID *string           `json:"organizationId"`
	DomainVerified bool              `json:"domainVerified"`
	OIDC           *PublicConfig     `json:"oidcConfig,omitempty"`
	SPMetadataURL  string            `json:"spMetadataUrl"`
}

type PublicSAMLConfig

type PublicSAMLConfig struct {
	EntryPoint           string `json:"entryPoint"`
	Audience             string `json:"audience,omitempty"`
	WantAssertionsSigned *bool  `json:"wantAssertionsSigned,omitempty"`
	AuthnRequestsSigned  bool   `json:"authnRequestsSigned,omitempty"`
	IdentifierFormat     string `json:"identifierFormat,omitempty"`
}

type Registered

type Registered struct {
	Provider
	RedirectURI             string `json:"redirectURI"`
	SAMLConfig              any    `json:"samlConfig"`
	DomainVerified          *bool  `json:"domainVerified,omitempty"`
	DomainVerificationToken string `json:"domainVerificationToken,omitempty"`
}

type SAMLConfig

type SAMLConfig struct {
	IDPInitiatedCallbackURL string `json:"idpInitiatedCallbackUrl,omitempty"`
	CallbackURL             string `json:"callbackUrl,omitempty"`

	SPMetadata           *SAMLSPMetadata `json:"spMetadata,omitempty"`
	Issuer               string          `json:"issuer,omitempty"`
	EntryPoint           string          `json:"entryPoint"`
	Certificates         Certificates    `json:"cert,omitempty"`
	IDPMetadata          SAMLIDPMetadata `json:"idpMetadata"`
	Audience             string          `json:"audience,omitempty"`
	WantAssertionsSigned *bool           `json:"wantAssertionsSigned,omitempty"`
	AuthnRequestsSigned  bool            `json:"authnRequestsSigned,omitempty"`
	IdentifierFormat     string          `json:"identifierFormat,omitempty"`
	Mapping              SAMLMapping     `json:"mapping,omitempty"`
	// contains filtered or unexported fields
}

func DecodeSAMLConfig

func DecodeSAMLConfig(raw []byte) (*SAMLConfig, error)

func (SAMLConfig) IdentityProviderEntityID

func (c SAMLConfig) IdentityProviderEntityID() string

IdentityProviderEntityID returns the assertion issuer from a decoded directory configuration.

func (SAMLConfig) MetadataValidAt

func (c SAMLConfig) MetadataValidAt(now time.Time) bool

MetadataValidAt checks the earliest XML entity or role expiration. Manual directories have no XML validity interval.

func (SAMLConfig) WithIDPMetadata

func (c SAMLConfig) WithIDPMetadata(raw string) (*SAMLConfig, error)

WithIDPMetadata builds the effective assertion authority from the new XML alone.

type SAMLDirectory

type SAMLDirectory struct {
	RecordID, Reference, ProviderID, Issuer, EntryPoint, OrganizationID string
}

SAMLDirectory identifies the current registration for a host's IdP-initiated login policy. RecordID changes on re-registration. Reference identifies the current catalog configuration, including its trusted signing certificates.

type SAMLDirectoryPolicy

type SAMLDirectoryPolicy func(context.Context, SAMLDirectory) (bool, error)

SAMLDirectoryPolicy authorizes unsolicited browser sign-in for a reviewed directory. A nil policy disables the flow. Return an error to fail closed when the authority supplying the host's decision is unavailable.

type SAMLEncryption

type SAMLEncryption struct {
	PrivateKey  *rsa.PrivateKey
	Certificate *x509.Certificate
}

SAMLEncryption holds the host's RSA key for decrypting SAML assertions. Its certificate is published only for directories that require encryption.

type SAMLIDPLogout

type SAMLIDPLogout struct {
	ID, ProviderID, Reference, Issuer string
	Identity                          SAMLLogoutIdentity
	IssuedAt                          time.Time
	NotOnOrAfter                      *time.Time
}

SAMLIDPLogout is a signed, validated request from one immutable directory.

func (SAMLIDPLogout) ValidAt

func (r SAMLIDPLogout) ValidAt(now time.Time) bool

ValidAt bounds the receipt window independently of the transport validator.

type SAMLIDPLogoutStore

type SAMLIDPLogoutStore interface {
	SAMLLogoutStore
	RevokeSAMLIDPSessions(ctx context.Context, request SAMLIDPLogout, browserToken string, requireDomainProof bool, now time.Time) (bool, error)
}

SAMLIDPLogoutStore atomically consumes a verified IdP request and revokes every recorded session matching its authority, exact NameID and SessionIndex. The result reports only whether the presented browser token was revoked.

type SAMLIDPMetadata

type SAMLIDPMetadata struct {
	SingleLogoutService  []SAMLService `json:"singleLogoutService,omitempty"`
	IsAssertionEncrypted bool          `json:"isAssertionEncrypted,omitempty"`
	Metadata             string        `json:"metadata,omitempty"`
	EntityID             string        `json:"entityID,omitempty"`
	Certificates         Certificates  `json:"cert,omitempty"`
}

type SAMLLogoutIdentity

type SAMLLogoutIdentity struct {
	NameID       saml.NameID
	SessionIndex string
}

SAMLLogoutIdentity records the exact NameID and IdP session from a verified assertion.

func (SAMLLogoutIdentity) Valid

func (i SAMLLogoutIdentity) Valid(subject string) bool

type SAMLLogoutRequest

type SAMLLogoutRequest struct {
	ID, State, BrowserHash, ProviderID, Reference, CallbackURL string
	ExpiresAt                                                  time.Time
}

type SAMLLogoutStore

type SAMLLogoutStore interface {
	SAMLStore
	SAMLSessionForLogout(context.Context, Actor, string, string, time.Time) (SAMLLogoutIdentity, error)
	StartSAMLLogout(context.Context, Actor, SAMLLogoutIdentity, SAMLLogoutRequest, bool, time.Time) error
	ConsumeSAMLLogout(ctx context.Context, proof SAMLLogoutRequest, now time.Time) (string, error)
}

SAMLLogoutStore keeps the IdP session, local revocation and single-use return in the same shared store as the original SAML session.

type SAMLMapping

type SAMLMapping struct {
	Email         string `json:"email,omitempty"`
	FirstName     string `json:"firstName,omitempty"`
	LastName      string `json:"lastName,omitempty"`
	Name          string `json:"name,omitempty"`
	EmailVerified string `json:"emailVerified,omitempty"`
}

type SAMLMetadataStore

type SAMLMetadataStore interface {
	UpdateSSOMetadata(ctx context.Context, actor Actor, id, recordID, expectedReference, metadata string, guard MutationGuard) (Provider, error)
}

SAMLMetadataStore replaces one registered IdP metadata document under a live direct-session and tenant check. ExpectedReference is the examined configuration.

type SAMLOptions

type SAMLOptions struct {
	// EnableSingleLogout enables SP-initiated signed HTTP-Redirect logout.
	EnableSingleLogout bool
	// EnableIDPInitiatedLogout accepts signed Redirect requests from the current directory.
	EnableIDPInitiatedLogout bool
	// LogoutRequestTTL defaults to five minutes.
	LogoutRequestTTL time.Duration
	// AllowIDPInitiated is a host-owned directory policy. Nil disables unsolicited sign-in.
	AllowIDPInitiated SAMLDirectoryPolicy
	// IDPInitiatedCallbackURL is the public landing page when a directory provides none.
	IDPInitiatedCallbackURL string
	Encryption              *SAMLEncryption
	// MaxMetadataSize limits inline IdP XML in bytes, defaulting to 100 KiB.
	MaxMetadataSize    int
	RequestSigner      crypto.Signer
	RequestCertificate *x509.Certificate
	TrustEmailVerified bool
}

SAMLOptions enables SP-initiated SAML. Request signing keys stay in the host.

type SAMLSPMetadata

type SAMLSPMetadata struct {
	IsAssertionEncrypted bool   `json:"isAssertionEncrypted,omitempty"`
	EntityID             string `json:"entityID,omitempty"`
}

type SAMLService

type SAMLService struct {
	Binding  string `json:"Binding"`
	Location string `json:"Location"`
}

SAMLService is a published SAML protocol binding and its destination.

type SAMLStore

type SAMLStore interface {
	BrowserStore
	CompleteSAMLLogin(ctx context.Context, reference string, provision, verified bool, provider, subject string, receipt AssertionReceipt, u auth.User, session auth.StoredSession, opts auth.OAuthLoginOptions) (auth.User, bool, error)
}

type Selector

type Selector struct{ ProviderID, Domain, OrganizationSlug, Protocol string }

type Store

type Store interface {
	CheckSSORegistration(context.Context, Actor, Provider, int) error
	CreateSSOProvider(context.Context, Actor, Provider, int) error
	ReadSSOProviders(context.Context, Actor, string) ([]Provider, error)
}

type TXTResolver

type TXTResolver interface {
	LookupTXT(context.Context, string) ([]string, error)
}

TXTResolver returns one string for each TXT resource record, concatenating that record's character strings. The lookup name is fully qualified.

Jump to

Keyboard shortcuts

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