user

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 27 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 (

	// MinPasswordLength is the only complexity rule we enforce. NIST
	// SP 800-63B recommends against required-character classes (they
	// reduce real-world security by encouraging predictable
	// substitutions). 12 chars is the post-2024 floor for low-stakes
	// systems; we'd raise to 16 for a financial-services tenant if a
	// DP requested.
	MinPasswordLength = 12

	// PasswordResetTokenTTL is how long a reset token remains valid.
	// 1 hour matches the GitHub / AWS Cognito / Auth0 default — long
	// enough for the recipient to find the email and click, short
	// enough that a leaked token isn't useful days later.
	PasswordResetTokenTTL = 1 * time.Hour
)
View Source
const (
	// ResetSendsPerWindow / ResetSendWindow bound how many reset EMAILS one
	// account can be sent. The per-IP limiter on /v1/auth slows credential
	// stuffing but does nothing against one caller pointing many requests at
	// a single victim's address, each inside the IP budget — flooding their
	// inbox and burning SMTP quota.
	//
	// The budget is derived from password_reset_tokens itself: the rows ARE
	// the record of what was sent, so the cap is cluster-wide by
	// construction, survives restarts, and needs no Redis. It replaced a
	// Redis bucket (ha-14 PR-B) that silently vanished wherever Redis was
	// unreachable — verified 2026-08-31: 8 consecutive sends, 0 refusals —
	// and before that an in-process map that degraded to 3xN per hour at N
	// replicas. Keyed on the ACCOUNT rather than the typed string, so it
	// counts what was actually delivered.
	ResetSendsPerWindow = 3
	ResetSendWindow     = time.Hour
)
View Source
const (
	// DeviceCookieName is the cookie that marks a browser that signed in.
	// It holds 32 random bytes as hex and is sent only to /v1/auth.
	DeviceCookieName = "hardcount_device"
)

The sign-in throttle (ADR-094, amended 2026-10-18). It slows repeated wrong passwords instead of locking the account.

Every sign-in attempt is counted before the password is checked, under one or two subjects:

  • A browser that has signed in to this email before (it sends the hardcount_device cookie) is counted under that browser and email only. Guesses from elsewhere never hold it out.
  • Any other browser is counted twice: under its address and the email, which stops one source early; and under the email alone, which caps guesses spread over many addresses.

Once a subject reaches its threshold, each further attempt starts a wait: 1 minute, then 2, 4 and 8, then 15 minutes per attempt. An attempt made during a wait is refused before any account lookup or bcrypt, and is not counted. A count whose last attempt is over 24 hours old starts again. Proof of the account (the right password, a completed password reset, an accepted invite) marks the browser and clears this address's count. Only the right password from a browser the email's count held clears that count too (SignedIn says why).

Every subject is an HMAC keyed from HARDCOUNT_ENCRYPTION_KEY, and the typed email is used as typed (trimmed, lower-cased), so an email with no account is counted and answered exactly like a real one. All times come from the database clock, so every copy of the server shares one count.

Variables

View Source
var ErrBadCredentials = errs.New("bad_credentials", "invalid email or password")

ErrBadCredentials covers both "no such user" and "wrong password". Same error for both so an attacker can't enumerate registered emails by timing the response. Handler maps to 401.

View Source
var ErrEmailTaken = errs.AlreadyExists("email", "an account with this email already exists")

ErrEmailTaken is returned when Create hits the email unique violation. Surfaced to the API as 409.

View Source
var ErrResetSendCapped = errors.New("user: password-reset send cap reached for this account")

Store is the persistence boundary for user accounts, the user↔tenant join, and password reset tokens. ADR-011. ErrResetSendCapped means this account has already been sent ResetSendsPerWindow reset links inside ResetSendWindow, so no token was issued. It is not an error the caller surfaces: the endpoint's response is fixed either way (the fixed body is the account-enumeration defence).

Functions

func HashPassword

func HashPassword(plaintext string) (string, error)

HashPassword applies bcrypt to a candidate plaintext. Validates length and the breached-password list before hashing. Returns the hash suitable for `users.password_hash`.

func ThrottleKey

