Documentation
¶
Overview ¶
Package session provides public types and helpers reusable across the codebase.
Index ¶
- Variables
- func HashToken(token string) string
- func RefreshTokenNotFoundError(id shared.ID) error
- func SessionNotFoundError(id shared.ID) error
- type AuthMethod
- type RefreshToken
- func NewRefreshToken(userID shared.ID, sessionID shared.ID, token string, duration time.Duration) (*RefreshToken, error)
- func NewRefreshTokenInFamily(userID shared.ID, sessionID shared.ID, token string, family shared.ID, ...) (*RefreshToken, error)
- func ReconstituteRefreshToken(id shared.ID, userID shared.ID, sessionID shared.ID, tokenHash string, ...) *RefreshToken
- func (rt *RefreshToken) CreatedAt() time.Time
- func (rt *RefreshToken) ExpiresAt() time.Time
- func (rt *RefreshToken) Family() shared.ID
- func (rt *RefreshToken) ID() shared.ID
- func (rt *RefreshToken) IsExpired() bool
- func (rt *RefreshToken) IsRevoked() bool
- func (rt *RefreshToken) IsUsed() bool
- func (rt *RefreshToken) IsValid() bool
- func (rt *RefreshToken) MarkUsed() error
- func (rt *RefreshToken) Revoke() error
- func (rt *RefreshToken) RevokedAt() *time.Time
- func (rt *RefreshToken) SessionID() shared.ID
- func (rt *RefreshToken) TokenHash() string
- func (rt *RefreshToken) UsedAt() *time.Time
- func (rt *RefreshToken) UserID() shared.ID
- func (rt *RefreshToken) VerifyToken(token string) bool
- type RefreshTokenRepository
- type Repository
- type Session
- func New(userID shared.ID, accessToken string, ipAddress string, userAgent string, ...) (*Session, error)
- func NewWithID(id shared.ID, userID shared.ID, accessToken string, ipAddress string, ...) (*Session, error)
- func Reconstitute(id shared.ID, userID shared.ID, accessTokenHash string, ipAddress string, ...) *Session
- func (s *Session) AccessTokenHash() string
- func (s *Session) AuthMethod() AuthMethod
- func (s *Session) CreatedAt() time.Time
- func (s *Session) DeviceFingerprint() string
- func (s *Session) Expire() error
- func (s *Session) ExpiresAt() time.Time
- func (s *Session) ID() shared.ID
- func (s *Session) IDPIssuer() string
- func (s *Session) IDPSID() string
- func (s *Session) IDPSub() string
- func (s *Session) IPAddress() string
- func (s *Session) IsActive() bool
- func (s *Session) IsExpired() bool
- func (s *Session) LastActivityAt() time.Time
- func (s *Session) Revoke() error
- func (s *Session) SetAuthMethod(m AuthMethod)
- func (s *Session) SetDeviceFingerprint(fingerprint string)
- func (s *Session) SetFederatedBinding(issuer, sid, sub string)
- func (s *Session) Status() Status
- func (s *Session) UpdateActivity()
- func (s *Session) UpdatedAt() time.Time
- func (s *Session) UserAgent() string
- func (s *Session) UserID() shared.ID
- func (s *Session) VerifyToken(token string) bool
- type Status
Constants ¶
This section is empty.
Variables ¶
var ( ErrSessionNotFound = errors.New("session not found") ErrSessionExpired = errors.New("session has expired") ErrSessionRevoked = errors.New("session has been revoked") ErrRefreshTokenNotFound = errors.New("refresh token not found") ErrRefreshTokenExpired = errors.New("refresh token has expired") ErrRefreshTokenUsed = errors.New("refresh token has already been used") ErrRefreshTokenRevoked = errors.New("refresh token has been revoked") ErrTokenFamilyMismatch = errors.New("refresh token family mismatch (possible replay attack)") ErrMaxSessionsReached = errors.New("maximum number of active sessions reached") ErrInvalidToken = errors.New("invalid token") )
Domain errors for session operations.
Functions ¶
func RefreshTokenNotFoundError ¶
RefreshTokenNotFoundError returns a refresh token not found error.
func SessionNotFoundError ¶
SessionNotFoundError returns a session not found error with ID.
Types ¶
type AuthMethod ¶ added in v0.4.0
type AuthMethod string
AuthMethod records HOW a session was authenticated. It is the discriminator the per-tenant SSO-enforcement gate uses to tell a local password login apart from a federated (SSO/OAuth/SAML) login: an SSO-enforced tenant refuses password sessions (the tenant owner is the break-glass exception) but always admits federated ones — an enforced tenant must always admit the very login method it requires. The zero value is password: fail-safe for the common case and backward compatible with session rows written before this field existed.
const ( // AuthMethodPassword marks a session created by a local email+password login. AuthMethodPassword AuthMethod = "password" // AuthMethodSSO marks a session created by a federated OIDC/OAuth flow // (per-tenant identity provider or social OAuth). Exempt from SSO enforcement. AuthMethodSSO AuthMethod = "sso" // AuthMethodSAML marks a session created by a validated SAML 2.0 assertion. // Exempt from SSO enforcement (it IS an SSO login). AuthMethodSAML AuthMethod = "saml" )
func AuthMethodFromString ¶ added in v0.4.0
func AuthMethodFromString(s string) AuthMethod
AuthMethodFromString converts a persisted string to an AuthMethod, defaulting to password for empty/unknown values (fail-safe: an unrecognized method must not silently pass SSO enforcement).
func (AuthMethod) IsFederated ¶ added in v0.4.0
func (m AuthMethod) IsFederated() bool
IsFederated reports whether the session was created by an external identity provider (SSO/OAuth/SAML) rather than a local password. Federated sessions satisfy per-tenant SSO enforcement; password sessions do not. An empty/unknown method is treated as NOT federated (fail-closed: an unmarked session must not silently pass enforcement).
func (AuthMethod) IsValid ¶ added in v0.4.0
func (m AuthMethod) IsValid() bool
IsValid reports whether the auth method is a known value.
func (AuthMethod) String ¶ added in v0.4.0
func (m AuthMethod) String() string
String returns the string representation of the auth method.
type RefreshToken ¶
type RefreshToken struct {
// contains filtered or unexported fields
}
RefreshToken represents a refresh token for session renewal. Implements token rotation with family tracking for replay attack detection.
func NewRefreshToken ¶
func NewRefreshToken( userID shared.ID, sessionID shared.ID, token string, duration time.Duration, ) (*RefreshToken, error)
NewRefreshToken creates a new refresh token.
func NewRefreshTokenInFamily ¶
func NewRefreshTokenInFamily( userID shared.ID, sessionID shared.ID, token string, family shared.ID, duration time.Duration, ) (*RefreshToken, error)
NewRefreshTokenInFamily creates a new refresh token in an existing family (rotation).
func ReconstituteRefreshToken ¶
func ReconstituteRefreshToken( id shared.ID, userID shared.ID, sessionID shared.ID, tokenHash string, family shared.ID, expiresAt time.Time, usedAt *time.Time, revokedAt *time.Time, createdAt time.Time, ) *RefreshToken
ReconstituteRefreshToken creates a refresh token from persisted data.
func (*RefreshToken) CreatedAt ¶
func (rt *RefreshToken) CreatedAt() time.Time
CreatedAt returns when the token was created.
func (*RefreshToken) ExpiresAt ¶
func (rt *RefreshToken) ExpiresAt() time.Time
ExpiresAt returns when the token expires.
func (*RefreshToken) Family ¶
func (rt *RefreshToken) Family() shared.ID
Family returns the token family ID.
func (*RefreshToken) IsExpired ¶
func (rt *RefreshToken) IsExpired() bool
IsExpired returns true if the token has expired.
func (*RefreshToken) IsRevoked ¶
func (rt *RefreshToken) IsRevoked() bool
IsRevoked returns true if the token has been revoked.
func (*RefreshToken) IsUsed ¶
func (rt *RefreshToken) IsUsed() bool
IsUsed returns true if the token has been used.
func (*RefreshToken) IsValid ¶
func (rt *RefreshToken) IsValid() bool
IsValid returns true if the token is valid (not expired, used, or revoked).
func (*RefreshToken) MarkUsed ¶
func (rt *RefreshToken) MarkUsed() error
MarkUsed marks the token as used.
func (*RefreshToken) Revoke ¶
func (rt *RefreshToken) Revoke() error
Revoke marks the token as revoked.
func (*RefreshToken) RevokedAt ¶
func (rt *RefreshToken) RevokedAt() *time.Time
RevokedAt returns when the token was revoked.
func (*RefreshToken) SessionID ¶
func (rt *RefreshToken) SessionID() shared.ID
SessionID returns the associated session ID.
func (*RefreshToken) TokenHash ¶
func (rt *RefreshToken) TokenHash() string
TokenHash returns the hash of the token.
func (*RefreshToken) UsedAt ¶
func (rt *RefreshToken) UsedAt() *time.Time
UsedAt returns when the token was used.
func (*RefreshToken) UserID ¶
func (rt *RefreshToken) UserID() shared.ID
UserID returns the user ID.
func (*RefreshToken) VerifyToken ¶
func (rt *RefreshToken) VerifyToken(token string) bool
VerifyToken verifies if the provided token matches this refresh token. Uses a constant-time comparison as defense-in-depth (the authoritative match is the SQL WHERE token_hash = $1 lookup).
type RefreshTokenRepository ¶
type RefreshTokenRepository interface {
// Create creates a new refresh token.
Create(ctx context.Context, token *RefreshToken) error
// GetByID retrieves a refresh token by its ID.
GetByID(ctx context.Context, id shared.ID) (*RefreshToken, error)
// GetByTokenHash retrieves a refresh token by its hash.
GetByTokenHash(ctx context.Context, hash string) (*RefreshToken, error)
// GetByFamily retrieves all refresh tokens in a family.
GetByFamily(ctx context.Context, family shared.ID) ([]*RefreshToken, error)
// Update updates a refresh token.
Update(ctx context.Context, token *RefreshToken) error
// Delete deletes a refresh token.
Delete(ctx context.Context, id shared.ID) error
// RevokeByFamily revokes all tokens in a family (for replay attack detection).
RevokeByFamily(ctx context.Context, family shared.ID) error
// RevokeBySessionID revokes all tokens for a session.
RevokeBySessionID(ctx context.Context, sessionID shared.ID) error
// RevokeByUserID revokes all tokens for a user.
RevokeByUserID(ctx context.Context, userID shared.ID) error
// DeleteExpired deletes all expired tokens (for cleanup job).
DeleteExpired(ctx context.Context) (int64, error)
}
RefreshTokenRepository defines the interface for refresh token persistence.
type Repository ¶
type Repository interface {
// Create creates a new session.
Create(ctx context.Context, session *Session) error
// GetByID retrieves a session by its ID.
GetByID(ctx context.Context, id shared.ID) (*Session, error)
// GetByAccessTokenHash retrieves a session by access token hash.
GetByAccessTokenHash(ctx context.Context, hash string) (*Session, error)
// GetActiveByUserID retrieves all active sessions for a user.
GetActiveByUserID(ctx context.Context, userID shared.ID) ([]*Session, error)
// Update updates an existing session.
Update(ctx context.Context, session *Session) error
// Delete deletes a session.
Delete(ctx context.Context, id shared.ID) error
// RevokeAllByUserID revokes all sessions for a user.
RevokeAllByUserID(ctx context.Context, userID shared.ID) error
// RevokeAllByUserIDExcept revokes all sessions for a user except the specified session.
RevokeAllByUserIDExcept(ctx context.Context, userID shared.ID, exceptSessionID shared.ID) error
// CountActiveByUserID counts active sessions for a user.
CountActiveByUserID(ctx context.Context, userID shared.ID) (int, error)
// GetOldestActiveByUserID retrieves the oldest active session for a user.
// Returns nil if no active sessions exist.
GetOldestActiveByUserID(ctx context.Context, userID shared.ID) (*Session, error)
// DeleteExpired deletes all expired sessions (for cleanup job).
DeleteExpired(ctx context.Context) (int64, error)
}
Repository defines the interface for session persistence.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session represents an authentication session.
func New ¶
func New( userID shared.ID, accessToken string, ipAddress string, userAgent string, sessionDuration time.Duration, ) (*Session, error)
New creates a new session.
func NewWithID ¶
func NewWithID( id shared.ID, userID shared.ID, accessToken string, ipAddress string, userAgent string, sessionDuration time.Duration, ) (*Session, error)
NewWithID creates a new session entity with a pre-generated ID. Use this when you need the session ID before creating the session (e.g., for JWT).
func Reconstitute ¶
func Reconstitute( id shared.ID, userID shared.ID, accessTokenHash string, ipAddress string, userAgent string, deviceFingerprint string, expiresAt time.Time, lastActivityAt time.Time, status Status, authMethod AuthMethod, idpIssuer string, idpSID string, idpSub string, createdAt time.Time, updatedAt time.Time, ) *Session
Reconstitute creates a session from persisted data.
func (*Session) AccessTokenHash ¶
AccessTokenHash returns the hash of the access token.
func (*Session) AuthMethod ¶ added in v0.4.0
func (s *Session) AuthMethod() AuthMethod
AuthMethod returns how the session was authenticated (password vs federated SSO/SAML). Used by the per-tenant SSO-enforcement gate; the zero value is password (fail-safe for rows written before this field existed).
func (*Session) DeviceFingerprint ¶
DeviceFingerprint returns the device fingerprint.
func (*Session) IDPIssuer ¶ added in v0.4.0
IDPIssuer returns the verified id_token issuer bound to this session (empty for local/SAML sessions). Used to scope OIDC back-channel logout per-provider.
func (*Session) IDPSID ¶ added in v0.4.0
IDPSID returns the id_token session id (sid) bound to this session, or empty.
func (*Session) IDPSub ¶ added in v0.4.0
IDPSub returns the id_token subject (sub) bound to this session, or empty.
func (*Session) LastActivityAt ¶
LastActivityAt returns the last activity time.
func (*Session) SetAuthMethod ¶ added in v0.4.0
func (s *Session) SetAuthMethod(m AuthMethod)
SetAuthMethod records how the session was authenticated. Callers stamp the federated flows (SSO/OAuth = AuthMethodSSO, SAML = AuthMethodSAML) BEFORE the session is persisted; local password logins keep the AuthMethodPassword default. This is the discriminator the SSO-enforcement gate reads.
func (*Session) SetDeviceFingerprint ¶
SetDeviceFingerprint sets the device fingerprint.
func (*Session) SetFederatedBinding ¶ added in v0.4.0
SetFederatedBinding records the IdP session binding (issuer/sid/sub) captured from the verified id_token at federated login, so an OIDC Back-Channel Logout can later revoke exactly the matching session(s). Callers stamp it BEFORE the session is persisted. Empty values are stored as-is (a provider may omit sid or sub). Identity metadata only — does not bump updatedAt.
func (*Session) UpdateActivity ¶
func (s *Session) UpdateActivity()
UpdateActivity updates the last activity time.
func (*Session) VerifyToken ¶
VerifyToken verifies if the provided token matches this session.