auth

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 35 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 auth is LibraryZ's authentication and authorization layer, built on github.com/kararnab/iam: argon2id passwords, bearer sessions (short access JWTs + rotating refresh tokens with reuse detection), per-account and per-IP login throttling, and RBAC.

LibraryZ supplies the storage (GORM adapters in users.go and sessions.go, checked by iam's storetest suite) and the HTTP endpoints (handler.go); iam supplies the rest.

Index

Constants

View Source
const (
	ActionModerate policy.Action = "moderate"
	ActionDelete   policy.Action = "delete"

	ResourceContribution = "contribution"
	ResourceEdition      = "edition"
	ResourceWork         = "work"
)

Permissions checked by the router (httpauth.RequirePermission).

View Source
const (
	DefaultAccessTokenTTL  = 15 * time.Minute
	DefaultRefreshTokenTTL = 30 * 24 * time.Hour
	DefaultSessionMaxAge   = 365 * 24 * time.Hour
)

Default token lifetimes.

View Source
const (
	ResetTokenTTL        = time.Hour
	VerificationTokenTTL = 48 * time.Hour
)

Lifetimes of the emailed recovery tokens (the emails quote them).

View Source
const (
	KindPasswordReset     = "password_reset"
	KindEmailVerification = "email_verification"
)

Email kinds, as logged by onemailer (password_reset_sent, …) and stored in account_emails.

View Source
const (
	EmailCooldown = 2 * time.Minute
	EmailDailyCap = 5
)

Per-account caps on recovery emails, per kind: no more than one every EmailCooldown and EmailDailyCap per 24 hours. They protect a person's inbox, which gateway limits can't (they see IPs, not accounts).

View Source
const RoleModerator = "moderator"

RoleModerator may approve/reject contributions and take works and editions down. Granted out-of-band; see UserRole.

Variables

View Source
var (
	SubjectID      = middleware.SubjectID
	ParseSubjectID = middleware.ParseSubjectID
)

Subject ids cross the iam boundary as decimal strings; see middleware.SubjectID / middleware.ParseSubjectID.

View Source
var PasswordPolicy = password.Policy{MinLength: 8, MaxLength: 1024}

PasswordPolicy keeps LibraryZ's 8-character minimum (iam's DefaultPolicy asks for 12). The maximum bounds hashing cost.

Functions

func PurgeAccountEmails

func PurgeAccountEmails(ctx context.Context, db *gorm.DB, now time.Time) (int, error)

PurgeAccountEmails deletes send records older than the daily window.

Types

type AccountEmail

type AccountEmail struct {
	ID     uint      `gorm:"primaryKey"`
	UserID uint      `gorm:"not null;index:idx_account_emails_user_kind_sent,priority:1"`
	Kind   string    `gorm:"not null;size:32;index:idx_account_emails_user_kind_sent,priority:2"`
	SentAt time.Time `gorm:"not null;index:idx_account_emails_user_kind_sent,priority:3"`
}

AccountEmail records each reset or verification email sent to an account, to cap them per account (a cooldown and a daily limit) so no one can flood a person's inbox by rotating IPs. Rows older than a day are purged on a ticker.

type Auth

type Auth struct {
	Service  iam.Service
	HTTP     *httpauth.Middleware
	Users    *Users
	Sessions *Sessions
	Tokens   *Tokens
	// Recovery is password reset and email verification (iam.Recovery).
	Recovery iam.Recovery
	// contains filtered or unexported fields
}

Auth bundles the iam service and its HTTP adapter.

func New

func New(cfg Config) (*Auth, error)

New builds the auth layer.

type Config

