Skip to content
Gasv0.10.0

gas/auth

auth/apikey

import "github.com/gasmod/gas/auth/apikey"

Package apikey authenticates HTTP requests by API key: a Service generates random keys, stores only their SHA-256 hashes in a SQL database, and turns a key presented in a request header into a gas.Principal with the key’s subject, scopes and metadata.

The Service implements auth.Authenticator, auth.PrincipalRevoker and gas.Service.

Register the service with the container, give a client a key, and authenticate requests with it:

opt := gas.WithSingletonService[*apikey.Service](apikey.New())
// keys is the *apikey.Service the container built and initialized:
key, info, err := keys.Generate(ctx, "client-42", "billing export",
[]string{"invoices:read"}, apikey.WithTTL(90*24*time.Hour))
if err != nil {
return err
}
// show key to the client once; keep info.ID to revoke it later
mux.Handle("/invoices", auth.Middleware(keys)(invoicesHandler))

A request with the header X-API-Key: <key> reaches invoicesHandler with a principal whose:

  • Subject is client-42.
  • Scheme is auth.SchemeAPIKey.
  • CredentialID is info.ID.
  • Metadata holds []string{"invoices:read"} under PrincipalMetadataKeyScopes.

A request without the header gets a 401.

Service.Generate makes a key from Settings.KeyLength bytes of crypto/rand, encoded as unpadded URL-safe base64, after Settings.Prefix: with the defaults, 43 characters and no prefix. It stores the key’s SHA-256 hash, never the key, and returns the key once; it cannot be read again.

Generate also returns the stored key’s KeyInfo, which holds neither the key nor its hash:

  • Its ID.
  • The subject and name given.
  • The scopes and the metadata.
  • The times.
  • KeyPrefix: Settings.Prefix and the first eight characters of the random part, stored in clear text to tell keys apart in a list. Those eight characters are 48 of the key’s random bits; at the minimum KeyLength of 16 bytes, 80 bits stay secret.

Generate checks its arguments in this order, and stores nothing when one fails:

  1. The subject must not be empty, or Generate fails with ErrEmptySubject.
  2. The subject, then the name, hold at most auth.MaxValueLength (255) bytes, or Generate fails with ErrValueTooLong, naming the field. The name may be empty. The limit is checked before anything is stored, so every database behaves the same.
  3. The expiry, as described below.
  4. The scopes, as described below.
  5. The metadata, as described below.

Scopes are strings the app gives meaning to. Each must be non-empty, hold no comma, and not start or end with white space; otherwise Generate fails with ErrInvalidScope. They come back as given, in order; nil comes back as an empty slice.

WithMetadata stores a map with the key, as JSON, so its values come back as JSON decodes them: a number as a float64, a struct as a map[string]any. The KeyInfo Generate returns already holds the decoded form. Metadata fails Generate when:

A key never expires unless WithTTL or WithExpiresAt is given; of the two, the last one given applies. Generate fails when:

Service.Authenticate reads the first value of the header Settings.HeaderName, X-API-Key by default, and compares it with the stored keys by hash, exactly: surrounding white space is part of the key. In this order:

  1. A request without the header, or with an empty value, returns auth.ErrNoCredentials, so an auth.Chain moves on to its next member.
  2. A key no stored key matches returns auth.ErrUnauthenticated.
  3. A revoked key returns auth.ErrCredentialRevoked, even when it has expired too.
  4. An expired key, one whose ExpiresAt is not after the current time, returns auth.ErrCredentialsExpired.
  5. Otherwise the key authenticates. The principal’s metadata holds the key’s metadata and, under PrincipalMetadataKeyScopes, its scopes as a []string, never nil. A stored key whose metadata has a scopes entry, written before the key was reserved, gets it replaced by the scopes.

A database failure while looking the key up is returned as is, wrapped, and matches none of the auth sentinels, so auth.Middleware answers 500.

On success Authenticate records the time in the key’s LastUsed. That write is best-effort: when it fails the request still authenticates. The failure is logged with the service’s gas.Logger at warn level, with the message api key last used update failed, the key’s ID under key_id and the error under error. When the request’s context has ended, the failure is not logged.

Revoking marks keys as revoked:

A revoked key stays stored, with KeyInfo.DeletedAt set, and authenticating with it fails with auth.ErrCredentialRevoked. Revoking a key twice keeps the first time.

