auth

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2026 License: Apache-2.0 Imports: 22 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

Index

Constants

View Source
const (
	AuditActionInvitationCreate         = "auth.invitation.create"
	AuditActionInvitationRevoke         = "auth.invitation.revoke"
	AuditActionDomainCreate             = "auth.domain.create"
	AuditActionDomainVerify             = "auth.domain.verify"
	AuditActionIdentityConnectionCreate = "auth.identity_connection.create"
)
View Source
const (
	PendingMFACookieName = "identrail_mfa_pending"
	DefaultMFAPendingTTL = 10 * time.Minute
)
View Source
const (
	CookieName              = "identrail_session"
	IdleTimeout             = db.SessionIdleTimeout
	AbsoluteTimeout         = 14 * 24 * time.Hour
	DefaultSessionListLimit = 100
)
View Source
const (
	PendingEmailVerificationCookieName = "identrail_email_verification_pending"
	DefaultEmailVerificationPendingTTL = 10 * time.Minute
)
View Source
const (
	WorkOSMFAModeEnrollment = "enrollment"
	WorkOSMFAModeChallenge  = "challenge"
)
View Source
const (

	// OAuthTransactionCookiePrefix prefixes the short-lived, HttpOnly,
	// Secure, SameSite=Lax cookie that binds an in-flight OAuth login to the
	// browser that started it. The cookie name is scoped per state nonce so
	// concurrent in-flight logins (double-click, two tabs, switching
	// provider) each keep their own browser-bound token instead of one
	// overwriting another.
	OAuthTransactionCookiePrefix = "idr_oauth_txn"
)
View Source
const (

	// SAMLRelayHandleByteLength chooses 16 random bytes → 22 base64url
	// characters, well under the 80-byte RelayState limit imposed by the
	// SAML 2.0 HTTP-Redirect binding for any IdP that enforces it.
	SAMLRelayHandleByteLength = 16
)
View Source
const WorkOSProvider = "workos"

Variables

View Source
var (
	ErrMFAPendingStateInvalid = errors.New("mfa pending state invalid")
	ErrMFAPendingStateExpired = errors.New("mfa pending state expired")
)
View Source
var (
	ErrOAuthStateInvalid = errors.New("oauth state invalid")
	ErrOAuthStateExpired = errors.New("oauth state expired")
	ErrOAuthStateReused  = errors.New("oauth state reused")
)
View Source
var (
	ErrEmailVerificationPendingStateInvalid = errors.New("email verification pending state invalid")
	ErrEmailVerificationPendingStateExpired = errors.New("email verification pending state expired")
)
View Source
var ErrInvalidSessionID = errors.New("invalid session id")
View Source
var ErrOAuthTransactionInvalid = errors.New("oauth transaction invalid")

ErrOAuthTransactionInvalid is returned when the store-backed OAuth transaction is missing, expired, already consumed, or its browser-bound cookie token does not match the row issued when the redirect was minted.

View Source
var ErrSAMLRelayHandleInvalid = errors.New("saml relay handle invalid")

ErrSAMLRelayHandleInvalid is returned when an opaque relay handle is missing, expired, malformed, or has already been consumed.

View Source
var ErrWorkOSUnavailable = errors.New("workos unavailable")

Functions

func DecodePublicSessionID

func DecodePublicSessionID(value string) ([]byte, error)

DecodePublicSessionID decodes a session-management id back to the stored hash.

func EncodePublicSessionID

func EncodePublicSessionID(hash []byte) string

EncodePublicSessionID returns the non-secret id used by session-management endpoints.

func EnterpriseAuditEvent

func EnterpriseAuditEvent(action string, orgID string, resourceType string, resourceID string, outcome string) audit.AuditEvent

EnterpriseAuditEvent builds the action audit envelope used by future enterprise auth flows.

func HashCookieValue

func HashCookieValue(value string) ([]byte, error)

HashCookieValue decodes a cookie value and returns its SHA-256 lookup key.

func NewSessionID

func NewSessionID() (string, []byte, error)

NewSessionID creates the plaintext cookie value and its database lookup hash.

func OAuthTransactionCookieName

func OAuthTransactionCookieName(nonce string) string