type Config struct {
	DB *gorm.DB

	// JWTSecret signs access tokens (HS256, at least 32 bytes).
	// JWTPreviousSecret, if set, still verifies them, so the secret can be
	// rotated with a rolling restart.
	JWTSecret         string
	JWTPreviousSecret string

	// AccessTokenTTL is the access-token lifetime. RefreshTokenTTL is how
	// long a session survives unused: every refresh restarts it, so an
	// active client stays signed in (as before iam). SessionMaxAge caps a
	// session's total lifetime regardless. Zero means the defaults above.
	AccessTokenTTL  time.Duration
	RefreshTokenTTL time.Duration
	SessionMaxAge   time.Duration

	// VerifySessionOnAccess checks on every request that the access token's
	// session still exists, so logout / logout-all / session revocation take
	// effect immediately instead of when the access token expires, at the
	// cost of one primary-key lookup per authenticated request.
	VerifySessionOnAccess bool

	// LoadSubjectOnAccess loads the user on every authenticated request, so
	// a granted or revoked role and a disabled or deleted user take effect
	// at once instead of when the access token expires (roles otherwise
	// come from the token). Two small lookups (users, user_roles) per
	// authenticated request. cmd/libraryz turns it on by default.
	LoadSubjectOnAccess bool

	// PerLogin and PerIP throttle failed logins. Nil means iam's in-memory
	// limiters, which are per-process: use a shared one (redisstore) when
	// running more than one instance.
	PerLogin ratelimit.Limiter
	PerIP    ratelimit.Limiter

	// TrustedProxies are the networks whose X-Forwarded-For is believed
	// when working out the client IP (Kong, load balancers). Without it,
	// behind a proxy every client shares the proxy's IP and the per-IP
	// login limit becomes global.
	TrustedProxies []netip.Prefix

	// Now is the clock (tests); nil means time.Now.
	Now func() time.Time
}

Config configures New.

type Handler

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

func NewHandler

func NewHandler(a *Auth, m Mail) *Handler

NewHandler serves the auth endpoints. m configures the recovery emails; the zero Mail means mail is off.

func (*Handler) CompleteEmailVerification

func (h *Handler) CompleteEmailVerification(w http.ResponseWriter, r *http.Request)

CompleteEmailVerification (POST /auth/email-verification/complete, anonymous: the token is the proof) marks the address as verified, as long as it is still the account's address.

func (*Handler) CompletePasswordReset

func (h *Handler) CompletePasswordReset(w http.ResponseWriter, r *http.Request)

CompletePasswordReset (POST /auth/password-reset/complete, anonymous) sets a new password with a reset token and signs the account out everywhere. A password the policy rejects leaves the token usable.

func (*Handler) HealthCheck

func (h *Handler) HealthCheck(w http.ResponseWriter, r *http.Request)

func (*Handler) ListSessions

func (h *Handler) ListSessions(w http.ResponseWriter, r *http.Request)

ListSessions returns the caller's active sessions.

func (*Handler) Login

func (h *Handler) Login(w http.ResponseWriter, r *http.Request)

func (*Handler) Logout

func (h *Handler) Logout(w http.ResponseWriter, r *http.Request)

Logout ends the session the given refresh token belongs to. It doesn't require an access token, so a client whose access token already expired can still log out cleanly. Always 204 for well-formed requests.

func (*Handler) LogoutAll

func (h *Handler) LogoutAll(w http.ResponseWriter, r *http.Request)

LogoutAll ends every session of the calling user, on every device. Refreshing stops at once; outstanding access tokens keep working until they expire unless VerifySessionOnAccess is on.

func (*Handler) Me

func (h *Handler) Me(w http.ResponseWriter, r *http.Request)

func (*Handler) Refresh

func (h *Handler) Refresh(w http.ResponseWriter, r *http.Request)

Refresh exchanges a refresh token for a new access + refresh pair. The presented refresh token is spent; presenting it again revokes the whole session (reuse detection).

func (*Handler) RequestEmailVerification

func (h *Handler) RequestEmailVerification(w http.ResponseWriter, r *http.Request)

RequestEmailVerification (POST /me/email-verification, authenticated) emails the caller a fresh verification link, replacing earlier ones. 204 when already verified; 429 when the account asked too recently.

func (*Handler) RequestPasswordReset

func (h *Handler) RequestPasswordReset(w http.ResponseWriter, r *http.Request)

RequestPasswordReset (POST /auth/password-reset, anonymous) emails a reset link if the address has an account. The answer is 202 whether or not it does, and whether or not the account's email cap held the message back, so it can't be used to find out which addresses are registered.

func (*Handler) RevokeSession