Service.Delete and Service.DeleteAll remove keys from the database, revoked or not, for when the rows themselves must go. A deleted key authenticates as an unknown one, with auth.ErrUnauthenticated.

Revoke and Delete do nothing for an unknown key. Rather than doing nothing, they fail with:

RevokeAllByScheme with another scheme does nothing.

Service.List returns a subject’s keys, newest first, as KeyInfo. Revoked keys are left out unless WithIncludeRevoked is given. Expired keys are listed, with their ExpiresAt, until they are deleted.

Keys with the same stored CreatedAt, as two keys generated within one second on SQLite or MySQL can have, are ordered by ID, descending, so a list keeps its order from one call to the next. IDs are random, so that order says nothing about which key came first.

Expired keys stay stored, and keep failing with auth.ErrCredentialsExpired, unless the cleanup is enabled with a positive Settings.CleanupInterval.

The cleanup is off by default: deleting a key loses its record, and an app may want to list expired keys or tell a client that its key expired.

When enabled, the cleanup runs in the background from Init to Close, first one interval after Init. It deletes every key whose expiry has passed, revoked or not; a deleted key then fails as unknown, with auth.ErrUnauthenticated. Each run is bounded by Settings.CleanupTimeout.

Each run logs, with gas/auth/apikey under service:

  • On success, the message expired api keys deleted at debug level, with the number deleted under count, zero included.
  • On failure, the message background task failed at warn level, with api key cleanup under task and the error under error. The cleanup goes on.

Service.WithTx returns a Provider whose operations run in a *sql.Tx the caller owns, so that generating or revoking a key commits or rolls back with the caller’s own writes. The Provider must not outlive the transaction, and the transaction must not be nil.

Config binds from the configuration section apikey. Its Settings:

  • HeaderName: the header the key is read from. Required. Default: DefaultHeaderName.
  • Prefix: put before every generated key, such as gas_, so keys are easy to recognize. Default: none.
  • KeyLength: random bytes in a key, at least 16. Default: DefaultKeyLength.
  • CleanupInterval: time between cleanup runs. Zero turns the cleanup off; a negative value is an error. Default: zero, off.
  • CleanupTimeout: bound on one cleanup run; must be positive when the cleanup is on. Default: DefaultCleanupTimeout.

Service.Init resolves the configuration:

  • With WithConfig, it uses a copy of the given Config, so later changes to it do not reach the service.
  • Otherwise it binds DefaultConfig from the gas.ConfigProvider, so a setting the configuration does not set keeps its default.

Either way the validate tags and the cleanup rules are checked. Init fails with:

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. The Provider WithTx returns is a *Service, whose Config is that of the service it came from.

New returns the constructor the dependency injection container calls. It fails only for a nil logger, with ErrNilLogger.

Service.Init runs these steps, in order:

  1. It resolves the configuration.
  2. It picks the SQL dialect from the database’s driver name.
  3. It registers the migrations that create the __gas_auth_api_keys table with the migration manager.
  4. It starts the cleanup when it is enabled.

The migration manager runs the migrations after every service’s Init, so a cleanup run that comes before them fails, is logged, and the next run goes on.

Service.Close stops the cleanup, waits for a run in progress, and uninitializes the service.

Init may run again, after Close or not:

  • It resolves the configuration afresh, and restarts the cleanup with the new settings, never running two.
  • A failed Init stops the cleanup and leaves the service uninitialized, whatever an earlier Init set up.

Every method other than Name, Init, Close, Config and WithTx checks first that the service is initialized, and fails with ErrNotInitialized before Init has succeeded, after a failed Init, and after Close, until Init succeeds again. The methods of a Provider WithTx returned check the service they came from at each call, and fail the same way.

The service supports Postgres, MySQL and SQLite, picked by the name the database provider’s Driver method reports:

  • Postgres: postgres or pgx.
  • MySQL: mysql. The DSN needs parseTime=true, which gas/database turns on itself. multiStatements is not needed, since gas/migrate sends a migration file’s statements one at a time.
  • SQLite: sqlite or sqlite3.

Postgres keeps scopes in a TEXT[] column. MySQL and SQLite keep them in one TEXT column, joined with commas, such as read,write, which is why a scope may not hold a comma. Metadata is a JSON object.

SQLite keeps times as text, in UTC. 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 key may so expire up to a second before its ExpiresAt, never after. Postgres keeps microseconds.

A Service is safe for concurrent use, and Init and Close may run while requests are served.