OAuthTransactionCookieName returns the per-nonce transaction cookie name. The nonce is base64url (RFC 4648 raw) so its characters are all valid cookie-name token characters; any unexpected character is mapped to '_' defensively so a malformed nonce can never produce an invalid Set-Cookie.

Types

type CurrentSession

type CurrentSession struct {
	Session db.Session
	IDHash  []byte
}

CurrentSession is the authenticated browser session attached to a request.

func CurrentFromGin

func CurrentFromGin(c *gin.Context) (CurrentSession, bool)

CurrentFromGin returns the current browser session from middleware state.

type EmailVerificationPendingStateManager added in v1.0.2

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

func NewEmailVerificationPendingStateManager added in v1.0.2

func NewEmailVerificationPendingStateManager(secret string, now func() time.Time) *EmailVerificationPendingStateManager

func (*EmailVerificationPendingStateManager) Open added in v1.0.2

func (*EmailVerificationPendingStateManager) Seal added in v1.0.2

func (*EmailVerificationPendingStateManager) TTL added in v1.0.2

func (*EmailVerificationPendingStateManager) WithPreviousSecret added in v1.0.2

WithPreviousSecret registers a previous sealing key accepted for opening (decryption) only during a key-rotation window. State is always sealed with the active secret; the previous secret is never used to seal. An empty previous secret clears any prior value. Returns the manager so it can be chained off the constructor.

type MFAPendingStateManager

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

func NewMFAPendingStateManager

func NewMFAPendingStateManager(secret string, now func() time.Time) *MFAPendingStateManager

func (*MFAPendingStateManager) Open

func (*MFAPendingStateManager) Seal

func (*MFAPendingStateManager) TTL

func (*MFAPendingStateManager) WithPreviousSecret

func (m *MFAPendingStateManager) WithPreviousSecret(previous string) *MFAPendingStateManager

WithPreviousSecret registers a previous sealing key accepted for opening (decryption) only during a key-rotation window. State is always sealed with the active secret; the previous secret is never used to seal. An empty previous secret clears any prior value. Returns the manager so it can be chained off the constructor.

type Manager

type Manager struct {
	Store         db.Store
	PublicBaseURL string
	Now           func() time.Time
	// PendingDeletionPaths lists request paths that may accept session
	// cookies belonging to a soft-deleted-within-grace user. The default is
	// the strict policy (every path refuses deleted users); the router opts
	// in `/v1/me/cancel-deletion` so the post-delete recovery flow can reach
	// its handler. Keys are exact match against `r.URL.Path`.
	PendingDeletionPaths map[string]struct{}
}

Manager owns session cookie encoding and lookup.

func (Manager) ClearCookie

func (m Manager) ClearCookie() *http.Cookie

ClearCookie returns the Set-Cookie value that removes a session.

func (Manager) Cookie

func (m Manager) Cookie(value string) *http.Cookie

Cookie returns the Set-Cookie value for a live session.

func (Manager) CreateSession

func (m Manager) CreateSession(ctx context.Context, session db.Session) (string, db.Session, error)

CreateSession creates a persisted session and returns the cookie value.

func (Manager) LookupRequest

func (m Manager) LookupRequest(r *http.Request) (CurrentSession, error)

LookupRequest resolves the request cookie into a current session. When the request path is on the Manager's pending-deletion allowlist, the lookup uses the lenient TouchSessionAllowingPendingDeletion variant so users in their soft-delete grace window can reach the recovery endpoint.

func (Manager) Middleware

func (m Manager) Middleware() gin.HandlerFunc

Middleware attaches a current session when a browser cookie is present.

type OAuthState

type OAuthState struct {
	Nonce         string `json:"nonce"`
	Intent        string `json:"intent"`
	ReturnTo      string `json:"return_to,omitempty"`
	ExpiresAt     int64  `json:"expires_at"`
	ConnectionID  string `json:"connection_id,omitempty"`
	SAMLRequestID string `json:"saml_request_id,omitempty"`
}

OAuthState captures the small amount of callback context we need to restore after WorkOS redirects back to Identrail. When the same state token carries a SAML SP-initiated request, ConnectionID and SAMLRequestID are populated so the ACS handler can scope the response to the originating connection and match the InResponseTo replay-protection field.

type OAuthStateManager

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

func NewOAuthStateManager

func NewOAuthStateManager(secret string, now func() time.Time) *OAuthStateManager

