apikey

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package apikey provides API key authentication for the Gas ecosystem. It implements gas.Authenticator, gas.PrincipalRevoker, and gas.Service.

Index

Constants

View Source
const (
	// PrincipalMetadataKeyScopes represents the principal metadata key used to store API key scopes.
	PrincipalMetadataKeyScopes = "scopes"
)

Variables

This section is empty.

Functions

func New

New captures options and returns a DI-injectable constructor.

Types

type Config

type Config struct {
	env.WithGasEnv

	APIKey Settings
}

Config holds API key service settings.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with sensible defaults.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the Config for correctness.

type GenerateOption

type GenerateOption func(*generateOptions)

GenerateOption customizes a call to Service.Generate.

func WithExpiresAt

func WithExpiresAt(t time.Time) GenerateOption

WithExpiresAt sets an explicit expiration time on the API key. A zero time is ignored. If both WithTTL and WithExpiresAt are supplied, the last one wins.

func WithMetadata

func WithMetadata(md map[string]any) GenerateOption

WithMetadata attaches a metadata map to the API key. It is stored as JSON and returned when the key is authenticated. Passing a nil or empty map is equivalent to not calling this option.

func WithTTL

func WithTTL(ttl time.Duration) GenerateOption

WithTTL sets the API key to expire after the given duration from now. A non-positive duration is ignored. If both WithTTL and WithExpiresAt are supplied, the last one wins.

type KeyInfo

type KeyInfo = db.KeyInfo

KeyInfo contains non-sensitive information about an API key. Re-exported from the db package for convenience.

type ListOption

type ListOption func(*listOptions)

ListOption customizes a call to Service.List.

func WithIncludeRevoked

func WithIncludeRevoked() ListOption

WithIncludeRevoked causes List to also return soft-deleted (revoked) keys. Revoked keys carry a non-nil KeyInfo.DeletedAt so callers can distinguish them from active keys.

type Option

type Option func(*Service)

Option configures a Service.

func WithConfig

func WithConfig(cfg *Config) Option

WithConfig sets a custom configuration, skipping auto-bind from ConfigProvider.

type Provider

type Provider interface {
	// Authenticate reads the API key from the configured header, hashes it,
	// looks it up in the database, validates expiry, updates last_used, and
	// returns a principal with scheme "apikey".
	Authenticate(ctx context.Context, r *http.Request) (gas.Principal, error)
	// Revoke soft-deletes an API key by the principal's credential ID. The
	// row stays in the database with deleted_at set and is excluded from
	// authentication and listing.
	Revoke(ctx context.Context, principal gas.Principal) error
	// RevokeAll soft-deletes all API keys for the given subject.
	RevokeAll(ctx context.Context, subject string) error
	// RevokeAllByScheme delegates to RevokeAll if the scheme is "apikey",
	// otherwise it is a no-op.
	RevokeAllByScheme(ctx context.Context, subject, scheme string) error
	// Delete permanently removes an API key row by the principal's credential
	// ID. Prefer Revoke for normal flows.
	Delete(ctx context.Context, principal gas.Principal) error
	// DeleteAll permanently removes all API key rows for the given subject.
	// Prefer RevokeAll for normal flows.
	DeleteAll(ctx context.Context, subject string) error
	// Generate creates a new API key for the given subject, stores its hash in
	// the database, and returns the full key exactly once along with the stored
	// KeyInfo record. The plaintext key is only available from this call; only
	// its hash is persisted.
	// Optional GenerateOption values (WithMetadata, WithTTL, WithExpiresAt) customize the key.
	Generate(ctx context.Context, subject, name string, scopes []string, opts ...GenerateOption) (key string, info *KeyInfo, err error)
	// List returns non-sensitive information about API keys for a subject. By
	// default only active (non-revoked) keys are returned; pass
	// WithIncludeRevoked to also include soft-deleted keys.
	List(ctx context.Context, subject string, opts ...ListOption) ([]KeyInfo, error)
	// WithTx returns a Provider whose operations execute against the given
	// transaction, allowing API key operations to be composed atomically with
	// caller-owned writes. The caller owns tx lifecycle (commit/rollback); the
	// returned Provider is scoped to the lifetime of tx and must not be cached.
	WithTx(tx *sql.Tx) Provider
}

Provider defines an interface for managing API keys and their associated operations, such as authentication and revocation.

type Service

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

Service is an API key authenticator implementing gas.Authenticator, gas.PrincipalRevoker, and gas.Service.

func (*Service) Authenticate

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

Authenticate reads the API key from the configured header, hashes it, looks it up in the database, validates expiry, updates last_used, and returns a principal with scheme "apikey".

func (*Service) Close

func (s *Service) Close() error

Close performs cleanup. API key service is stateless so this is a no-op.

func (*Service) Delete

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

Delete permanently removes an API key row by the principal's credential ID. Prefer Revoke for normal flows; use Delete only when the row must be purged (e.g. GDPR erasure, test cleanup).

func (*Service) DeleteAll

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

DeleteAll permanently removes all API key rows for the given subject. Prefer RevokeAll for normal flows.

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 new API key for the given subject, stores its hash in the database, and returns the full key exactly once along with its record ID.

func (*Service) Init

func (s *Service) Init() error

Init validates configuration and initializes the store.

func (*Service) List

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

List returns non-sensitive information about API keys for a subject. By default, only active (non-revoked) keys are returned; pass WithIncludeRevoked to also include soft-deleted keys.

func (*Service) Name

func (s *Service) Name() string

Name returns the service identifier.

func (*Service) Revoke

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

Revoke soft-deletes an API key by the principal's credential ID. The row remains in the database with deleted_at set, but is excluded from authentication and listing. Use Delete for permanent removal.

func (*Service) RevokeAll

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

RevokeAll soft-deletes all API keys for the given subject. Use DeleteAll for permanent removal.

func (*Service) RevokeAllByScheme

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

RevokeAllByScheme delegates to RevokeAll if the scheme is "apikey", otherwise it is a no-op.

func (*Service) WithTx

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

WithTx returns a Provider whose operations execute against tx. The caller owns tx lifecycle; the returned Provider is scoped to its lifetime and must not be cached.

type Settings

type Settings struct {
	// HeaderName is the HTTP header used to pass the API key.
	HeaderName string
	// Prefix is prepended to generated keys for identification.
	Prefix string
	// KeyLength is the number of random bytes used for key generation.
	KeyLength int
}

Settings represents the API key configuration values.

Directories

Path Synopsis
db

Jump to

Keyboard shortcuts

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