Init builds its configuration and store afresh and publishes them in one step. A request sees either the old ones or the new ones, never a mix, or fails with ErrNotInitialized.

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 service’s own sentinel errors, to be tested with errors.Is:

Authenticate’s denials wrap auth.ErrNoCredentials, auth.ErrUnauthenticated, auth.ErrCredentialRevoked and auth.ErrCredentialsExpired, as described under Authentication. Database failures are wrapped with the operation’s name.

Every error starts with ServiceName. No error includes a key, a key’s hash, a configuration value, or a metadata value, so the errors of encoding/json, which can quote one, are replaced by a fixed reason. An invalid scope is quoted, since it is not a secret:

gas/auth/apikey: no credentials
gas/auth/apikey: unauthenticated
gas/auth/apikey: unauthenticated: credential revoked
gas/auth/apikey: unauthenticated: credentials expired
gas/auth/apikey: service not initialized
gas/auth/apikey: config is nil
gas/auth/apikey: invalid config: cleanup timeout must be positive when cleanup is enabled
gas/auth/apikey: logger is nil
gas/auth/apikey: empty subject
gas/auth/apikey: value too long: name is longer than 255 bytes
gas/auth/apikey: invalid scope "read,write": must not contain a comma
gas/auth/apikey: reserved metadata key "scopes"
gas/auth/apikey: invalid metadata: does not encode as JSON
gas/auth/apikey: invalid ttl: must be positive
gas/auth/apikey: invalid expiry: must be in the future
gas/auth/apikey: nil principal
gas/auth/apikey: principal scheme mismatch

const (
// ServiceName is the service's name, which prefixes its errors.
ServiceName = "gas/auth/apikey"
// PrincipalMetadataKeyScopes is the principal metadata key that holds
// a key's scopes, as a []string. Key metadata may not use it.
PrincipalMetadataKeyScopes = "scopes"
)

const (
// DefaultHeaderName is the default HTTP header the key is read from.
DefaultHeaderName = "X-API-Key"
// DefaultKeyLength is the default number of random bytes in a key.
DefaultKeyLength = 32
// DefaultCleanupTimeout is the default bound on one run of the
// expired-key cleanup.
DefaultCleanupTimeout = 30 * time.Second
)

var (
// ErrNilConfig indicates that WithConfig was given a nil
// configuration. It is svcutil's sentinel, so either matches.
ErrNilConfig = svcutil.ErrNilConfig
// ErrNoConfigProvider indicates that the service has neither a
// configuration given to WithConfig nor a ConfigProvider.
ErrNoConfigProvider = svcutil.ErrNoConfigProvider
// ErrInvalidConfig indicates that the configuration failed to bind,
// failed its validate tags, or broke one of the service's rules.
ErrInvalidConfig = svcutil.ErrInvalidConfig
// ErrNotInitialized indicates that a method was called before Init
// succeeded, after a failed Init, or after Close.
ErrNotInitialized = svcutil.ErrNotInitialized
// ErrNilLogger indicates that New's constructor was given a nil
// logger. It is svcutil's sentinel, so either matches.
ErrNilLogger = svcutil.ErrNilLogger
// ErrEmptySubject indicates that Generate was given an empty subject.
// It is auth.ErrEmptySubject, so either matches.
ErrEmptySubject = auth.ErrEmptySubject
// ErrValueTooLong indicates that Generate was given a subject or a
// name longer than auth.MaxValueLength bytes. It is
// auth.ErrValueTooLong, so either matches.
ErrValueTooLong = auth.ErrValueTooLong
// ErrNilPrincipal indicates that Revoke or Delete was given a nil
// principal or a nil pointer. It is auth.ErrNilPrincipal, so either
// matches.
ErrNilPrincipal = auth.ErrNilPrincipal
// ErrSchemeMismatch indicates that Revoke or Delete was given a
// principal of another scheme than auth.SchemeAPIKey. It is
// auth.ErrSchemeMismatch, so either matches.
ErrSchemeMismatch = auth.ErrSchemeMismatch
// ErrReservedMetadataKey indicates that Generate was given metadata
// holding PrincipalMetadataKeyScopes.
ErrReservedMetadataKey = errors.New("reserved metadata key")
// ErrInvalidMetadata indicates that Generate was given metadata that
// does not encode as JSON.
ErrInvalidMetadata = errors.New("invalid metadata")
// ErrInvalidScope indicates that Generate was given a scope that is
// empty, holds a comma, or starts or ends with white space.
ErrInvalidScope = errors.New("invalid scope")
// ErrInvalidTTL indicates that Generate was given a TTL that is not
// positive.
ErrInvalidTTL = errors.New("invalid ttl")
// ErrInvalidExpiry indicates that Generate was given an expiry time
// that is not in the future.
ErrInvalidExpiry = errors.New("invalid expiry")
)

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 ErrNilLogger; the configuration is resolved and checked in Init.