func (*OAuthStateManager) Consume

func (m *OAuthStateManager) Consume(raw string) (OAuthState, error)

Consume verifies the signed state (via Decode, the single source of token-verification truth) and then marks the nonce consumed in the process-local replay map. It is only the single-use authority when no store-backed OAuth transaction is wired; otherwise the callback uses Decode and the store row enforces single-use across the fleet.

func (*OAuthStateManager) Decode

func (m *OAuthStateManager) Decode(raw string) (OAuthState, error)

Decode verifies the HMAC signature and expiry of a signed state token and returns the embedded state WITHOUT marking the nonce consumed. The start handler uses it to recover the freshly minted nonce so it can bind a store-backed, browser-bound transaction to it. Single-use enforcement is the job of Consume and the store-backed OAuth transaction.

func (*OAuthStateManager) Issue

func (m *OAuthStateManager) Issue(intent string, returnTo string) (string, error)

func (*OAuthStateManager) IssueWithSAML

func (m *OAuthStateManager) IssueWithSAML(intent, returnTo, connectionID, samlRequestID string) (string, error)

IssueWithSAML mints a state token carrying SAML SP-initiated context. The connection id and AuthnRequest id propagate through the IdP as RelayState and come back to the ACS handler so it can verify InResponseTo and route to the right connection.

func (*OAuthStateManager) WithPreviousSecret

func (m *OAuthStateManager) WithPreviousSecret(previous string) *OAuthStateManager

WithPreviousSecret registers a previous signing key accepted for verification only during a key-rotation window. New state is always signed with the active secret; the previous secret is never used to issue tokens. An empty previous secret clears any prior value.

Set/clear is decided on the trimmed value so a whitespace-only string (e.g. injected by env templating or a stray newline) is treated as unset, matching how config (security.go) decides whether IDENTRAIL_SESSION_KEY_PREVIOUS is configured. This prevents an accidental low-entropy fallback key from ever being accepted for verification.

When a real key is present it is stored verbatim, exactly as NewOAuthStateManager stores the active secret. This is deliberate: state is signed with the active key's raw bytes, so after a rotation the same raw bytes (including any surrounding whitespace that was part of the real key) must be presented as the previous key for in-flight signatures to verify. Returns the manager so it can be chained off the constructor.

type OAuthTransactionEntry

type OAuthTransactionEntry struct {
	Nonce             string
	Intent            string
	ReturnTo          string
	ExpectedUserID    string
	ExpectedSessionID string
	ExpiresAt         time.Time
}

OAuthTransactionEntry is the SP-side context bound to one in-flight WorkOS OAuth login. Nonce comes from the signed state token; CookieToken is the opaque value placed in the browser-bound transaction cookie.

type OAuthTransactionStore

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

OAuthTransactionStore mints the browser-bound cookie token, persists the transaction through db.Store, and one-shot-consumes it on the callback. Persisting through db.Store means a callback routed to a different API instance than the one that issued the redirect still finds the row, so a captured signed state cannot be replayed anywhere in the fleet.

func NewOAuthTransactionStore

func NewOAuthTransactionStore(store db.Store, now func() time.Time) *OAuthTransactionStore

NewOAuthTransactionStore returns a store backed by the supplied db.Store. The now function is injectable so tests can advance the clock; pass nil for time.Now.

func (*OAuthTransactionStore) Consume

func (s *OAuthTransactionStore) Consume(ctx context.Context, nonce string, cookieToken string) (OAuthTransactionEntry, error)

Consume returns the entry for the (nonce, cookieToken) pair and atomically marks the row consumed. A missing, expired, reused, or cookie-mismatched transaction returns ErrOAuthTransactionInvalid, so the OAuth state cannot be replayed even against another API instance sharing the database.

func (*OAuthTransactionStore) Issue

Issue generates the opaque cookie token, persists the transaction keyed by the signed-state nonce, and returns the cookie token. The caller sets the returned value in a short-lived HttpOnly, Secure, SameSite=Lax cookie.

func (*OAuthTransactionStore) TTL

TTL is the lifetime of an in-flight OAuth transaction. The browser-bound cookie is set to expire on the same window so a stale cookie cannot outlive its store row.

type SAMLRelayEntry