func ThrottleKey(encryptionKeyHex string) ([]byte, error)

ThrottleKey derives the throttle's HMAC key from HARDCOUNT_ENCRYPTION_KEY (64 hex characters) with HKDF. With no key, as in local development, it derives from a fixed value: the subjects then still hold no email or address, but anyone with the code can test a guess against them. Production refuses to start without a key.

func ValidatePassword

func ValidatePassword(plaintext string) error

ValidatePassword runs the complexity checks without hashing — used at the start of HashPassword and exposed for the password-reset confirm endpoint to give an early 422 on bad input before doing any crypto work.

func VerifyPassword

func VerifyPassword(hash, plaintext string) error

VerifyPassword does a constant-time bcrypt compare. Returns nil on match, a generic ErrBadCredentials on mismatch (no leaking of "user exists vs password wrong"), or a wrapped error on implementation failures.

Types

type AuditRecorder

type AuditRecorder interface {
	Log(ctx context.Context, tenantID, action, resourceType, resourceID, resourceLabel string, metadata map[string]any) error
}

AuditRecorder is the narrow audit surface the auth handler needs — kept here (not an import of *audit.Logger) so internal/user stays decoupled. Production wires *audit.Logger via SetAuditLogger in router.go. Optional: nil = the handler skips audit writes (login/logout/reset still work; they just leave no row), which is the safe default for the unit tests that build a bare handler.

type ConfirmResetReq

type ConfirmResetReq struct {
	Token    string `json:"token"`
	Password string `json:"password"`
}

type EmailSender

type EmailSender interface {
	SendPasswordReset(ctx context.Context, tenantID, email, resetLink string) error
}

EmailSender is the narrow surface this handler uses to dispatch password-reset emails. Satisfied in production by an adapter over internal/email's Sender / OutboxSender. SMTP misconfiguration surfaces as a SendPasswordReset error logged here; the response to the user stays generic to prevent enumeration.

type Handler

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

Handler wires the dashboard auth endpoints. ADR-011.

Routes (mounted under /v1/auth):

POST /login                     — email + password → mint cookie
POST /logout                    — clear cookie + revoke session
POST /password-reset/request    — email → send reset link
POST /password-reset/confirm    — token + new password → set

func NewHandler

func NewHandler(users *Service, sessions SessionService, cookie session.CookieConfig, emailSender EmailSender, dashboardBaseURL string, smtpConfigured bool) *Handler

NewHandler wires the dependencies. emailSender is required — password-reset requests will nil-panic if it's nil. dashboardBaseURL is the canonical dashboard origin used to build password-reset links; it is never derived from the request (Host header) to prevent host-header poisoning / token theft. When empty, password-reset emails are not sent (requestPasswordReset fails safe). Set it to your dashboard URL — in split-origin dev (Vite on :5173 vs API on :8080) that's the SPA URL.

func (*Handler) Routes

func (h *Handler) Routes() chi.Router

Routes returns the dashboard auth surface. Mount under /v1/auth. All routes are intentionally outside session middleware: they're either pre-session (login, password-reset) or take the cookie via r.Cookie directly (logout, mode).

func (*Handler) SetAuditLogger

func (h *Handler) SetAuditLogger(a AuditRecorder)

SetAuditLogger wires the audit recorder used to log authenticated auth events (login, logout, mode change, password reset). Without it those events are not audited. Failed logins are NOT routed here — they're pre-auth (no tenant to scope a per-tenant audit row, and surfacing email-existence in the log would be an enumeration oracle), so they go to the structured security log instead.

func (*Handler) SetLoginThrottle

func (h *Handler) SetLoginThrottle(t *LoginThrottle)

SetLoginThrottle wires the sign-in throttle (throttle.go). Production always wires it in internal/api; the e2e tests there prove it. A handler without one checks every password, as before the throttle.

type LoginReq

type LoginReq struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

type LoginResponse

type LoginResponse struct {
	UserID    string `json:"user_id"`
	TenantID  string `json:"tenant_id"`
	Email     string `json:"email"`
	Livemode  bool   `json:"livemode"`
	ExpiresAt string `json:"expires_at"`
}