func (h *Handler) RevokeSession(w http.ResponseWriter, r *http.Request)

RevokeSession ends one of the caller's sessions. Revoking a session that doesn't exist (or isn't theirs) is a 404.

func (*Handler) SignUp

func (h *Handler) SignUp(w http.ResponseWriter, r *http.Request)

type HealthResponse

type HealthResponse struct {
	Status string `json:"status"`
	Time   string `json:"time"`
}

type Identity

type Identity struct {
	Provider   string `gorm:"primaryKey;size:64"`
	ProviderID string `gorm:"primaryKey;size:320"`
	UserID     uint   `gorm:"not null;index"`
	User       User   `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE"`
	CreatedAt  time.Time
}

Identity links a provider identity ("password" + normalized email) to a user. One user may have several.

type Mail

type Mail struct {
	// Outbox delivers messages; nil means mail is off (nothing is sent,
	// and requests are answered as usual).
	Outbox Outbox
	// PublicURL is the web app's origin; links are
	// {PublicURL}/reset-password?token=… and /verify-email?token=….
	PublicURL string
	// CanReply adds "Questions? Reply to this email." (a Reply-To is set).
	CanReply bool
}

Mail configures the recovery emails.

type MeResponse

type MeResponse struct {
	ID    uint     `json:"id"`
	Email string   `json:"email"`
	Name  string   `json:"name"`
	Roles []string `json:"roles"`
	// EmailVerified is true once the user followed a verification link for
	// their current address.
	EmailVerified bool `json:"email_verified"`
	// IsModerator is read from the database, so it reflects a promotion
	// immediately — though moderator-only routes check the roles in the
	// access token, which catch up at the next refresh.
	IsModerator bool `json:"is_moderator"`
}

MeResponse is the shape of /auth/me.

type OneTimeToken

type OneTimeToken struct {
	ID        string    `gorm:"primaryKey;size:64"`
	TokenHash []byte    `gorm:"not null;uniqueIndex"`
	Purpose   string    `gorm:"not null;size:32;index:idx_one_time_tokens_subject_purpose,priority:2"`
	SubjectID string    `gorm:"not null;size:32;index:idx_one_time_tokens_subject_purpose,priority:1"`
	Login     string    `gorm:"size:320"` // password reset: the login
	Email     string    `gorm:"size:320"` // email verification: the address
	CreatedAt time.Time `gorm:"not null"`
	ExpiresAt time.Time `gorm:"not null;index"`
	UsedAt    *time.Time
}

OneTimeToken backs iam's onetime.Store: single-use, expiring password reset and email verification tokens. Only the SHA-256 of the secret is stored. A new request deletes the subject's earlier tokens of the same purpose, so the table stays small; expired rows are purged on a ticker.

type Outbox

type Outbox interface {
	Enqueue(m onemailer.Message) bool
}

Outbox accepts messages for delivery off the request path: *onemailer.Queue in production, a recorder in tests.

type PasswordCredential

type PasswordCredential struct {
	Login     string `gorm:"primaryKey;size:320"`
	Hash      string `gorm:"not null"`
	UpdatedAt time.Time
}

PasswordCredential is a password hash by normalized login. It exists before its user does (iam registers the credential, then creates and links the subject), so it is keyed by login, not user id.

type Session

type Session struct {
	ID         string         `gorm:"primaryKey;size:64"`
	SubjectID  string         `gorm:"not null;index;size:32"`
	Mode       string         `gorm:"not null;size:16"`
	TokenHash  []byte         `gorm:"not null;uniqueIndex"`
	CreatedAt  time.Time      `gorm:"not null"`
	LastUsedAt time.Time      `gorm:"not null"`
	ExpiresAt  time.Time      `gorm:"not null;index"`
	Attrs      datatypes.JSON // map[string]string: ip, user_agent, provider
}

Session is an iam session (a refresh-token family in bearer mode). Only the SHA-256 of the current refresh token is stored.

type SessionResponse

type SessionResponse struct {
	ID         string    `json:"id"`
	CreatedAt  time.Time `json:"created_at"`
	LastUsedAt time.Time `json:"last_used_at"`
	ExpiresAt  time.Time `json:"expires_at"`
	IP         string    `json:"ip,omitempty"`
	UserAgent  string    `json:"user_agent,omitempty"`
	// Current is true for the session the request's access token belongs to.
	Current bool `json:"current"`
}

SessionResponse describes one of the caller's sessions (devices).

type SessionRotation

type SessionRotation struct {
	TokenHash []byte    `gorm:"primaryKey"`
	SessionID string    `gorm:"not null;index;size:64"`
	Session   Session   `gorm:"foreignKey:SessionID;constraint:OnDelete:CASCADE"`
	RotatedAt time.Time `gorm:"not null"`
}

SessionRotation remembers a refresh token that was rotated away, so presenting it again is detected as reuse.

type Sessions

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

Sessions implements session.Store over the sessions and session_rotations tables.

func NewSessions

func NewSessions(db *gorm.DB) *Sessions

NewSessions returns the session store.

func (*Sessions) Create

func (s *Sessions) Create(ctx context.Context, sess *session.Session) error

Create implements session.Store.

func (*Sessions) Delete

func (s *Sessions) Delete(ctx context.Context, id string) error

Delete implements session.Store. Rotated hashes are deleted explicitly rather than relying on ON DELETE CASCADE, which sqlite only enforces with foreign_keys=ON.

func (*Sessions) DeleteBySubject

func (s *Sessions) DeleteBySubject(ctx context.Context, subjectID, exceptID string) (int, error)

DeleteBySubject implements session.Store.

func (*Sessions) Get

func (s *Sessions) Get(ctx context.Context, id string) (*session.Session, error)

Get implements session.Store.

func (*Sessions) GetByTokenHash

func (s *Sessions) GetByTokenHash(ctx context.Context, hash []byte) (*session.Session, session.TokenState, error)

GetByTokenHash implements session.Store: the current token first, then the rotated ones.

func (*Sessions) ListBySubject

func (s *Sessions) ListBySubject(ctx context.Context, subjectID string) ([]*session.Session, error)

ListBySubject implements session.Store, oldest first.

func (*Sessions) PurgeExpired

func (s *Sessions) PurgeExpired(ctx context.Context, now time.Time) (int, error)

PurgeExpired implements session.Purger: it deletes sessions whose absolute expiry is at or before now (with their rotated hashes), and returns how many. iam never returns them (the manager checks expiry), so this only bounds table growth. Idle-expired sessions linger until their absolute expiry; they're just as unusable.

func (*Sessions) Rotate

func (s *Sessions) Rotate(ctx context.Context, id string, oldHash, newHash []byte, at time.Time) error

Rotate implements session.Store. The compare-and-swap is a single UPDATE ... WHERE token_hash = old, so of two concurrent rotations only one matches a row (Postgres re-checks the WHERE after the row lock; sqlite serializes writers).

func (*Sessions) Touch

func (s *Sessions) Touch(ctx context.Context, id string, at time.Time) error

Touch implements session.Store.

type TokenResponse

type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	TokenType    string `json:"token_type"`
	// ExpiresIn is the access token's lifetime in seconds.
	ExpiresIn int `json:"expires_in"`
}