type SAMLRelayEntry struct {
	ConnectionID  string
	SAMLRequestID string
	ReturnTo      string
	Intent        string
	ExpiresAt     time.Time
}

SAMLRelayEntry is the SP-side state associated with one opaque relay handle. The HMAC-signed cookie pattern used by OAuthStateManager would produce a token too large for the SAML 2.0 RelayState 80-byte cap, so SAML SP-initiated flows store the full state server-side and put only a short opaque handle on the wire.

type SAMLRelayStore

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

SAMLRelayStore mints opaque handles and one-shot-consumes them on the ACS callback. State is persisted through db.Store so callbacks routed to a different API instance than the one that issued the AuthnRequest still find their relay row.

func NewSAMLRelayStore

func NewSAMLRelayStore(store db.Store, now func() time.Time) *SAMLRelayStore

NewSAMLRelayStore returns a store backed by the supplied db.Store. The now function is injectable so tests can advance the clock; pass nil for time.Now.

func (*SAMLRelayStore) Consume

func (s *SAMLRelayStore) Consume(ctx context.Context, handle string) (SAMLRelayEntry, error)

Consume returns the entry for handle and atomically marks it consumed. A subsequent call with the same handle returns ErrSAMLRelayHandleInvalid, preventing replay of the same RelayState value.

func (*SAMLRelayStore) Issue

func (s *SAMLRelayStore) Issue(ctx context.Context, entry SAMLRelayEntry) (string, error)

Issue generates an opaque handle, persists the entry through db.Store, and returns the handle. The handle is short enough to fit inside any IdP's RelayState limit and contains no sensitive information.

type WorkOSAuthentication

type WorkOSAuthentication struct {
	User                 WorkOSProfile
	OrganizationID       string
	AuthenticationMethod string
	MFACompleted         bool
}

type WorkOSAuthenticationRequest

type WorkOSAuthenticationRequest struct {
	Code      string
	IPAddress string
	UserAgent string
}

type WorkOSAuthorizationRequest

type WorkOSAuthorizationRequest struct {
	RedirectURI    string
	State          string
	ScreenHint     string
	Provider       string
	ProviderScopes []string
}

type WorkOSClient

type WorkOSClient interface {
	AuthorizationURL(input WorkOSAuthorizationRequest) (string, error)
	AuthenticateWithCode(ctx context.Context, input WorkOSAuthenticationRequest) (WorkOSAuthentication, error)
	EnrollAuthFactor(ctx context.Context, input WorkOSMFAEnrollRequest) (WorkOSMFAEnrollResponse, error)
	ChallengeAuthFactor(ctx context.Context, input WorkOSMFAChallengeRequest) (WorkOSMFAChallengeResponse, error)
	AuthenticateWithTOTP(ctx context.Context, input WorkOSMFAVerifyRequest) (WorkOSAuthentication, error)
	AuthenticateWithEmailVerificationCode(ctx context.Context, input WorkOSEmailVerificationVerifyRequest) (WorkOSAuthentication, error)
}

type WorkOSEmailVerificationPendingState added in v1.0.2

type WorkOSEmailVerificationPendingState struct {
	Intent                     string `json:"intent,omitempty"`
	ReturnTo                   string `json:"return_to,omitempty"`
	Email                      string `json:"email,omitempty"`
	PendingAuthenticationToken string `json:"pending_authentication_token"`
	EmailVerificationID        string `json:"email_verification_id,omitempty"`
	ExpiresAt                  int64  `json:"expires_at"`
}

type WorkOSEmailVerificationRequired added in v1.0.2

type WorkOSEmailVerificationRequired struct {
	Email                      string
	PendingAuthenticationToken string
	EmailVerificationID        string
}

WorkOSEmailVerificationRequired is returned when WorkOS refuses a code exchange because the user's email address has not been verified. WorkOS has already emailed the user a one-time code; the pending token and verification id let the app finish the handshake once the user enters it.

func AsWorkOSEmailVerificationRequired added in v1.0.2

func AsWorkOSEmailVerificationRequired(err error) (*WorkOSEmailVerificationRequired, bool)

func (*WorkOSEmailVerificationRequired) Error added in v1.0.2

type WorkOSEmailVerificationVerifyRequest added in v1.0.2

type WorkOSEmailVerificationVerifyRequest struct {
	PendingAuthenticationToken string
	Code                       string
	IPAddress                  string
	UserAgent                  string
}

