gas/auth
auth/token
import "github.com/gasmod/gas/auth/token"Package token issues single-use, time-limited tokens, for links such as a password reset, an email verification, a magic login link or an invite.
A token is a random string the app sends to a user. When the user presents it, the app verifies it once, for the purpose it was issued for, and learns whose it is. The database keeps the token’s hash, never the token.
Service is a gas.Service. It is not an auth.Authenticator, since a token is consumed when verified.
Register the service, issue a token when a user asks for a reset, and verify it when the link comes back:
gas.WithSingletonService[*token.Service](token.New())
raw, err := tokens.Issue(ctx, userID, "password-reset", 0)if err != nil { return err}sendResetLink(email, raw)
// later, in the handler the link leads to:userID, err := tokens.Verify(ctx, r.FormValue("token"), "password-reset")if errors.Is(err, auth.ErrUnauthenticated) { // unknown, used, expired, or not a reset token: ask for a new link}The first Verify returns the user’s ID; any later Verify of the same token returns an error wrapping ErrTokenInvalid.
Configuration
Section titled “Configuration”Config is bound from the token section of the configuration, over
DefaultConfig, unless WithConfig gives one. Its Settings:
- DefaultTTL: how long a token lives when Issue is given a ttl of 0. It must be positive. Default: DefaultTTL, 15 minutes.
- TokenLength: the number of random bytes in a token, at least 16. Default: DefaultTokenLength, 32.
- CleanupInterval: the time between deletions of expired tokens; 0 turns the cleanup off, and a negative interval is an error. Default: DefaultCleanupInterval, an hour.
- CleanupTimeout: the bound on each deletion, which must be positive when the cleanup is on. Default: DefaultCleanupTimeout, 30 seconds.
WithConfig makes Init use a copy of the given Config, so later changes
to the caller’s struct have no effect. Init checks the copy as it checks
a bound one: the validate tags, then the cleanup rules.
Init fails without a configuration:
- WithConfig(nil) makes Init fail with ErrNilConfig.
- Without WithConfig and without a ConfigProvider, Init fails with ErrNoConfigProvider.
Service.Config returns a copy of the configuration the last successful Init resolved, defaults included, or the zero Config before one. A failed Init and Close leave it as it was.
Lifecycle
Section titled “Lifecycle”New returns the constructor the dependency injection container calls. It fails only for a nil logger, with an error wrapping ErrNilLogger.
Service.Init runs these steps, in order:
- It resolves and checks the configuration.
- It builds a store that picks the SQL dialect from the database provider’s driver.
- It registers the store’s migrations with the migration manager, which runs them after every service’s Init.
- It publishes the configuration and the store together.
- It starts the background cleanup.
Service.Close stops the cleanup and waits for a deletion in progress to end.
A Service may be initialized again, with or without a Close between, any number of times:
- Each Init resolves the configuration afresh and builds a new store.
- Init stops a cleanup that an earlier Init started before it starts its own, so there is never more than one.
- An Init that fails leaves the service uninitialized, with its cleanup stopped.
Issue, Verify, Revoke and RevokeAllByPurpose check first that the service is initialized. Before Init succeeds, after an Init that failed, and after Close, they return an error wrapping ErrNotInitialized and touch nothing.
Issuing
Section titled “Issuing”Service.Issue makes a token of TokenLength random bytes from crypto/rand, encoded as unpadded URL-safe base64 (43 characters at the default length), so it is safe in a URL without escaping. It stores the token’s SHA-256 hash with the subject, the purpose and an expiry ttl from now, and returns the token. A ttl of 0 means DefaultTTL.
Issue checks its arguments in this order, and stores nothing when one fails:
- A negative ttl is an error wrapping ErrInvalidTTL.
- An empty subject is an error wrapping auth.ErrEmptySubject.
- A subject, then a purpose, longer than auth.MaxValueLength (255) bytes is an error wrapping auth.ErrValueTooLong that names the field, never its value. The check runs before the insert, so every database behaves the same.
Subject and purpose are otherwise stored as given; the purpose may be empty. A subject may hold any number of tokens, of any purposes.
Verifying
Section titled “Verifying”Service.Verify hashes the token it is given and consumes the stored token with that hash: it deletes the token and reads what it held in one atomic step, so of any number of calls presenting the same token, at the same time or not, at most one succeeds. Then:
- No stored token, including one consumed or revoked already: an error wrapping ErrTokenInvalid.
- A token issued for another purpose, compared exactly: an error wrapping ErrTokenInvalid. It is consumed all the same.
- An expired token: an error wrapping ErrTokenExpired. It is consumed all the same.
- Otherwise, the subject it was issued for.
So a token is burned the first time it is presented, whatever the outcome: a guess at its purpose cannot be retried, and a bug that passes the wrong purpose fails at once instead of leaving the token usable. The purpose is checked before the expiry, so presenting a token for the wrong flow says nothing about whether it has expired.
Revoking
Section titled “Revoking”Service.Revoke deletes one token, whatever its purpose and expiry. A token that is not stored, including one consumed or revoked already, is not an error, so a Revoke may be repeated.
Service.RevokeAllByPurpose deletes every token of a subject issued for a purpose, expired ones included, and is not an error when there are none; use it to cancel the outstanding reset links of a user who has just reset the password.
Expiry and cleanup
Section titled “Expiry and cleanup”A token is expired from its expiry on: at exactly its expiry, it is expired already. Expired tokens stay in the database until they are presented, revoked, or deleted by the cleanup.
The cleanup runs once every CleanupInterval, the first time one interval after Init. It deletes the tokens that are expired when it runs, each run bounded by CleanupTimeout.
Logging
Section titled “Logging”The service logs these events, each with gas/auth/token under
service:
- Init logs
service initializedat info level. - A cleanup run that succeeds logs
expired tokens deletedat debug level, with the number deleted undercount, zero included. - A cleanup run that fails logs
background task failedat warn level, withtoken cleanupundertaskand the error undererror. The cleanup goes on.
Nothing is logged for a run that Close interrupts.
Time precision
Section titled “Time precision”MySQL and SQLite keep times in whole seconds, and the auth stores truncate every time to the second before writing it, so a stored time is up to a second earlier than the one written. On those databases a token may so expire up to a second before its ttl has passed, never after. Postgres keeps microseconds.
Storage
Section titled “Storage”Tokens live in the table __gas_auth_tokens, on Postgres, MySQL or
SQLite, chosen by the name the database provider’s Driver method
reports:
- Postgres:
postgresorpgx. - MySQL:
mysql. It needsparseTime=truein the DSN, which gas/database turns on itself.multiStatementsis not needed, since gas/migrate sends a MySQL migration’s statements one at a time. - SQLite:
sqliteorsqlite3.
The store’s migrations create the table, and then drop a redundant index on the token hash that its first version made. Lookups use the hash’s unique index.
Postgres and SQLite consume a token with one DELETE ... RETURNING.
MySQL selects and deletes in one transaction, and treats a delete that
removed no row as a token another caller consumed.
Concurrency
Section titled “Concurrency”Every method is safe for concurrent use, Init and Close included.
Each Init publishes its configuration and store in one atomic step. A call that runs while Init does uses either the earlier ones or the new ones, never a mix, and a successful Init does not make the calls around it fail.
Init and Close run one at a time, so the published state and the running cleanup always belong to the same call: once Close returns, no cleanup runs until the next Init.
The atomic consume holds across processes that share the database, not only within one.
Errors
Section titled “Errors”Every error starts with gas/auth/token: and wraps its cause, to be
tested with errors.Is. Verify denies a token with an error wrapping
one of these:
- ErrTokenInvalid: no such token, or one issued for another purpose. It wraps auth.ErrUnauthenticated.
- ErrTokenExpired: the token has expired. It wraps auth.ErrCredentialsExpired, which wraps auth.ErrUnauthenticated.
So errors.Is(err, auth.ErrUnauthenticated) holds for every denial, and for nothing else. The other errors wrap:
- ErrInvalidTTL: Issue was given a negative ttl.
- auth.ErrEmptySubject: Issue was given an empty subject.
- auth.ErrValueTooLong: Issue was given a subject or a purpose longer than auth.MaxValueLength bytes.
- ErrNotInitialized: a method ran before Init succeeded, after an Init that failed, or after Close.
- ErrNilLogger: the constructor was given a nil logger.
- ErrNilConfig, ErrNoConfigProvider, ErrInvalidConfig: Init
could not resolve the configuration. ErrInvalidConfig wraps the
binder’s or the validator’s error, so errors.As finds
validator.ValidationErrors; a field that fails its tag is named
with the tag, after
invalid config: validate config:. - A database error, prefixed by the store and the operation, such as
gas/auth/token-store: consume token:.
ErrNotInitialized, ErrNilLogger, ErrNilConfig, ErrNoConfigProvider and ErrInvalidConfig are the auth module’s shared service sentinels, so they match the same errors from the module’s other services.
No error includes a token, its hash, or a configuration value. Sample messages:
gas/auth/token: unauthenticated: invalid tokengas/auth/token: unauthenticated: credentials expired: token expiredgas/auth/token: invalid ttl: must not be negativegas/auth/token: empty subjectgas/auth/token: value too long: subject is longer than 255 bytesgas/auth/token: service not initializedgas/auth/token: logger is nilgas/auth/token: config is nilgas/auth/token: invalid config: cleanup interval must not be negativegas/auth/token: invalid config: cleanup timeout must be positive when cleanup is enabledgas/auth/token: database not initializedAPI reference
Section titled “API reference”Constants
Section titled “Constants”const ( // DefaultTTL is the default of Settings.DefaultTTL. DefaultTTL = 15 * time.Minute // DefaultTokenLength is the default of Settings.TokenLength. DefaultTokenLength = 32 // DefaultCleanupInterval is the default of Settings.CleanupInterval. DefaultCleanupInterval = time.Hour // DefaultCleanupTimeout is the default of Settings.CleanupTimeout. DefaultCleanupTimeout = 30 * time.Second)const ServiceName = "gas/auth/token"ServiceName is the name of the service, which prefixes its errors.
Variables
Section titled “Variables”var ( // ErrTokenInvalid indicates that a token does not exist, was consumed // or revoked already, or was issued for another purpose. It wraps // auth.ErrUnauthenticated. ErrTokenInvalid = fmt.Errorf("%w: invalid token", auth.ErrUnauthenticated) // ErrTokenExpired indicates that a token was issued for the purpose // asked for and has expired. It wraps auth.ErrCredentialsExpired, and // so auth.ErrUnauthenticated. ErrTokenExpired = fmt.Errorf("%w: token expired", auth.ErrCredentialsExpired) // ErrInvalidTTL indicates that Issue was given a negative ttl. ErrInvalidTTL = errors.New("invalid ttl")
// ErrNotInitialized indicates that a method was called before Init // succeeded, after an Init that failed, or after Close. ErrNotInitialized = svcutil.ErrNotInitialized // ErrNilLogger indicates that the constructor was given a nil logger. ErrNilLogger = svcutil.ErrNilLogger // ErrNilConfig indicates that WithConfig was given nil. ErrNilConfig = svcutil.ErrNilConfig // ErrNoConfigProvider indicates that the service has neither a // configuration from WithConfig nor a ConfigProvider to bind one from. ErrNoConfigProvider = svcutil.ErrNoConfigProvider // ErrInvalidConfig indicates that the configuration failed to bind, // failed its validate tags, or broke a rule. ErrInvalidConfig = svcutil.ErrInvalidConfig)func New
Section titled “func New”func New( opts ...Option,) func(gas.DatabaseProvider, gas.Logger, gas.MigrationManager, gas.ConfigProvider) (*Service, error)New returns a constructor for a Service, in the shape the dependency injection container calls. The constructor applies opts and fails only for a nil logger, with an error wrapping ErrNilLogger; the configuration is resolved by Init.
type Config
Section titled “type Config”type Config struct { // Token holds the settings. Token Settings}Config is the token service’s configuration, bound from the token
section, as described in the package documentation.
func DefaultConfig
Section titled “func DefaultConfig”func DefaultConfig() *ConfigDefaultConfig returns a new Config holding the defaults.
type Option
Section titled “type Option”type Option func(*Service)Option configures a Service. Options only record what they are given; Init checks it.
func WithConfig
Section titled “func WithConfig”func WithConfig(cfg *Config) OptionWithConfig makes Init use a copy of cfg instead of binding the configuration from the ConfigProvider. Init checks the copy as it checks a bound one, and fails with ErrNilConfig for a nil cfg.
Default: bind the token section from the ConfigProvider over
DefaultConfig.
type Provider
Section titled “type Provider”type Provider interface { // Issue stores a new token for subject and purpose that lives for ttl, // or for the configured default when ttl is 0, and returns it. Issue(ctx context.Context, subject, purpose string, ttl time.Duration) (string, error) // Verify consumes the token and returns its subject when it was issued // for purpose and has not expired. Verify(ctx context.Context, rawToken, purpose string) (subject string, err error) // Revoke deletes the token; a token that is not stored is not an // error. Revoke(ctx context.Context, rawToken string) error // RevokeAllByPurpose deletes every token of subject issued for purpose. RevokeAllByPurpose(ctx context.Context, subject, purpose string) error}Provider is what Service offers once initialized, for code that wants to depend on an interface, such as to swap in a fake in tests. The methods behave as described in the package documentation.
type Service
Section titled “type Service”type Service struct { // contains filtered or unexported fields}Service issues and verifies single-use tokens, as described in the package documentation. It is safe for concurrent use.
func (*Service) Close
Section titled “func (*Service) Close”func (s *Service) Close(context.Context) errorClose stops the background cleanup and waits for a deletion in progress to end. The methods then return ErrNotInitialized until Init runs again. Close never fails, and does nothing to a service that is not initialized.
func (*Service) Config
Section titled “func (*Service) Config”func (s *Service) Config() ConfigConfig returns a copy of the configuration the last successful Init resolved, defaults included, or the zero Config before one. A failed Init and Close leave it as it was. Config holds no slice, map or pointer, so the copy shares nothing with the service.
func (*Service) Init
Section titled “func (*Service) Init”func (s *Service) Init(context.Context) errorInit resolves and checks the configuration, builds a new store and registers its migrations, publishes them, and restarts the background cleanup on the new store. Calls running at the same time use the earlier Init’s store until the new one is published. An Init that fails leaves the service uninitialized, with its cleanup stopped. The context is unused: the cleanup runs until Close, not until the context ends.
func (*Service) Issue
Section titled “func (*Service) Issue”func (s *Service) Issue( ctx context.Context, subject, purpose string, ttl time.Duration,) (string, error)Issue stores a new token for subject and purpose that expires ttl from now, and returns it. A ttl of 0 uses Settings.DefaultTTL; a negative ttl is an error wrapping ErrInvalidTTL. An empty subject is an error wrapping auth.ErrEmptySubject, and a subject or purpose longer than auth.MaxValueLength bytes one wrapping auth.ErrValueTooLong. Only the token’s hash is stored, and nothing is stored on error.
func (*Service) Name
Section titled “func (*Service) Name”func (s *Service) Name() stringName returns ServiceName.
func (*Service) Revoke
Section titled “func (*Service) Revoke”func (s *Service) Revoke(ctx context.Context, rawToken string) errorRevoke deletes the token, whatever its purpose and expiry. A token that is not stored, including one consumed or revoked already, is not an error, so Revoke may be called again.
func (*Service) RevokeAllByPurpose
Section titled “func (*Service) RevokeAllByPurpose”func (s *Service) RevokeAllByPurpose(ctx context.Context, subject, purpose string) errorRevokeAllByPurpose deletes every token of subject issued for purpose, expired ones included. Deleting none is not an error.
func (*Service) Verify
Section titled “func (*Service) Verify”func (s *Service) Verify(ctx context.Context, rawToken, purpose string) (string, error)Verify consumes the token and returns its subject when it was issued for purpose and has not expired. The token is deleted whatever the outcome, in one atomic step, so it verifies at most once. It returns an error wrapping ErrTokenInvalid for a token that does not exist, was consumed already, or was issued for another purpose, and one wrapping ErrTokenExpired for an expired one.
type Settings
Section titled “type Settings”type Settings struct { // DefaultTTL is how long a token lives when Issue is given a ttl of 0. // It must be positive. // // Default: DefaultTTL. DefaultTTL time.Duration `validate:"gt=0s"` // TokenLength is the number of random bytes in a token, at least 16. // // Default: DefaultTokenLength. TokenLength int `validate:"min=16"` // CleanupInterval is the time between deletions of expired tokens. An // interval of 0 turns the cleanup off; a negative one is an error. // // Default: DefaultCleanupInterval. CleanupInterval time.Duration // CleanupTimeout bounds each deletion of expired tokens. It must be // positive when CleanupInterval is. // // Default: DefaultCleanupTimeout. CleanupTimeout time.Duration}Settings are the token service’s settings.