TokenResponse is what signup, login and refresh return. Tokens travel in the body only (no Authorization response header).

type Tokens

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

Tokens is iam's onetime.Store over GORM: password-reset and email-verification tokens. Checked by iam's storetest.Tokens suite.

func NewTokens

func NewTokens(db *gorm.DB) *Tokens

NewTokens returns a token store over db.

func (*Tokens) Consume

func (s *Tokens) Consume(ctx context.Context, hash []byte, purpose onetime.Purpose, at time.Time) (*onetime.Token, error)

Consume marks the token used at `at`, but only if it has this purpose and is still unused and unexpired. A single conditional UPDATE, so of two concurrent calls at most one succeeds.

func (*Tokens) Create

func (s *Tokens) Create(ctx context.Context, t *onetime.Token) error

Create persists a new token.

func (*Tokens) DeleteBySubject

func (s *Tokens) DeleteBySubject(ctx context.Context, subjectID string, purpose onetime.Purpose) error

DeleteBySubject removes a subject's tokens of one purpose.

func (*Tokens) GetByTokenHash

func (s *Tokens) GetByTokenHash(ctx context.Context, hash []byte) (*onetime.Token, error)

GetByTokenHash returns a token, used or not, or onetime.ErrNotFound.

func (*Tokens) PurgeExpired