type Config struct {
// APIKey holds the service's settings.
APIKey Settings
}

Config is the API key service’s configuration, as described in the package documentation. It binds from the apikey section.

func DefaultConfig() *Config

DefaultConfig returns a new Config holding the defaults: the header DefaultHeaderName, no prefix, DefaultKeyLength random bytes, the cleanup off, and DefaultCleanupTimeout.

type GenerateOption func(*generateOptions)

GenerateOption customizes a call to Service.Generate.

func WithExpiresAt(t time.Time) GenerateOption

WithExpiresAt makes the key expire at t. A t that is not after the time Generate is called, the zero time included, makes Generate fail with ErrInvalidExpiry. Of WithTTL and WithExpiresAt, the last one given applies.

Default: the key never expires.

func WithMetadata(md map[string]any) GenerateOption

WithMetadata stores md with the key, as JSON. Authenticate puts its values in the principal’s metadata. md may not hold the key PrincipalMetadataKeyScopes. A nil or empty md stores no metadata.

func WithTTL(ttl time.Duration) GenerateOption

WithTTL makes the key expire ttl after Generate is called. A ttl that is not positive makes Generate fail with ErrInvalidTTL. Of WithTTL and WithExpiresAt, the last one given applies.

Default: the key never expires.

type KeyInfo struct {
// CreatedAt is when the key was generated.
CreatedAt time.Time
// LastUsed is when the key last authenticated a request, or nil if
// it never has.
LastUsed *time.Time
// ExpiresAt is when the key stops authenticating, or nil if it never
// expires.
ExpiresAt *time.Time
// DeletedAt is when the key was revoked, or nil if it is not.
DeletedAt *time.Time
// Metadata holds the values given to WithMetadata, as decoded from
// JSON. It is never nil.
Metadata map[string]any
// ID identifies the key. It is the CredentialID of the principals the
// key authenticates.
ID string
// Subject is the user or client the key belongs to.
Subject string
// Name is the label given to Generate.
Name string
// KeyPrefix is Settings.Prefix and the first eight characters of the
// key's random part, to tell keys apart.
KeyPrefix string
// Scopes are the scopes given to Generate. It is never nil.
Scopes []string
}

KeyInfo describes a stored API key, as described in the package documentation. It holds neither the key nor its hash.

type ListOption func(*listOptions)

ListOption customizes a call to Service.List.

func WithIncludeRevoked() ListOption

WithIncludeRevoked makes List return revoked keys too, with their KeyInfo.DeletedAt set.

Default: revoked keys are left out.

type Option func(*Service)

Option configures a Service. Options only record what they are given; Init checks it.

func WithConfig(cfg *Config) Option

WithConfig makes Init use a copy of cfg instead of binding the configuration from the ConfigProvider. The copy is checked like a bound one, and later changes to cfg do not reach the service. A nil cfg makes Init fail with ErrNilConfig.

Default: bind the apikey section from the ConfigProvider over DefaultConfig.

type Provider interface {
// Authenticator authenticates a request by the key in its header.
auth.Authenticator
// PrincipalRevoker revokes the key a principal authenticated with, or
// every key of a subject. RevokeAllByScheme is a no-op for a scheme
// other than auth.SchemeAPIKey.
auth.PrincipalRevoker
// Delete removes the stored key principal authenticated with.
Delete(ctx context.Context, principal gas.Principal) error
// DeleteAll removes every stored key of subject.
DeleteAll(ctx context.Context, subject string) error
// Generate creates and stores a key, and returns it with its KeyInfo.
Generate(
ctx context.Context,
subject, name string,
scopes []string,
opts ...GenerateOption,
) (key string, info *KeyInfo, err error)
// List returns the keys of subject, newest first.
List(ctx context.Context, subject string, opts ...ListOption) ([]KeyInfo, error)
// WithTx returns a Provider whose operations run in tx.
WithTx(tx *sql.Tx) Provider
}