LoginResponse is POST /v1/auth/login's 200.

type LoginThrottle

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

LoginThrottle counts sign-in attempts in the login_throttle table.

func NewLoginThrottle

func NewLoginThrottle(db *postgres.DB, key []byte, cookie session.CookieConfig) *LoginThrottle

NewLoginThrottle builds the throttle. key comes from ThrottleKey; cookie gives the hardcount_device cookie the session cookie's Domain, Secure and SameSite.

func (*LoginThrottle) Cleanup

func (t *LoginThrottle) Cleanup(ctx context.Context) (int, error)

Cleanup deletes rows nothing reads any more: no attempt for 24 hours, no wait still running, and no sign-in from that browser within 180 days. The leader runs it with the other cleanup steps.

func (*LoginThrottle) InboxProved

func (t *LoginThrottle) InboxProved(w http.ResponseWriter, r *http.Request, email string) error

InboxProved records a completed password reset or an accepted invite. Each proves the inbox, so it marks the browser and clears this address's count for the email, like a sign-in. It leaves the email's count running: the marked browser is no longer held by it, and clearing it would end other people's wait early (see SignedIn).

func (*LoginThrottle) Reserve

func (t *LoginThrottle) Reserve(r *http.Request, email string) (ThrottleVerdict, error)

Reserve counts one sign-in attempt for the typed email from this request, before the password is checked. When any of the attempt's subjects is in a wait, nothing is counted and the verdict is a refusal.

func (*LoginThrottle) SignedIn

SignedIn records a sign-in with the right password. v is the verdict Reserve gave the same request. The sign-in marks the browser, sets the hardcount_device cookie and clears this address's count for the email.

It clears the email's count only when the attempt was counted under it, that is, from a browser that never signed in to the email. A successful sign-in should reset the failures it was held by (NIST SP 800-63B-4 §3.2.2), and without that reset a person who signs in from private windows, or a script with no cookie jar, would pile up waits. Such a sign-in cannot end a running wait: during one, the attempt was refused. A known browser was never held by the email's count, so its sign-in leaves the count alone. Clearing it there would end other people's wait early, which shows a guesser that the email has an account and gives them a new allowance of guesses.

type PostgresStore

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

PostgresStore is the production persistence for user accounts. All queries run under TxBypass — there is no tenant context for users (a user *belongs to* tenants via user_tenants but the user row itself is global). Auth resolution happens before any tenant ctx is available.

func NewPostgresStore

func NewPostgresStore(db *postgres.DB) *PostgresStore

func (*PostgresStore) AttachTenant

func (s *PostgresStore) AttachTenant(ctx context.Context, userID, tenantID, role string) error

func (*PostgresStore) ConsumeResetToken

func (s *PostgresStore) ConsumeResetToken(ctx context.Context, tokenHash string) (string, error)

func (*PostgresStore) Create

func (s *PostgresStore) Create(ctx context.Context, email, passwordHash string) (domain.User, error)

func (*PostgresStore) CreateInTx

func (s *PostgresStore) CreateInTx(ctx context.Context, tx *sql.Tx, email, passwordHash, tenantID, role string) (domain.User, error)

CreateInTx inserts a user and their tenant attachment inside the CALLER's transaction — the seam tenant.RunBootstrap needs so the owner user commits (or rolls back) atomically with the tenant, keys, and settings it belongs to (ADR-073). passwordHash must already be a bcrypt hash (user.HashPassword validates + hashes). No commit here; the caller owns the tx.

func (*PostgresStore) CreateResetToken

func (s *PostgresStore) CreateResetToken(ctx context.Context, userID, tokenHash string, expiresAt time.Time) (domain.PasswordResetToken, error)

func (*PostgresStore) GetByEmail

func (s *PostgresStore) GetByEmail(ctx context.Context, email string) (domain.User, error)

func (*PostgresStore) GetByID

func (s *PostgresStore) GetByID(ctx context.Context, id string) (domain.User, error)

func (*PostgresStore) LookupResetToken

func (s *PostgresStore) LookupResetToken(ctx context.Context, tokenHash string) (string, error)

