Documentation
¶
Overview ¶
Package auth implements the auth_management business module.
doc.go owns the package overview. The module supplies a session-cookie login flow on top of user_management: it verifies passwords through the configured passhash.Hasher, issues cryptographically random session IDs, persists session metadata to a pluggable SessionStore, and emits audit events on success and failure.
Design:
- Composable: catalog wires NewModule and consumes Compose() to declare Provides/Requires.
- Chainable: pk-pro embeds *Module and extends Service() with SSO, MFA, rate limiting, and risk scoring without changing the public OSS contract.
- Store-agnostic: callers either supply their own SessionStore or use the default sqlite store via WithSQLiteDSN.
ADR: ADR-0009 (ports-only module communication), ADR-0017 (composition through dependency injection), ADR-0029 (file purpose declaration). Convention: C-14 (every Go file declares its purpose).
Index ¶
- Constants
- Variables
- type AuthService
- type Credentials
- type Handler
- type LoginPolicy
- type Module
- type Option
- func WithAdminRegistrar(r portslib.AdminRegistrar) Option
- func WithAuditEmitter(a audit.AuditEmitter) Option
- func WithHasher(h passhash.Hasher) Option
- func WithHealthRegistrar(r portslib.HealthRegistrar) Option
- func WithLoginPolicy(p LoginPolicy) Option
- func WithSQLiteDB(db *sql.DB) Option
- func WithSQLiteDSN(dsn string) Option
- func WithSQLiteDriver(driverName string) Option
- func WithSessionStore(s SessionStore) Option
- func WithSessionTTL(d time.Duration) Option
- func WithUserReader(r user.UserBoundaryReader) Option
- type Session
- type SessionStore
Constants ¶
const ( ModuleID = "auth_management" ModuleName = "Auth Management" ModuleDescription = "Session-cookie login flow on top of user_management." ModuleVersion = "0.0.0" ReleaseVersion = portslib.ReleaseVersion )
Module metadata constants used by both the catalog and admin shell.
const APIPath = "/api/v1/auth/sessions"
APIPath is the canonical HTTP base path for the session surface.
const EntityName = "Session"
EntityName is the stable display name of the Session entity.
Variables ¶
var ( ErrInvalidCredentials = errors.New("auth: invalid credentials") ErrSessionExpired = errors.New("auth: session expired") ErrSessionRevoked = errors.New("auth: session revoked") ErrNoCredentials = errors.New("auth: credentials require email or username") ErrUserInactive = errors.New("auth: user is inactive") ErrPolicyDenied = errors.New("auth: login policy denied") // ErrInvalidRequest marks a malformed login request the caller must fix // (missing tenant_id, missing identifier, or missing password). Handlers // map it to HTTP 400. It is distinct from ErrInvalidCredentials so that a // well-formed-but-wrong attempt (401) is never confused with a malformed // request, and so neither path leaks whether a user exists. ErrInvalidRequest = errors.New("auth: invalid request") )
Sentinel errors returned by AuthService. Callers should not branch on the underlying passhash error to avoid leaking whether the user exists.
Functions ¶
This section is empty.
Types ¶
type AuthService ¶
type AuthService interface {
Login(ctx context.Context, tenantID string, creds Credentials) (*Session, error)
Logout(ctx context.Context, sessionID string) error
ValidateSession(ctx context.Context, sessionID string) (*Session, error)
InvalidateAllSessions(ctx context.Context, userID string) error
}
AuthService is the public port other modules use to drive the login lifecycle.
type Credentials ¶
Credentials carries the inputs to Login. Exactly one of Email and Username must be set; Password is always required. The struct is value-typed so callers cannot accidentally retain a pointer to credential plaintext.
func (Credentials) Identifier ¶
func (c Credentials) Identifier() string
Identifier returns whichever of Email or Username the credentials carry. Returns an empty string when neither is set.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler exposes the auth session HTTP surface.
func NewHandler ¶
func NewHandler(svc AuthService) *Handler
NewHandler constructs a Handler wired to the given service.
func (*Handler) RegisterRoutes ¶
RegisterRoutes mounts the handler under the canonical APIPath on the given mux.
type LoginPolicy ¶
type LoginPolicy interface {
AllowLogin(ctx context.Context, tenantID, identifier string) error
RecordFailure(ctx context.Context, tenantID, identifier string)
RecordSuccess(ctx context.Context, tenantID, identifier string)
}
LoginPolicy is the mandatory policy hook auth_management consults before issuing a session and after each attempt. Hosts provide rate limiting, lockout, and risk scoring through this boundary.
type Module ¶
type Module struct {
// contains filtered or unexported fields
}
Module is the OSS auth_management module. Pro embeds *Module and adds Pro-only fields/methods.
func MustNewModule ¶
MustNewModule is the panic-on-error variant of NewModule.
Panics if NewModule returns an error (for example, when required options such as a store or DSN are missing or the backing database cannot be opened). Use NewModule when an error return is preferred.
func (*Module) Compose ¶
func (m *Module) Compose() pkmodule.Composable
Compose returns the module.Composable representation the catalog consumes when validating port wiring.
func (*Module) HTTPHandler ¶
HTTPHandler returns the wired HTTP handler so the host application can mount it on its router of choice.
func (*Module) Migrations ¶
Migrations exposes the embedded migrations FS for app-level migration runners.
func (*Module) Service ¶
func (m *Module) Service() AuthService
Service returns an AuthService backed by this module's session store.
func (*Module) SessionTTL ¶
SessionTTL returns the configured session lifetime.
func (*Module) Sessions ¶
func (m *Module) Sessions() SessionStore
Sessions returns the underlying SessionStore so Pro can wrap with auditing.
type Option ¶
type Option func(*config)
Option configures a Module at construction time.
func WithAdminRegistrar ¶
func WithAdminRegistrar(r portslib.AdminRegistrar) Option
WithAdminRegistrar wires the host application's admin shell.
func WithAuditEmitter ¶
func WithAuditEmitter(a audit.AuditEmitter) Option
WithAuditEmitter wires an audit emitter used to record login successes and failures. Optional; absent emitter silently disables auditing.
func WithHasher ¶
WithHasher selects the password hasher used to verify the stored PassHash. The default mirrors user_management: bcrypt at passhash.DefaultCost.
func WithHealthRegistrar ¶
func WithHealthRegistrar(r portslib.HealthRegistrar) Option
WithHealthRegistrar wires the host application's health registrar.
func WithLoginPolicy ¶
func WithLoginPolicy(p LoginPolicy) Option
WithLoginPolicy installs the mandatory policy hook consulted on every login.
func WithSQLiteDB ¶ added in v0.1.0
WithSQLiteDB wires the default sqlite session store on top of a caller-owned *sql.DB. Use this when several modules must share one connection pool over a single SQLite file — the host opens one *sql.DB (typically with SetMaxOpenConns(1)) and hands the same handle to every module so they cannot race each other's schema creation or fan out into independent pools. The caller retains ownership of the *sql.DB lifecycle (Close). It wins over WithSQLiteDSN but loses to an explicit WithSessionStore.
func WithSQLiteDSN ¶
WithSQLiteDSN selects the default sqlite store using the caller-registered driver. The driver name defaults to "sqlite" (used by modernc.org/sqlite).
func WithSQLiteDriver ¶
WithSQLiteDriver overrides the sql.Open driver name used by WithSQLiteDSN. The default ("sqlite") matches modernc.org/sqlite.
func WithSessionStore ¶
func WithSessionStore(s SessionStore) Option
WithSessionStore wires a caller-provided SessionStore implementation.
func WithSessionTTL ¶
WithSessionTTL overrides the default session lifetime. The OSS default is 24h; production deployments typically lower this.
func WithUserReader ¶
func WithUserReader(r user.UserBoundaryReader) Option
WithUserReader wires the user_management read-port used to resolve credentials. Auth needs at least the PassHash and Active fields on the returned user.User.
type Session ¶
type Session struct {
ID string `json:"id"`
UserID string `json:"user_id"`
TenantID string `json:"tenant_id"`
IssuedAt time.Time `json:"issued_at"`
ExpiresAt time.Time `json:"expires_at"`
RevokedAt *time.Time `json:"revoked_at,omitempty"`
}
Session is the persisted authentication artifact returned by Login and consumed by ValidateSession. Sessions are revoked by setting RevokedAt and expire automatically once the wall clock passes ExpiresAt.
type SessionStore ¶
type SessionStore interface {
Create(ctx context.Context, s *Session) error
Get(ctx context.Context, id string) (*Session, error)
Revoke(ctx context.Context, id string) error
RevokeByUser(ctx context.Context, userID string) error
}
SessionStore is the persistence contract for sessions. Implementations must be safe for concurrent use.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package migrations exposes the embedded auth_management migration files as an io/fs.FS so application-level runners can replay them.
|
Package migrations exposes the embedded auth_management migration files as an io/fs.FS so application-level runners can replay them. |
|
Package store defines the persistence contract for auth_management.
|
Package store defines the persistence contract for auth_management. |
|
sqlite
Package sqlite is the default SessionStore implementation for auth_management backed by database/sql.
|
Package sqlite is the default SessionStore implementation for auth_management backed by database/sql. |