Provider is what a Service offers once initialized: authentication, revocation and key management, as described in the package documentation. Code that uses API keys can depend on it, and tests can replace it.

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

Service authenticates requests by API key and manages the keys, as described in the package documentation. It is safe for concurrent use.

func (s *Service) Authenticate(ctx context.Context, r *http.Request) (gas.Principal, error)

Authenticate reads the key from the configured header and returns the principal of the key it names, as described in the package documentation. A missing key is ErrNoCredentials; an unknown, revoked or expired one matches auth.ErrUnauthenticated. No error includes the key.

func (s *Service) Close(context.Context) error

Close stops the expired-key cleanup, waits for a run in progress to return, and uninitializes the service: its methods, and those of the Providers WithTx returned, fail with ErrNotInitialized until Init succeeds again. The context is unused.

func (s *Service) Config() Config

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. Config holds no slice, map or pointer, so the copy shares nothing with the service. On a Provider WithTx returned, it is the configuration of the service it came from.

func (s *Service) Delete(ctx context.Context, principal gas.Principal) error

Delete removes the stored key principal authenticated with, by its CredentialID, revoked or not. Authenticating with it then fails with auth.ErrUnauthenticated, as for a key that never existed. An unknown key is a no-op. A nil principal is ErrNilPrincipal, and a principal of another scheme ErrSchemeMismatch.

func (s *Service) DeleteAll(ctx context.Context, subject string) error

DeleteAll removes every stored key of subject, as Delete does one.

func (s *Service) Generate(
ctx context.Context,
subject, name string,
scopes []string,
opts ...GenerateOption,
) (key string, info *KeyInfo, err error)

Generate creates a key for subject, labeled name, with scopes, and stores its hash, as described in the package documentation. It returns the key, which is not stored and cannot be read again, and the stored key’s KeyInfo. An invalid subject, name, expiry, scope or metadata fails before anything is stored.

func (s *Service) Init(context.Context) error

Init resolves and checks the configuration, sets up the store and registers its migrations, and starts the expired-key cleanup when it is enabled, as described in the package documentation. A failed Init stops the cleanup and leaves the service uninitialized. The context is unused.

func (s *Service) List(ctx context.Context, subject string, opts ...ListOption) ([]KeyInfo, error)

List returns the keys of subject, newest first, keys created at the same stored time ordered by ID, as described in the package documentation. Revoked keys are left out unless WithIncludeRevoked is given; expired keys are listed until they are deleted. A subject without keys gets an empty slice.

func (s *Service) Name() string

Name returns ServiceName.

func (s *Service) Revoke(ctx context.Context, principal gas.Principal) error

Revoke revokes the key principal authenticated with, by its CredentialID: the key stays stored, and authenticating with it fails with auth.ErrCredentialRevoked. An unknown key and a key already revoked are no-ops. A nil principal is ErrNilPrincipal, and a principal of another scheme ErrSchemeMismatch.

func (s *Service) RevokeAll(ctx context.Context, subject string) error

RevokeAll revokes every key of subject, as Revoke does one. Keys already revoked keep their revocation time.

func (s *Service) RevokeAllByScheme(ctx context.Context, subject, scheme string) error

RevokeAllByScheme is RevokeAll when scheme is auth.SchemeAPIKey, and a no-op for any other scheme. Either way it fails with ErrNotInitialized when the service is not initialized.

func (s *Service) WithTx(tx *sql.Tx) Provider

WithTx returns a Provider whose operations run in tx, as described in the package documentation. The caller owns tx; the Provider must not outlive it. The Provider uses what the service’s last successful Init set up, at each call, so its methods fail with ErrNotInitialized whenever the service’s do.

type Settings struct {
// HeaderName is the HTTP header the key is read from. It is required.
HeaderName string `validate:"required"`
// Prefix is prepended to every generated key, such as `gas_`. It may
// be empty.
Prefix string
// KeyLength is the number of random bytes in a generated key, at
// least 16.
KeyLength int `validate:"min=16"`
// CleanupInterval is the time between runs of the expired-key
// cleanup. Zero turns the cleanup off; a negative value is an error.
CleanupInterval time.Duration
// CleanupTimeout bounds one run of the cleanup. It must be positive
// when CleanupInterval is.
CleanupTimeout time.Duration
}

Settings are the API key service’s settings, as described in the package documentation.