LookupResetToken is the read-only counterpart — same validity gate (un-used, un-expired) but no UPDATE. Used by the reset-password page on mount to decide between rendering the form vs. an "this link is no longer valid" message.

func (*PostgresStore) SetPassword

func (s *PostgresStore) SetPassword(ctx context.Context, id, passwordHash string) error

func (*PostgresStore) TenantsForUser

func (s *PostgresStore) TenantsForUser(ctx context.Context, userID string) ([]domain.UserTenant, error)

func (*PostgresStore) TouchLastLogin

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

type RequestResetReq

type RequestResetReq struct {
	Email string `json:"email"`
}

type Service

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

Service is the auth-side surface for user accounts. ADR-011.

The recipe is intentionally boring: bcrypt cost 12 for hashing, crypto/rand for tokens, sha256 for token storage. The sign-in throttle (throttle.go, ADR-094) runs in the handler before Authenticate. All of this is well-trodden Go stdlib + x/crypto territory.

func NewService

func NewService(store Store, clk clock.Clock) *Service

func (*Service) Authenticate

func (s *Service) Authenticate(ctx context.Context, email, plaintext string) (domain.User, []domain.UserTenant, error)

Authenticate verifies email + password and returns the user + their tenant memberships. Returns ErrBadCredentials for a missing user OR a wrong password — the same error, with identical timing on both paths (the not-found path runs a dummy bcrypt), so response timing can't be used to enumerate registered emails. On success: stamps last_login_at.

There is no account-lock check, and there never is: the sign-in throttle (throttle.go) slows guesses before this runs and does not lock an account (ADR-094). An account under active attack is handled by password reset / session revocation, not by refusing login.

func (*Service) CheckResetToken

func (s *Service) CheckResetToken(ctx context.Context, plaintext string) error

CheckResetToken is the non-consuming counterpart of ConsumeResetToken. The reset-password page calls it on mount and renders the form only when nil is returned; otherwise it shows "this link is no longer valid". Stops the operator from filling in the form and only learning at submit-time that the token was already used (e.g. they reset earlier and clicked the email link from history).

func (*Service) ConsumeResetToken

func (s *Service) ConsumeResetToken(ctx context.Context, plaintext, newPassword string) (domain.User, error)

ConsumeResetToken validates the token, sets the new password, and returns the user it belonged to. Single-use: the token is stamped used_at atomically inside ConsumeResetToken, so a concurrent second redeem fails.

func (*Service) CreateUser

func (s *Service) CreateUser(ctx context.Context, email, plaintext, tenantID, role string) (domain.User, error)

CreateUser inserts a new user with hashed password and binds them to the given tenant with the supplied role. Used by the bootstrap CLI; not exposed via the HTTP API in v1 (no public signup).

func (*Service) GetByID

func (s *Service) GetByID(ctx context.Context, id string) (domain.User, error)

GetByID looks up a user by id. Used by /v1/whoami to project email onto the cookie-path response without forcing the session row to duplicate it.

func (*Service) IssueResetToken

func (s *Service) IssueResetToken(ctx context.Context, email string) (plaintext, tenantID, userID string, err error)

IssueResetToken generates a fresh reset token for the user with the given email, persists the hash, and returns the plaintext (caller emails it to the user via the reset link) along with the user's tenant_id (caller threads it into the email-outbox row so the password-reset email lands on the right tenant for operator visibility). Returns ("", "", nil) if the email doesn't match — the caller should always render the same "if your email is on file, you'll get a link" response so we don't leak account existence. IssueResetToken also returns the matched user's ID so the caller can record an audit row that POINTS AT the account instead of STORING its email. audit_log is append-only (0150 revoked DELETE), so an address written into a row is an erasure dead end; a user id is not.

func (*Service) TenantForUser

func (s *Service) TenantForUser(ctx context.Context, userID string) (string, error)

TenantForUser returns the user's (single, v1) tenant id. The auth handler needs it to scope a password-reset-completed audit row, where it holds only the domain.User (which carries no tenant). Returns "" + nil when the user has no tenant membership — the caller treats that as "nothing to audit," not an error worth failing the reset over.