type WorkOSMFAChallengeRequest

type WorkOSMFAChallengeRequest struct {
	FactorID string
}

type WorkOSMFAChallengeResponse

type WorkOSMFAChallengeResponse struct {
	ChallengeID string
	FactorID    string
	ExpiresAt   string
}

type WorkOSMFAEnrollRequest

type WorkOSMFAEnrollRequest struct {
	UserID     string
	TOTPIssuer string
	TOTPUser   string
}

type WorkOSMFAEnrollResponse

type WorkOSMFAEnrollResponse struct {
	FactorID    string
	FactorType  string
	ChallengeID string
	ExpiresAt   string
	TOTPQRCode  string
	TOTPSecret  string
	TOTPURI     string
}

type WorkOSMFAFactor

type WorkOSMFAFactor struct {
	ID   string `json:"id"`
	Type string `json:"type"`
}

type WorkOSMFAPendingState

type WorkOSMFAPendingState struct {
	Mode                       string             `json:"mode"`
	Intent                     string             `json:"intent,omitempty"`
	ReturnTo                   string             `json:"return_to,omitempty"`
	PendingAuthenticationToken string             `json:"pending_authentication_token"`
	User                       WorkOSProfile      `json:"user"`
	AuthenticationFactors      []WorkOSMFAFactor  `json:"authentication_factors,omitempty"`
	ChallengeID                string             `json:"challenge_id,omitempty"`
	ChallengeExpiresAt         string             `json:"challenge_expires_at,omitempty"`
	TOTP                       *WorkOSPendingTOTP `json:"totp,omitempty"`
	ExpiresAt                  int64              `json:"expires_at"`
}

type WorkOSMFARequired

type WorkOSMFARequired struct {
	Mode                       string
	User                       WorkOSProfile
	PendingAuthenticationToken string
	AuthenticationFactors      []WorkOSMFAFactor
}

func AsWorkOSMFARequired

func AsWorkOSMFARequired(err error) (*WorkOSMFARequired, bool)

func (*WorkOSMFARequired) Error

func (e *WorkOSMFARequired) Error() string

type WorkOSMFAVerifyRequest

type WorkOSMFAVerifyRequest struct {
	PendingAuthenticationToken string
	AuthenticationChallengeID  string
	Code                       string
	IPAddress                  string
	UserAgent                  string
}

type WorkOSPendingTOTP

type WorkOSPendingTOTP struct {
	FactorID string `json:"factor_id"`
	QRCode   string `json:"qr_code"`
	Secret   string `json:"secret"`
	URI      string `json:"uri"`
}

type WorkOSProfile

type WorkOSProfile struct {
	ID                string          `json:"id"`
	Email             string          `json:"email"`
	OrganizationID    string          `json:"organization_id,omitempty"`
	FirstName         string          `json:"first_name,omitempty"`
	LastName          string          `json:"last_name,omitempty"`
	EmailVerified     bool            `json:"email_verified"`
	ProfilePictureURL string          `json:"profile_picture_url,omitempty"`
	RawClaims         json.RawMessage `json:"raw_claims,omitempty"`
}

type WorkOSSDKClient

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

func NewWorkOSSDKClient

func NewWorkOSSDKClient(apiKey string, clientID string) *WorkOSSDKClient

func (*WorkOSSDKClient) AuthenticateWithCode

func (*WorkOSSDKClient) AuthenticateWithEmailVerificationCode added in v1.0.2

func (c *WorkOSSDKClient) AuthenticateWithEmailVerificationCode(ctx context.Context, input WorkOSEmailVerificationVerifyRequest) (WorkOSAuthentication, error)

func (*WorkOSSDKClient) AuthenticateWithTOTP

func (c *WorkOSSDKClient) AuthenticateWithTOTP(ctx context.Context, input WorkOSMFAVerifyRequest) (WorkOSAuthentication, error)

func (*WorkOSSDKClient) AuthorizationURL

func (c *WorkOSSDKClient) AuthorizationURL(input WorkOSAuthorizationRequest) (string, error)

func (*WorkOSSDKClient) ChallengeAuthFactor

func (*WorkOSSDKClient) EnrollAuthFactor

Jump to

Keyboard shortcuts

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