password

package
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 33 Imported by: 1 module, 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 password registers, logs in and recovers users by password. It works with any user store: the application hands it three functions of identifiers and subjects (Users) and a hash.Hasher, and the package owns only the password hashes. Reset links are signed values, not rows.

What it owns

A Verifier stores one hash per user (the hasher's output, base64 encoded). It offers the Go operations (Verifier.Authenticate, Verifier.Set, Verifier.Reset), the auth.Credential that lets a user re-prove themselves with their password (Verifier.Credential), and the JSON handlers behind /register, /login, PUT /password, /password/forgot and /password/reset. Registration is off until Builder.Registration enables it, and forgot and reset are off until Builder.Reset configures them; the other handlers need no switch.

Rules

  • Login answers one ErrInvalidCredentials (422) for an unknown user, a wrong password, a user without a password and a disabled user, and runs a dummy hash for the unknown ones so response times match.
  • Verifier.LoginHandler reserves an attempt before hashing and refunds it on success, so only failures count: 10 per identifier and client address together, 50 per identifier across addresses and 100 per client address in 15 minutes. Past a limit it answers ErrThrottled (429) with Retry-After. Verifier.Authenticate itself does not throttle: it is for code that has its own limits. While the user is in a second-factor lockout (auth.Guard.LockedOut) a correct password is not refunded either, so starting pending logins that cannot finish keeps costing throttle budget. Register and forgot are counted too, per identifier as typed and per client address, before any lookup.
  • A password change keeps the caller's session, ends the user's other logins and runs Builder.AfterChange. A reset calls Users.ProveEmail and Users.Rotate, which ends every session, pending login and API token of the user, and never logs the user in.
  • Registration and password changes are credential changes: the handlers require a browser session where they act on a logged-in user and call auth.Guard.Fresh themselves.
  • A reset link is a value signed by a core link.Signer (Builder.Reset) for the path "/password/reset" and the subject, bound to the user's current stored password hash (link.Bind) and expiring after Builder.ResetTTL. Changing the password by any means invalidates every link sent before, so no token is stored. Verifier.Reset checks the password policy first (a weak password does not use up the link), verifies the signature against the current hash, then stores the new hash with a conditional write in one transaction: an update matching only the hash the link was signed for, or, for a user without a password, an insert that does nothing on conflict. Zero affected rows means the link was already used, so of two concurrent submits exactly one wins, and ownership proof and rotation run only for that one. Every invalid, forged, expired or used link is ErrInvalidToken.
  • The forgot handler stores a reset job on the Builder.Queue dispatcher with a ResetRequest holding the identifier as typed, whether or not the user exists, and answers an empty 202; nothing is looked up in the request. The worker, which registers the job with Verifier.RegisterJobs, runs Verifier.SendReset: it looks the user up and sends the reset email through the mailer of Builder.Reset, to the address Users.Lookup returned, never to the text of the request. The send may run more than once for one request, because its error makes the queue retry. The email is a short plain-text message; ResetBuilder.Email replaces it. The job runs on the queue "iam", named "iam-password-reset" plus "-<instance>" for a named Builder.Instance.

Storage

The package never runs DDL. Verifier.Migrations describes the table "password_hashes" (prefixed "<instance>_" for a named Builder.Instance) in the group "arkoren.dev:ark/access:password", and the application's migrator executes them. Every package of the module assumes the same database.Database; writes that span packages join the transaction carried by the context.

Example:

clientIP := ratelimit.TrustedProxyKey(netip.MustParsePrefix("10.0.0.0/8"))
verifier, err := password.NewVerifier(provider, db, store, clientIP, hasher, password.Users{
	Lookup: directory.Lookup,
	Create: directory.Create,
	Rotate: directory.Rotate,
}, func(passwords *password.Builder) {
	passwords.Queue(dispatcher).Registration(true).Reset(signer, mailer, "https://app.example.com/reset-password")
})
if err != nil {
	return err
}
guard, err := auth.NewGuard(provider, store, func(policy *auth.GuardBuilder) {
	policy.StepUp(verifier.Credential())
})
web.Post("/register", verifier.RegisterHandler(), password.RegisterOperation)
web.Post("/login", verifier.LoginHandler(guard), password.LoginOperation)

Index

Examples

Constants

View Source
const (
	// DefaultResetTTL is how long a password reset link stays valid when
	// [Builder.ResetTTL] is not set.
	//
	// Example:
	//
	//	passwords.ResetTTL(password.DefaultResetTTL / 2)
	DefaultResetTTL = time.Hour

	// MinLength is the shortest password the default policy accepts, in bytes.
	//
	// Example:
	//
	//	fmt.Println(password.MinLength) // 8
	MinLength = 8

	// MaxLength is the longest password the default policy accepts, in bytes.
	// bcrypt hashers reject more than 72 bytes, so the default never admits a
	// password the common hashers cannot take.
	//
	// Example:
	//
	//	fmt.Println(password.MaxLength) // 72
	MaxLength = 72
)

Variables

View Source
var Changed = event.NewTopic[UserEvent]("password.credential.changed")

Changed is published after a logged-in user set or changed their password. It is the hook for a "your password changed" notification.

Example:

unsubscribe, err := events.Listen(password.Changed, func(ctx context.Context, changed password.UserEvent) error {
	return nil
})
View Source
var ErrIdentifierTaken = errors.New("password: identifier taken")

ErrIdentifierTaken is what Users.Create returns, or wraps, when the identifier already belongs to a user. Verifier.RegisterHandler answers the same 202 as for a new user and notifies the owner instead of revealing it, so the error never reaches the client. It is a plain error, not a problem: with the built-in directory the facade maps its own [account.ErrEmailTaken] to it.

Example:

create := func(ctx context.Context, identifier string) (string, error) {
	if exists(identifier) {
		return "", password.ErrIdentifierTaken
	}
	return insert(ctx, identifier)
}
View Source
var ErrInvalidConfig = errors.New("password: invalid configuration")

ErrInvalidConfig is wrapped by the errors of NewVerifier for an unusable configuration.

Example:

_, err := password.NewVerifier(nil, nil, nil, nil, nil, password.Users{})
fmt.Println(errors.Is(err, password.ErrInvalidConfig)) // true
View Source
var ErrInvalidCredentials = problem.New(func(details *problem.Builder) {
	details.Type("tag:arkoren.dev,2026-11:ark/access:password:invalid-credentials")
	details.Title("Invalid credentials")
	details.Detail("The identifier or password is incorrect.")
	details.Status(http.StatusUnprocessableEntity)
})

ErrInvalidCredentials is the one answer to a failed login or password check: unknown user, wrong password, user without a password or disabled user. It is a problem with status 422.

Example:

_, err := verifier.Authenticate(ctx, "ada@example.com", "wrong")
if errors.Is(err, password.ErrInvalidCredentials) {
	// show "wrong email or password"
}
View Source
var ErrInvalidPassword = problem.New(func(details *problem.Builder) {
	details.Type("tag:arkoren.dev,2026-11:ark/access:password:invalid-password")
	details.Title("Invalid password")
	details.Detail("The password does not meet the requirements.")
	details.Status(http.StatusUnprocessableEntity)
})

ErrInvalidPassword is returned when a new password fails the policy (by default 8 to 72 bytes; see Builder.Policy). It is a problem with status 422.

Example:

err := verifier.Set(ctx, subject, "short")
fmt.Println(errors.Is(err, password.ErrInvalidPassword)) // true
View Source
var ErrInvalidToken = problem.New(func(details *problem.Builder) {
	details.Type("tag:arkoren.dev,2026-11:ark/access:password:invalid-token")
	details.Title("Invalid token")
	details.Detail("The token is invalid or has expired.")
	details.Status(http.StatusUnprocessableEntity)
})

ErrInvalidToken is returned for a reset link that is malformed, forged, expired or already used (the password it was bound to has changed). One answer covers all of them, so a client learns nothing about which. It is a problem with status 422.

Example:

_, err := verifier.Reset(ctx, signed, "a new password")
if errors.Is(err, password.ErrInvalidToken) {
	// ask the user to request a new link
}
View Source
var ErrNotMigrated = storage.ErrNotMigrated

ErrNotMigrated is returned by Verifier.Ping when the tables do not exist. Add Verifier.Migrations to the application's migrator and run them.

Example:

if errors.Is(verifier.Ping(ctx), password.ErrNotMigrated) {
	// run the migrator
}
View Source
var ErrThrottled = problem.New(func(details *problem.Builder) {
	details.Type("tag:arkoren.dev,2026-11:ark/access:password:throttled")
	details.Title("Too many attempts")
	details.Detail("Too many failed attempts. Try again later.")
	details.Status(http.StatusTooManyRequests)
})

ErrThrottled is returned by the login and change handlers when too many attempts were made. The response carries Retry-After in seconds. It is a problem with status 429.

Example:

if errors.Is(err, password.ErrThrottled) {
	// wait for Retry-After
}
View Source
var WasReset = event.NewTopic[UserEvent]("password.credential.reset")

WasReset is published after a reset link replaced a user's password.

Example:

unsubscribe, err := events.Listen(password.WasReset, func(ctx context.Context, reset password.UserEvent) error {
	return nil
})

Functions

func ChangeOperation added in v0.6.0

func ChangeOperation(operation *router.OperationBuilder)

ChangeOperation describes Verifier.ChangeHandler. It needs a browser session and a fresh login, answers 204 and re-issues the session cookie because the other logins of the user end. A wrong current password is 422 ErrInvalidCredentials, a password that fails the policy 422 ErrInvalidPassword and too many attempts 429 ErrThrottled.

Example:

web.Put("/password", verifier.ChangeHandler(guard), password.ChangeOperation)

func ForgotOperation added in v0.6.0

func ForgotOperation(operation *router.OperationBuilder)

ForgotOperation describes Verifier.ForgotHandler. It answers an empty 202 whether or not the user exists, because the work is stored for a worker, and throttles requests per identifier as typed and per client address (429 with Retry-After).

Example:

web.Post("/password/forgot", verifier.ForgotHandler(), password.ForgotOperation)

func LoginOperation added in v0.6.0

func LoginOperation(operation *router.OperationBuilder)

LoginOperation describes Verifier.LoginHandler. The body takes email (or identifier) and password, and a failure is the same 422 ErrInvalidCredentials for every cause. A complete login is 204; a user with a second factor is parked and answered 202 with the methods to use at the challenge route. Both set the session cookie. Failed attempts are throttled (429 with Retry-After). The annotation changes no handler behavior.

Example:

web.Post("/login", verifier.LoginHandler(guard), password.LoginOperation)

func RegisterOperation added in v0.6.0

func RegisterOperation(operation *router.OperationBuilder)

RegisterOperation describes Verifier.RegisterHandler. It always answers 202 with no body and never logs the user in, so the answer does not say whether the identifier was free. Registrations are throttled (429 with Retry-After), and a password that fails the policy is 422 ErrInvalidPassword.

Example:

web.Post("/register", verifier.RegisterHandler(), password.RegisterOperation)

func ResetOperation added in v0.6.0

func ResetOperation(operation *router.OperationBuilder)

ResetOperation describes Verifier.ResetHandler. It answers 204, never logs the user in, and ends all the user's logins. An invalid, expired or used link is 422 ErrInvalidToken and a password that fails the policy 422 ErrInvalidPassword.

Example:

web.Post("/password/reset", verifier.ResetHandler(guard), password.ResetOperation)

Types

type Builder

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

Builder configures NewVerifier before publication. Callbacks run directly once, in order, on one fresh draft; methods return the same draft.

Example:

verifier, err := password.NewVerifier(provider, db, store, clientIP, hasher, users, func(passwords *password.Builder) {
	passwords.Queue(dispatcher).Reset(signer, mailer, "https://app.example.com/reset-password").ResetTTL(30 * time.Minute)
})

func (*Builder) AfterChange

func (passwords *Builder) AfterChange(hook func(ctx context.Context, subject string) error) *Builder

AfterChange adds a function that runs in Verifier.ChangeHandler after the new password is stored and before the caller's other logins end, for what must not survive a password change, such as the user's device tokens. An error fails the request; the password has changed by then, so the client may retry. Hooks add up instead of replacing each other, so the token revocation the facade registers survives an application hook: they run in the order added, all of them even when one fails, and their errors are joined.

Example:

passwords.AfterChange(issuer.RevokeDevices)

func (*Builder) Events

func (passwords *Builder) Events(bus *event.Bus) *Builder

Events publishes Changed and WasReset on bus. A nil bus publishes nothing.

Example:

passwords.Events(events)

func (*Builder) Instance

func (passwords *Builder) Instance(name string) *Builder

Instance selects a named instance: tables are prefixed "<instance>_" and the migration group gains ":<instance>". The name is 1 to 20 bytes of [a-z0-9_] starting with a letter; the default is the empty instance.

Example:

passwords.Instance("tenant_a")

func (*Builder) Policy

func (passwords *Builder) Policy(check func(ctx context.Context, password string) error) *Builder

Policy replaces the password policy, which by default requires MinLength to MaxLength bytes. check returns an error wrapping ErrInvalidPassword to reject a password; any other error is an infrastructure failure.

Example:

passwords.Policy(func(ctx context.Context, password string) error {
	if len(password) < 12 {
		return fmt.Errorf("too short: %w", passwordpkg.ErrInvalidPassword)
	}
	return nil
})

func (*Builder) Queue added in v0.5.0

func (passwords *Builder) Queue(dispatcher *queue.Dispatcher) *Builder

Queue sets the dispatcher that stores the module's background work. Reset needs it: the forgot-password route stores one job per request on it and returns, and the worker that runs Verifier.RegisterJobs sends the email. Through the facade, iam.Builder.Queue sets it for every package, so only code that builds a Verifier by itself calls it. The jobs run on the queue "iam"; see Verifier.RegisterJobs. A later call replaces the earlier one.

Example:

passwords.Queue(dispatcher)

func (*Builder) Registered

func (passwords *Builder) Registered(hook func(ctx context.Context, subject, identifier string) error) *Builder

Registered adds a function that runs after Verifier.RegisterHandler committed a new user, for work that must follow a registration such as sending an email verification. The handler never logs the user in; it answers 202 and the user logs in afterwards. An error is logged and does not fail the request: the user is registered either way, and a mail outage must not turn into a failed signup. Hooks add up instead of replacing each other, so the verification the facade requests survives an application hook: they run in the order added, all of them, and their errors are logged together.

Example:

passwords.Registered(func(ctx context.Context, subject, identifier string) error {
	return directory.RequestVerification(ctx, subject)
})

func (*Builder) Registration

func (passwords *Builder) Registration(enabled bool) *Builder

Registration enables self-service registration: Verifier.RegisterHandler creates users with Users.Create and the facade mounts POST /register. The default is false, because most applications add users themselves (an invite, an admin, a social sign-up) and an open registration route is an abuse surface they never asked for. With false the handler panics at composition. NewVerifier ignores it, with one warning, when it is true and Users.Create is nil: nothing could create the user. Through the facade with the built-in users, registration also needs Builder.Reset: iam.New ignores it, with a warning, without it, because the reset notice is how the owner of an address that someone else registered first learns of it and recovers the account.

Example:

passwords.Registration(true).Reset(signer, mailer, "https://app.example.com/reset-password")

func (*Builder) Reset

func (passwords *Builder) Reset(signer *link.Signer, mailer *mail.Mailer, resetURL string, configure ...ResetBuilderFunc) *Builder

Reset turns forgotten-password recovery on: calling it makes Verifier.ForgotHandler and Verifier.ResetHandler work, and Verifier.SendReset and Verifier.RegisterJobs exist for the worker. Recovery is off when the method is never called; to switch it from configuration, wrap the call in an if. A later call replaces the earlier one. The package keeps no reset table and runs no goroutine; a reset link is a value that signer signs and that stops working by itself:

  • It is bound to the user's current stored password hash (link.Bind), so the first successful reset or password change invalidates every link sent before, and it expires after Builder.ResetTTL.
  • The forgot-password route stores one job on the Builder.Queue dispatcher per request (and the notice to the owner of a taken identifier, with ResetRequest.Notice set, see Builder.Taken) and returns, or returns an error, which answers 500 so the client retries. The job carries the identifier exactly as typed and is stored whether or not the user exists, so the response and its timing reveal nothing.
  • The stored job later reaches Verifier.SendReset in a worker, which looks the user up, signs the link and sends the email through mailer. Its error is returned so the queue retries, which means one request may send more than once.

resetURL is the page of the application that the link opens, for example "https://app.example.com/reset-password". The signed value travels in the URL fragment (ResetMessage.Link), so the page reads it from location.hash and posts it to POST /password/reset. It must be an absolute URL without a fragment. The email is a plain-text message with a default subject and wording; configure may replace it with ResetBuilder.Email. The callbacks run directly once, in order, on one fresh ResetBuilder.

Signer, mailer, resetURL and a Builder.Queue dispatcher are all required: NewVerifier fails with ErrInvalidConfig when any is missing or invalid. Use a signer whose key is reserved for links, and share it only with code that signs distinct paths; a reset link is authenticated for its path, so links of other features never work here.

Example:

passwords.Queue(dispatcher).Reset(signer, mailer, "https://app.example.com/reset-password", func(reset *password.ResetBuilder) {
	reset.Email(resetEmail)
})

func (*Builder) ResetTTL

func (passwords *Builder) ResetTTL(ttl time.Duration) *Builder

ResetTTL sets how long a reset link is valid; zero selects DefaultResetTTL.

Example:

passwords.ResetTTL(30 * time.Minute)

func (*Builder) Taken

func (passwords *Builder) Taken(hook func(ctx context.Context, identifier string) error) *Builder

Taken adds a function that runs when Verifier.RegisterHandler meets an identifier that already belongs to a user, with the identifier as typed. It is where the owner is told that someone tried to register: dispatch the same kind of work as Builder.Registered does for a new user, so the two paths cost the same and the answer, 202 for both, reveals nothing. Verifier.RequestReset with ResetRequest.Notice set is the reset notice. An error is logged and does not change the answer. Hooks add up instead of replacing each other: they run in the order added, all of them, and their errors are logged together.

Example:

passwords.Taken(func(ctx context.Context, identifier string) error {
	return verifier.RequestReset(ctx, password.ResetRequest{Identifier: identifier, Notice: true})
})

type BuilderFunc

type BuilderFunc = func(*Builder)

BuilderFunc is the callback form of Builder.

Example:

var configure password.BuilderFunc = func(passwords *password.Builder) {
	passwords.Instance("tenant_a")
}
verifier, err := password.NewVerifier(provider, db, store, clientIP, hasher, users, configure)

type ResetBuilder added in v0.5.0

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

ResetBuilder configures the email of Builder.Reset. Callbacks run directly once, in order, on one fresh draft; methods return the same draft.

Example:

passwords.Reset(signer, mailer, resetURL, func(reset *password.ResetBuilder) {
	reset.Email(resetEmail)
})

func (*ResetBuilder) Email added in v0.5.0

func (reset *ResetBuilder) Email(compose ResetEmailFunc) *ResetBuilder

Email replaces the default reset email, a short plain-text message that says who asked, shows the link and when it expires. compose runs in the worker for every send, once per attempt, and must not keep the message: its Signed value is a credential. A nil compose restores the default. Notice emails (see ResetMessage.Notice) go through the same function, so a custom email must handle both wordings.

Example:

reset.Email(func(message password.ResetMessage, href string) mail.Message {
	return mail.NewMessage(mail.Recipients{To: []mail.Address{{Email: message.Address}}}, mail.Body{Text: href})
})

type ResetBuilderFunc added in v0.5.0

type ResetBuilderFunc = func(*ResetBuilder)

ResetBuilderFunc is the callback form of ResetBuilder.

Example:

var configure password.ResetBuilderFunc = func(reset *password.ResetBuilder) {
	reset.Email(resetEmail)
}
passwords.Reset(signer, mailer, resetURL, configure)

type ResetEmailFunc added in v0.5.0

type ResetEmailFunc = func(message ResetMessage, href string) mail.Message

ResetEmailFunc writes the email of a password reset: message describes the request and href is the page link to put in the body, the application's reset URL with the signed value in its fragment. The result needs the recipient message.Address and a body; the sender comes from the mailer's defaults unless the message sets it. A message that fails validation is a permanent failure of the job, because retrying cannot fix it.

Example:

var resetEmail password.ResetEmailFunc = func(message password.ResetMessage, href string) mail.Message {
	return mail.NewMessage(mail.Recipients{To: []mail.Address{{Email: message.Address}}}, mail.Body{Text: href}, func(letter *mail.MessageBuilder) {
		letter.Subject("Reset your password")
	})
}

type ResetMessage

type ResetMessage struct {
	// Address is where to send the email: the address [Users.Lookup] returned
	// for the user, never the text of the request, so a request cannot send a
	// victim's link elsewhere.
	Address string

	// Signed is the signed link value that [Verifier.Reset] accepts. It is a URL
	// (relative, or absolute under the signer's origin) that the front end posts
	// back verbatim; it is not a page address.
	Signed string

	// ExpiresAt is when the link stops working.
	ExpiresAt time.Time

	// Notice is true for the notice to the owner of an identifier that someone
	// tried to register ([ResetRequest.Notice]): the email should say so, and
	// that the link sets a new password if it was not them. It is false for a
	// request of the owner.
	Notice bool
}

ResetMessage describes one reset email to the function of ResetBuilder.Email. Signed is a credential until it expires or the password changes; never log it.

Example:

href := message.Link("https://app.example.com/reset-password")
func (message ResetMessage) Link(base string) string

Link returns base with the signed value in the URL fragment, escaped, as base#<value>. A fragment is never sent to the server, so the link stays out of access logs, proxies and the Referer header of the page it opens. The page reads location.hash, decodes it with decodeURIComponent after removing the leading "#", removes it from the address bar and posts it as the "token" of POST /password/reset. base must not already carry a fragment.

Example:

message := password.ResetMessage{Signed: "/password/reset?subject=u1"}
fmt.Println(message.Link("https://app.example.com/reset")) // https://app.example.com/reset#%2Fpassword%2Freset%3Fsubject%3Du1

type ResetRequest

type ResetRequest struct {
	// Identifier is exactly what the user typed, never looked up before the
	// request was dispatched: the response of the forgot-password route must
	// not depend on whether the user exists. [Verifier.SendReset] resolves it.
	Identifier string `json:"identifier"`

	// Notice marks the notice to the owner of an identifier that someone tried to
	// register ([Builder.Taken]): the same link, with an email that says so.
	Notice bool `json:"notice,omitzero"`
}

ResetRequest is the payload of the reset job that every forgot-password request stores on the Builder.Queue dispatcher, and what Verifier.SendReset takes: the work of sending one reset email. It is plain data with JSON tags, so a queue job or a workflow input can carry it as is.

Stored requests must stay decodable across upgrades: new fields are only ever added, never renamed, repurposed or removed, and a missing field keeps its zero value. Decode old payloads with the same type.

Example:

request := password.ResetRequest{Identifier: "ada@example.com"}
err := verifier.SendReset(ctx, request)

type UserEvent

type UserEvent struct {
	// Subject is the user the event is about.
	Subject string
}

UserEvent is the payload of the events of this package. It carries only the subject, never a password, hash or token.

Example:

events.Listen(password.Changed, func(ctx context.Context, changed password.UserEvent) error {
	return notify(ctx, changed.Subject, "your password changed")
})

type Users

type Users struct {
	// Lookup returns the subject of the user with identifier and the address
	// to write to, as stored with the user (with the directory, the stored
	// email, which can differ from what was typed). An unknown user must
	// return an error wrapping [auth.ErrUserNotFound]; any other error is an
	// infrastructure failure. It must not reveal more than that. The address
	// must not be empty: a reset email is sent only to it, never to the typed
	// identifier, so a request cannot redirect a victim's link.
	Lookup func(ctx context.Context, identifier string) (subject, address string, err error)

	// Create adds a user with identifier and returns the subject. It is used by
	// registration and may be nil for an application that registers users
	// elsewhere; [Builder.Registration] without it is ignored with a warning,
	// because nothing could create the user. Its errors
	// (a taken identifier, an invalid one) pass through to the client. It must
	// fail on an existing identifier and never return the existing user.
	Create func(ctx context.Context, identifier string) (subject string, err error)

	// Rotate bumps the user's [auth.UserRecord.Version], which ends every
	// session, pending login and API token of the user. A reset calls it.
	Rotate func(ctx context.Context, subject string) error

	// ProveEmail is optional. [Verifier.Reset] calls it in its transaction,
	// after the new password is stored, because a completed reset proves the
	// user controls the mailbox the link went to. An implementation marks the
	// address verified and, when it was not verified before, removes what
	// someone who registered the address first could have attached
	// (connections, two-factor, tokens). An error rolls the reset back.
	ProveEmail func(ctx context.Context, subject string) error
}

Users connects the verifier to the application's user store. The functions speak identifiers (what the user types at login, such as an email) and subjects (what the rest of the system uses). The facade fills them from the built-in directory or from the application's own users; the package never imports either.

Example:

users := password.Users{
	Lookup: directory.Lookup,
	Create: directory.Create,
	Rotate: directory.Rotate,
}

type Verifier

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

Verifier owns the password hashes. Reset links are signed values, not rows (Builder.Reset). It is safe for concurrent use. Create it with NewVerifier.

Example:

verifier, err := password.NewVerifier(provider, db, store, clientIP, hasher, users)
if err != nil {
	return err
}

func NewVerifier

func NewVerifier(provider *auth.UserProvider, db *database.Database, store *cache.Cache, clientIP func(*http.Request) string, hasher *hash.Hasher, users Users, configure ...BuilderFunc) (*Verifier, error)

NewVerifier returns a verifier. provider finds users (to refuse disabled ones and to read the version), db holds the tables, store counts login attempts, clientIP finds the client address those counters are keyed on, hasher hashes passwords and users connects the user store. clientIP is required because the right source depends on the deployment: behind a reverse proxy r.RemoteAddr is the proxy, so every user would share one counter. Pass ratelimit.TrustedProxyKey with your proxies' prefixes, or with none when no proxy sits in front of the application. It does no I/O: the tables come from Verifier.Migrations. Errors wrap ErrInvalidConfig.

It registers a forget hook on provider that deletes the user's hash in the caller's transaction.

Example:

clientIP := ratelimit.TrustedProxyKey(netip.MustParsePrefix("10.0.0.0/8"))
verifier, err := password.NewVerifier(provider, db, store, clientIP, hasher, password.Users{
	Lookup: directory.Lookup,
	Rotate: directory.Rotate,
})

func (*Verifier) Authenticate

func (verifier *Verifier) Authenticate(ctx context.Context, identifier, password string) (string, error)

Authenticate checks identifier and password and returns the subject. Every failure (unknown user, wrong password, no password, disabled user) is ErrInvalidCredentials, and unknown users cost one dummy hash. It does not log anyone in and does not throttle; Verifier.LoginHandler adds both. A failure of the user store or the database is returned as is.

Example:

subject, err := verifier.Authenticate(ctx, "ada@example.com", "correct horse")
if errors.Is(err, password.ErrInvalidCredentials) {
	// wrong email or password
}

func (*Verifier) ChangeHandler

func (verifier *Verifier) ChangeHandler(guard *auth.Guard) router.Handler

ChangeHandler returns the handler of PUT /password. The body is {"current_password": "...", "password": "..."}; "current_password" is required unless the user has no password yet (a user created by a social login sets their first one). It needs a browser session and a fresh login (auth.Guard.Fresh), checks the current password with the same throttle as login, stores the new one, ends the user's other logins and keeps the caller's session, which also records the password as a recent proof. Success is 204. It publishes Changed and runs Builder.AfterChange (the facade revokes the user's device tokens there, because a device keeps no session to end). It does not rotate the user, so tokens the hook leaves, such as personal access tokens, survive a change. Reset links sent before are bound to the old hash, so they stop working. If the hook fails the response is its error (500), but the password is already changed and the other logins already ended; the client should repeat the change so the hook runs again.

Example:

web.Put("/password", verifier.ChangeHandler(guard), password.ChangeOperation)

func (*Verifier) Check

func (verifier *Verifier) Check(ctx context.Context, subject, password string) error

Check verifies password against the stored hash of subject and returns ErrInvalidCredentials for a wrong password or a user without one, doing the same work for both. A successful check upgrades the stored hash when the hasher says it is outdated and it has not since changed or been removed. Rehashing is best effort and never overwrites a concurrent credential change.

Example:

if err := verifier.Check(ctx, subject, "current password"); err != nil {
	return err
}

func (*Verifier) Credential

func (verifier *Verifier) Credential() auth.Credential

Credential returns the auth.Credential that lets a user re-prove themselves with their password: method "pwd", kind knowledge. Register it with the guard's StepUp registry so the shared confirm route (POST /confirm with {"method": "pwd", "password": "..."}) accepts it. It is enrolled for users who have a password; a wrong password wraps auth.ErrInvalidCredential, which core counts as an attempt.

Example:

guard, err := auth.NewGuard(provider, store, func(policy *auth.GuardBuilder) {
	policy.StepUp(verifier.Credential())
})

func (*Verifier) ForgotHandler

func (verifier *Verifier) ForgotHandler() router.Handler

ForgotHandler returns the handler of POST /password/forgot. The body is {"email": "..."} (or "identifier"). It counts the request, then calls the reset job on the Builder.Queue dispatcher with a ResetRequest holding the identifier exactly as typed, whether or not the user exists, and answers an empty 202. Nothing is looked up in the request, so the answer and its time say nothing about which identifiers exist; the lookup, the signing and the email happen in the worker that runs Verifier.RegisterJobs, and the email goes to the address stored with the user, never to the text of the request.

Requests are counted before anything else: more than 5 per identifier as typed or 30 per client address in 15 minutes is ErrThrottled (429), which holds whatever the identifier is. A dispatch error is returned (500), because the work was not stored and the client should try again. It panics at composition without Builder.Reset.

Example:

web.Post("/password/forgot", verifier.ForgotHandler(), password.ForgotOperation)

func (*Verifier) Has

func (verifier *Verifier) Has(ctx context.Context, subject string) (bool, error)

Has reports whether subject has a password. It is the Enrolled function of Verifier.Credential and the fallback check that stops a user from removing their last way to log in.

Example:

has, err := verifier.Has(ctx, subject)

func (*Verifier) LoginHandler

func (verifier *Verifier) LoginHandler(guard *auth.Guard) router.Handler

LoginHandler returns the handler of POST /login. The body is {"email": "...", "password": "..."} (or "identifier" instead of "email"). It counts the attempt before hashing (ErrThrottled, 429, with Retry-After), authenticates, and hands the user to auth.Guard.Begin: 204 when logged in, or 202 with the second-factor methods when the user has to answer a challenge (POST /login/challenge). A failure is ErrInvalidCredentials (422), the same for every cause.

Only failed logins count. The limits in 15 minutes are 10 per identifier and client address together, so someone failing from elsewhere cannot lock the real user out; 50 per identifier across all addresses, a looser cap against a distributed guess; and 100 per client address. A successful login refunds its attempt on all three and clears the identifier-and-address counter. A user locked out of an account by a distributed guess waits for the window, or resets the password. A user in a second-factor lockout (auth.Guard.LockedOut) is not refunded: a correct password only parks a pending login that cannot finish, so it counts as a failure.

Example:

web.Post("/login", verifier.LoginHandler(guard), password.LoginOperation)

func (*Verifier) Migrations

func (verifier *Verifier) Migrations() []migrate.Definition

Migrations returns the migration that creates the "password_hashes" table (prefixed "<instance>_" for a named instance) in the group "arkoren.dev:ark/access:password", plus ":<instance>". It creates the table strictly and its down step drops it. The application adds them to its migrator; constructing or reading them never runs DDL.

Example:

if err := migrator.Add(verifier.Migrations()...); err != nil {
	return err
}

func (*Verifier) Ping

func (verifier *Verifier) Ping(ctx context.Context) error

Ping verifies, read-only, that the table exists. A missing table returns an error wrapping ErrNotMigrated. Use it as a readiness check.

Example:

if err := verifier.Ping(ctx); err != nil {
	return err
}

func (*Verifier) RegisterHandler

func (verifier *Verifier) RegisterHandler() router.Handler

RegisterHandler returns the handler of POST /register. The body is {"email": "...", "password": "..."} (or "identifier"). It counts the request first, per identifier as typed (5) and per client address (30) in 15 minutes (ErrThrottled, 429), checks the password policy (a weak password is ErrInvalidPassword, 422), then creates the user (Users.Create) and stores the password in one transaction and runs the Builder.Registered hook.

It always answers 202 with no body and never logs the user in, so the answer does not say whether the identifier was free: the user logs in afterwards (Verifier.LoginHandler). When Users.Create returns ErrIdentifierTaken it creates nothing, still hashes the password so the time taken matches, and runs the Builder.Taken hook, which is where the application tells the owner (the facade stores a reset notice or a verification job there). The hook runs at most as often as the throttle lets registrations through, so the route cannot be used to flood a mailbox. Any other error of Users.Create (an invalid identifier, say) passes through. The answer does not say whether the identifier was free, but a login with the password just registered does (it succeeds only for a new identifier), which the throttles above and the notice to the owner bound but do not remove. A failing Builder.Registered or Builder.Taken hook is logged and does not change the answer. A new user is unverified, and with the facade cannot connect a provider, enroll two-factor or create tokens until the email is verified. It panics at composition unless Builder.Registration is enabled (it is off by default, and NewVerifier already refuses it without Users.Create).

Example:

web.Post("/register", verifier.RegisterHandler(), password.RegisterOperation)

func (*Verifier) RegisterJobs added in v0.5.0

func (verifier *Verifier) RegisterJobs(consumer *queue.Consumer) error

RegisterJobs registers the handler of the reset job on consumer, which the worker process runs. It registers nothing, and returns nil, without Builder.Reset. The job is named "iam-password-reset", with "-<instance>" appended (underscores written as hyphens) for a named Builder.Instance, and runs on the queue "iam": a consumer restricted with queue.ConsumerBuilder.Queues must list it. It returns an error wrapping queue.ErrDuplicateName when the handler is already registered. Through the facade, call IAM.RegisterJobs instead, which registers the jobs of every enabled package.

Example:

if err := verifier.RegisterJobs(consumer); err != nil {
	return err
}

func (*Verifier) Registration

func (verifier *Verifier) Registration() bool

Registration reports whether self-service registration is enabled (Builder.Registration), which the facade reads to decide whether to mount POST /register.

Example:

if verifier.Registration() {
	web.Post("/register", verifier.RegisterHandler(), password.RegisterOperation)
}

func (*Verifier) Remove

func (verifier *Verifier) Remove(ctx context.Context, subject string) error

Remove deletes the password of subject, so the user can no longer log in with one and Verifier.Has reports false. It is idempotent and runs in the transaction carried by ctx, which makes it part of larger changes: the verifier registers it to forget a deleted user, and the facade calls it when the owner of a verified provider email takes over an account that was registered with a password and never verified. It does not end the user's logins; whoever calls it rotates the user (auth.UserRecord.Version) if they must end.

Example:

err := db.WithTransaction(ctx, func(ctx context.Context) error {
	return verifier.Remove(ctx, subject)
})

func (*Verifier) RequestReset

func (verifier *Verifier) RequestReset(ctx context.Context, request ResetRequest) error

RequestReset stores a reset job for request on the Builder.Queue dispatcher, in the caller's request, which is how the forgot-password route and a Builder.Taken hook ask for a reset email. The email is sent later by the worker that runs Verifier.RegisterJobs. It returns the dispatch error, which means the work was not stored, or one wrapping ErrInvalidConfig without Builder.Reset.

Example:

err := verifier.RequestReset(ctx, password.ResetRequest{Identifier: "ada@example.com", Notice: true})

func (*Verifier) Reset

func (verifier *Verifier) Reset(ctx context.Context, signed, password string) (string, error)

Reset checks a signed reset link and sets the password, calls Users.ProveEmail when set and then Users.Rotate, in one transaction, and returns the subject. The link only reached someone who controls the mailbox, so the reset is the proof of ownership an unverified registration lacks. Rotation ends every session, pending login and API token of the user; call auth.Guard.RevokeAll to remove their login records as well, as Verifier.ResetHandler does. Reset never logs the user in, so it cannot bypass a second factor.

The steps run in this order. A password that fails the policy is ErrInvalidPassword and is checked first, so a weak password does not use up the link. The signed value is parsed and its subject read, the user's current hash is loaded and the signature is verified against it. The password is then stored by a conditional write inside the transaction: an update that matches only the hash the link was signed for (or an insert that does nothing on conflict for a user without a password, such as one who signed up with a provider). Zero affected rows means a concurrent reset or password change won, so of two concurrent submits of one link exactly one succeeds. Ownership proof, rotation and the other effects run only when the row changed. Invalid, forged, expired, used and replaced links are all ErrInvalidToken.

Example:

subject, err := verifier.Reset(ctx, signed, "a new long password")
if errors.Is(err, password.ErrInvalidToken) {
	// ask for a new link
}

func (*Verifier) ResetEnabled

func (verifier *Verifier) ResetEnabled() bool

ResetEnabled reports whether Builder.Reset was configured, which the facade reads to decide whether to mount the forgot and reset routes.

Example:

if verifier.ResetEnabled() {
	web.Post("/password/forgot", verifier.ForgotHandler(), password.ForgotOperation)
}

func (*Verifier) ResetHandler

func (verifier *Verifier) ResetHandler(guard *auth.Guard) router.Handler

ResetHandler returns the handler of POST /password/reset. The body is {"token": "...", "password": "..."}, where the token is the signed value of ResetMessage.Signed. It runs Verifier.Reset, which rotates the user, then removes the user's login records with auth.Guard.RevokeAll. It never logs the user in: after a reset the user logs in again, with their second factor if they have one. Success is 204 and the publisher of WasReset has run. An invalid, expired or used link is ErrInvalidToken (422). It panics at composition without Builder.Reset.

Example:

web.Post("/password/reset", verifier.ResetHandler(guard), password.ResetOperation)

func (*Verifier) SendReset

func (verifier *Verifier) SendReset(ctx context.Context, request ResetRequest) error

SendReset is the worker side of a password reset: it looks request.Identifier up with Users.Lookup, signs a link bound to the user's current password hash and sends the reset email through the mailer of Builder.Reset to the address that Lookup returned, never the text of the identifier. An unknown or disabled user gets nothing and the call returns nil, so a retry never repeats pointless work. A mailer error is returned as is, so a queue retries; because of that, one request may send more than once, and the links of the attempts all work until the password changes or they expire. An email that fails validation (see ResetEmailFunc) is returned wrapped with queue.Permanent, because retrying cannot fix it. An error is also returned when Users.Lookup returns no address. It does not throttle: Verifier.ForgotHandler does, before dispatching. Without Builder.Reset it returns an error wrapping ErrInvalidConfig.

It has the shape func(context.Context, ResetRequest) error, so a workflow step can use it directly; a queue worker uses Verifier.RegisterJobs.

Example:

err := verifier.SendReset(ctx, password.ResetRequest{Identifier: "ada@example.com"})

func (*Verifier) Set

func (verifier *Verifier) Set(ctx context.Context, subject, password string) error

Set replaces the password of subject, creating it when there is none, after checking the policy (ErrInvalidPassword). It does not end any login: the handlers decide that, and Verifier.Reset rotates the user.

Example:

if err := verifier.Set(ctx, subject, "a new long password"); err != nil {
	return err
}

Jump to

Keyboard shortcuts

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