type SessionService

type SessionService interface {
	Issue(ctx context.Context, in session.IssueInput) (string, session.Session, error)
	Resolve(ctx context.Context, rawID string) (session.Session, error)
	Revoke(ctx context.Context, rawID string) error
	RevokeAllForUser(ctx context.Context, userID string) error
	SetLivemode(ctx context.Context, rawID string, livemode bool) error
}

SessionService is the narrow seam the handler needs from *session.Service.

It exists so the FAILURE paths can be tested. logout used to write its audit row BEFORE revoking, log a revoke error to stderr, and return 204 regardless — a permanent append-only row asserting a logout that never happened, and a live session behind a browser told it was signed out. That survived an end-to-end audit because nothing could inject a failing Revoke: the dependency was a concrete *session.Service. A guarantee you cannot write a failing test for is a guarantee you do not have.

type SetModeReq

type SetModeReq struct {
	Livemode bool `json:"livemode"`
}

type Store

type Store interface {
	// Create inserts a user. Returns ErrEmailTaken if the email is
	// already in the table (citext unique violation).
	Create(ctx context.Context, email, passwordHash string) (domain.User, error)

	// GetByEmail loads the user with the given email (case-insensitive
	// via citext). Returns errs.ErrNotFound when no row matches.
	GetByEmail(ctx context.Context, email string) (domain.User, error)

	// GetByID loads the user by id.
	GetByID(ctx context.Context, id string) (domain.User, error)

	// TouchLastLogin updates last_login_at on successful login.
	TouchLastLogin(ctx context.Context, id string, at time.Time) error

	// SetPassword updates the password_hash. Used by the reset flow.
	SetPassword(ctx context.Context, id, passwordHash string) error

	// AttachTenant adds (user_id, tenant_id, role) to user_tenants.
	// Idempotent on (user_id, tenant_id) primary key conflict.
	AttachTenant(ctx context.Context, userID, tenantID, role string) error

	// TenantsForUser returns the tenant memberships for a user. v1 has
	// 1:1 user:tenant; the shape supports growth.
	TenantsForUser(ctx context.Context, userID string) ([]domain.UserTenant, error)

	// CreateResetToken enforces the per-account send cap and inserts a row
	// whose token_hash matches the
	// caller-provided hash. Plaintext token never enters the DB.
	CreateResetToken(ctx context.Context, userID, tokenHash string, expiresAt time.Time) (domain.PasswordResetToken, error)

	// ConsumeResetToken atomically looks up the token by hash, asserts
	// it isn't used or expired, and stamps used_at. Returns the token's
	// owning user_id.
	ConsumeResetToken(ctx context.Context, tokenHash string) (string, error)

	// LookupResetToken is the non-consuming counterpart of
	// ConsumeResetToken — returns the owning user_id if the token is
	// currently valid (not used, not expired) without flipping
	// used_at. Backs the page-mount validity check on the reset-
	// password screen so the operator who clicks an already-used
	// email link gets "this link is no longer valid" instead of a
	// form that rejects them at submit time.
	LookupResetToken(ctx context.Context, tokenHash string) (string, error)
}

type ThrottleVerdict

type ThrottleVerdict struct {
	Allowed    bool
	RetryAfter time.Duration // when refused: until the longest wait ends
	// Account is the first 12 hex characters of the email's subject. Logs
	// use it to group attempts on one email from any address without
	// writing the email down.
	Account string
	// contains filtered or unexported fields
}

ThrottleVerdict says whether one sign-in attempt may go on to the password check.

Directories

Path Synopsis
Package breachedpw holds the breached-password list that user.ValidatePassword checks when a password is set or reset (ADR-095, "Offline breached-password").
Package breachedpw holds the breached-password list that user.ValidatePassword checks when a password is set or reset (ADR-095, "Offline breached-password").
gen command
Command gen rebuilds internal/user/breachedpw/passwords.txt from a downloaded copy of the source list.
Command gen rebuilds internal/user/breachedpw/passwords.txt from a downloaded copy of the source list.

Jump to

Keyboard shortcuts

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