func (s *Tokens) PurgeExpired(ctx context.Context, now time.Time) (int, error)

PurgeExpired deletes tokens that expired before now (used ones too: a used token is never usable again). Returns how many were removed.

type User

type User struct {
	ID    uint   `gorm:"primaryKey"`
	Email string `gorm:"uniqueIndex"`
	Name  string
	// Disabled users can't log in or refresh (iam rejects them).
	Disabled  bool `gorm:"not null;default:false"`
	CreatedAt time.Time
	// EmailVerifiedAt is set when the user follows an email-verification
	// link for their current address; nil means unverified.
	EmailVerifiedAt *time.Time
}

User is the application's subject: the row iam's Subject.ID points at (as a decimal string). It holds profile data only; how someone signs in lives in Identity + PasswordCredential, and what they may do in UserRole.

type UserRole

type UserRole struct {
	UserID uint   `gorm:"primaryKey;autoIncrement:false"`
	Role   string `gorm:"primaryKey;size:64"`
	User   User   `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE"`
}

UserRole grants a role (see Roles) to a user. There is no admin endpoint; promote out-of-band:

INSERT INTO user_roles (user_id, role)
SELECT id, 'moderator' FROM users WHERE email = 'you@example.com';

type Users

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

Users implements iam.UserStore and password.CredentialStore over the users, user_roles, identities and password_credentials tables.

LibraryZ keeps numeric user ids everywhere else (contributions, user_books, rec_*, editions.uploaded_by), so ids cross the iam boundary as decimal strings.

func NewUsers

func NewUsers(db *gorm.DB) *Users

NewUsers returns the user store.

func (*Users) CreateCredential

func (u *Users) CreateCredential(ctx context.Context, login, encodedHash string) error

CreateCredential implements password.CredentialStore.

func (*Users) CreateSubject

func (u *Users) CreateSubject(ctx context.Context, id provider.Identity, grant iam.SignupGrant) (string, error)

CreateSubject implements iam.IdentityStore: a users row (with the display name from the sign-up form, grant.Profile["name"]) plus the granted roles, in one transaction. It doesn't link the identity (iam does).

func (*Users) DeleteCredential

func (u *Users) DeleteCredential(ctx context.Context, login string) error

DeleteCredential implements password.CredentialStore.

func (*Users) DeleteSubject

func (u *Users) DeleteSubject(ctx context.Context, subjectID string) error

DeleteSubject implements iam.SubjectDeleter: iam calls it when a sign-up fails after CreateSubject. Roles and identities are deleted explicitly (sqlite only enforces ON DELETE CASCADE with foreign_keys=ON).

func (*Users) GetCredential

func (u *Users) GetCredential(ctx context.Context, login string) (string, error)

GetCredential implements password.CredentialStore.

func (*Users) LinkIdentity

func (u *Users) LinkIdentity(ctx context.Context, subjectID string, id provider.Identity) error

LinkIdentity implements iam.IdentityStore.

func (*Users) LoadSubject

func (u *Users) LoadSubject(ctx context.Context, subjectID string) (*iam.Subject, error)

LoadSubject implements iam.SubjectLoader. Roles come back sorted by name.

func (*Users) ResolveIdentity

func (u *Users) ResolveIdentity(ctx context.Context, prov, providerID string) (string, error)

ResolveIdentity implements iam.IdentityStore.

func (*Users) UnlinkIdentity

func (u *Users) UnlinkIdentity(ctx context.Context, subjectID, prov, providerID string) error

UnlinkIdentity implements iam.IdentityStore.

func (*Users) UpdateCredential

func (u *Users) UpdateCredential(ctx context.Context, login, encodedHash string) error

UpdateCredential implements password.CredentialStore.

Jump to

Keyboard shortcuts

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