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:
- The subject must not be empty, or Generate fails with ErrEmptySubject.
- 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.
- The expiry, as described below.
- The scopes, as described below.
- The metadata, as described below.
Scopes and metadata
Section titled “Scopes and metadata”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:
- It holds the reserved key PrincipalMetadataKeyScopes,
scopes: ErrReservedMetadataKey. - It does not encode as JSON: ErrInvalidMetadata.
Key expiry
Section titled “Key expiry”A key never expires unless WithTTL or WithExpiresAt is given; of the two, the last one given applies. Generate fails when:
- A TTL is not positive: ErrInvalidTTL.
- An expiry time is not after the call: ErrInvalidExpiry.
Authentication
Section titled “Authentication”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:
- A request without the header, or with an empty value, returns auth.ErrNoCredentials, so an auth.Chain moves on to its next member.
- A key no stored key matches returns auth.ErrUnauthenticated.
- A revoked key returns auth.ErrCredentialRevoked, even when it has expired too.
- An expired key, one whose ExpiresAt is not after the current time, returns auth.ErrCredentialsExpired.
- 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
scopesentry, 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.
Revocation and deletion
Section titled “Revocation and deletion”Revoking marks keys as revoked:
- Service.Revoke revokes the key a principal authenticated with, found by its CredentialID.
- Service.RevokeAll revokes every key of a subject.
- Service.RevokeAllByScheme does so only for the scheme auth.SchemeAPIKey.
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:
- ErrNilPrincipal for a nil principal or a nil pointer.
- ErrSchemeMismatch for a principal of another scheme than auth.SchemeAPIKey.
RevokeAllByScheme with another scheme does nothing.
Listing
Section titled “Listing”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
Section titled “Expired keys”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 deletedat debug level, with the number deleted undercount, zero included. - On failure, the message
background task failedat warn level, withapi key cleanupundertaskand the error undererror. The cleanup goes on.
Transactions
Section titled “Transactions”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.
Configuration
Section titled “Configuration”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:
- ErrInvalidConfig for a configuration that fails them.
- ErrNilConfig for a nil Config given to WithConfig.
- ErrNoConfigProvider for the lack of both a Config and a ConfigProvider.
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.
Lifecycle
Section titled “Lifecycle”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:
- It resolves the configuration.
- It picks the SQL dialect from the database’s driver name.
- It registers the migrations that create the
__gas_auth_api_keystable with the migration manager. - 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.
Storage
Section titled “Storage”The service supports Postgres, MySQL and SQLite, picked by the name the database provider’s Driver method reports:
- Postgres:
postgresorpgx. - MySQL:
mysql. The DSN needsparseTime=true, which gas/database turns on itself.multiStatementsis not needed, since gas/migrate sends a migration file’s statements one at a time. - SQLite:
sqliteorsqlite3.
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.
Concurrency
Section titled “Concurrency”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.
Errors
Section titled “Errors”The service’s own sentinel errors, to be tested with errors.Is:
- ErrNilConfig, ErrNoConfigProvider, ErrInvalidConfig: Init could not resolve a valid configuration. They are svcutil’s, so the validator’s errors stay in the chain for errors.As.
- ErrNotInitialized: a method ran before Init succeeded, after a failed Init, or after Close.
- ErrNilLogger: New’s constructor was given a nil logger. It is svcutil’s.
- ErrEmptySubject, ErrValueTooLong, ErrInvalidScope, ErrReservedMetadataKey, ErrInvalidMetadata, ErrInvalidTTL, ErrInvalidExpiry: Generate was given what it cannot store. ErrEmptySubject and ErrValueTooLong are the auth package’s.
- ErrNilPrincipal, ErrSchemeMismatch: Revoke or Delete was given a nil principal, or one of another scheme. They are the auth package’s.
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 credentialsgas/auth/apikey: unauthenticatedgas/auth/apikey: unauthenticated: credential revokedgas/auth/apikey: unauthenticated: credentials expiredgas/auth/apikey: service not initializedgas/auth/apikey: config is nilgas/auth/apikey: invalid config: cleanup timeout must be positive when cleanup is enabledgas/auth/apikey: logger is nilgas/auth/apikey: empty subjectgas/auth/apikey: value too long: name is longer than 255 bytesgas/auth/apikey: invalid scope "read,write": must not contain a commagas/auth/apikey: reserved metadata key "scopes"gas/auth/apikey: invalid metadata: does not encode as JSONgas/auth/apikey: invalid ttl: must be positivegas/auth/apikey: invalid expiry: must be in the futuregas/auth/apikey: nil principalgas/auth/apikey: principal scheme mismatchAPI reference
Section titled “API reference”Constants
Section titled “Constants”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)Variables
Section titled “Variables”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
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 ErrNilLogger; the configuration is resolved and checked in Init.
type Config
Section titled “type Config”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
Section titled “func DefaultConfig”func DefaultConfig() *ConfigDefaultConfig returns a new Config holding the defaults: the header DefaultHeaderName, no prefix, DefaultKeyLength random bytes, the cleanup off, and DefaultCleanupTimeout.
type GenerateOption
Section titled “type GenerateOption”type GenerateOption func(*generateOptions)GenerateOption customizes a call to Service.Generate.
func WithExpiresAt
Section titled “func WithExpiresAt”func WithExpiresAt(t time.Time) GenerateOptionWithExpiresAt 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
Section titled “func WithMetadata”func WithMetadata(md map[string]any) GenerateOptionWithMetadata 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
Section titled “func WithTTL”func WithTTL(ttl time.Duration) GenerateOptionWithTTL 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
Section titled “type KeyInfo”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
Section titled “type ListOption”type ListOption func(*listOptions)ListOption customizes a call to Service.List.
func WithIncludeRevoked
Section titled “func WithIncludeRevoked”func WithIncludeRevoked() ListOptionWithIncludeRevoked makes List return revoked keys too, with their KeyInfo.DeletedAt set.
Default: revoked keys are left out.
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. 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
Section titled “type Provider”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
Section titled “type Service”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 (*Service) Authenticate
Section titled “func (*Service) Authenticate”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 (*Service) Close
Section titled “func (*Service) Close”func (s *Service) Close(context.Context) errorClose 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 (*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. On a Provider WithTx returned, it is the configuration of the service it came from.
func (*Service) Delete
Section titled “func (*Service) Delete”func (s *Service) Delete(ctx context.Context, principal gas.Principal) errorDelete 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 (*Service) DeleteAll
Section titled “func (*Service) DeleteAll”func (s *Service) DeleteAll(ctx context.Context, subject string) errorDeleteAll removes every stored key of subject, as Delete does one.
func (*Service) Generate
Section titled “func (*Service) Generate”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 (*Service) Init
Section titled “func (*Service) Init”func (s *Service) Init(context.Context) errorInit 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 (*Service) List
Section titled “func (*Service) List”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 (*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, principal gas.Principal) errorRevoke 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 (*Service) RevokeAll
Section titled “func (*Service) RevokeAll”func (s *Service) RevokeAll(ctx context.Context, subject string) errorRevokeAll revokes every key of subject, as Revoke does one. Keys already revoked keep their revocation time.
func (*Service) RevokeAllByScheme
Section titled “func (*Service) RevokeAllByScheme”func (s *Service) RevokeAllByScheme(ctx context.Context, subject, scheme string) errorRevokeAllByScheme 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 (*Service) WithTx
Section titled “func (*Service) WithTx”func (s *Service) WithTx(tx *sql.Tx) ProviderWithTx 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
Section titled “type Settings”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.