Documentation
¶
Index ¶
- Constants
- Variables
- func CalculateRefill(apiKey *ApiKey, now time.Time) bool
- func CheckPermissions(granted map[string][]string, required map[string][]string) bool
- func DefaultKeyGenerator(length int, prefix string) (string, error)
- func DefaultKeyHasher(key string) (string, error)
- func EvaluateRateLimit(apiKey *ApiKey, now time.Time) bool
- type ApiKey
- type ApiKeyCreatedPayload
- type ApiKeyDeletedPayload
- type ApiKeyExpiredPayload
- type ApiKeyUpdatedPayload
- type ApiKeyVerifiedPayload
- type Config
- type CreateApiKeyParams
- type CreateApiKeyResult
- type DeleteApiKeyParams
- type GetApiKeyParams
- type KeyGeneratorFunc
- type KeyHasherFunc
- type ListApiKeysParams
- type ListApiKeysResult
- type Option
- func WithCustomKeyGenerator(fn KeyGeneratorFunc) Option
- func WithCustomKeyHasher(fn KeyHasherFunc) Option
- func WithDefaultKeyLength(length int) Option
- func WithDefaultPrefix(prefix string) Option
- func WithDeferUpdates(deferUpdates bool) Option
- func WithDisableKeyHashing(disable bool) Option
- func WithEnableSessionForAPIKeys(enable bool) Option
- func WithExpiration(defaultExpiresIn *time.Duration) Option
- func WithHeaderNames(headers ...string) Option
- func WithRateLimit(enabled bool, window time.Duration, maxReq int64) Option
- type Plugin
- func (p *Plugin) Authenticate() func(next http.Handler) http.Handler
- func (p *Plugin) Config() Config
- func (p *Plugin) CreateKey(ctx context.Context, params CreateApiKeyParams) (*CreateApiKeyResult, error)
- func (p *Plugin) DeleteAllExpiredKeys(ctx context.Context) (int64, error)
- func (p *Plugin) DeleteKey(ctx context.Context, params DeleteApiKeyParams) error
- func (p *Plugin) GetKey(ctx context.Context, params GetApiKeyParams) (*ApiKey, error)
- func (p *Plugin) ID() string
- func (p *Plugin) Init(ctx *plugin.Context) error
- func (p *Plugin) ListKeys(ctx context.Context, params ListApiKeysParams) (*ListApiKeysResult, error)
- func (p *Plugin) UpdateKey(ctx context.Context, params UpdateApiKeyParams) (*ApiKey, error)
- func (p *Plugin) VerifyKey(ctx context.Context, params VerifyApiKeyParams) (*VerifyApiKeyResult, error)
- type Repository
- type UpdateApiKeyParams
- type VerifyApiKeyParams
- type VerifyApiKeyResult
Constants ¶
const ( ApiKeyContextKey contextKey = "apikey" UserContextKey contextKey = "apikey_user" )
const ( // EventApiKeyCreated is emitted after a new API Key is successfully issued. // Payload: *ApiKeyCreatedPayload EventApiKeyCreated = "apikey:created" // EventApiKeyVerified is emitted after an incoming API Key verification attempt completes. // Payload: *ApiKeyVerifiedPayload EventApiKeyVerified = "apikey:verified" // EventApiKeyUpdated is emitted when an existing API Key record is modified. // Payload: *ApiKeyUpdatedPayload EventApiKeyUpdated = "apikey:updated" // EventApiKeyDeleted is emitted when an API Key is deleted or revoked. // Payload: *ApiKeyDeletedPayload EventApiKeyDeleted = "apikey:deleted" // EventApiKeyExpired is emitted when an expired API Key is attempted or purged. // Payload: *ApiKeyExpiredPayload EventApiKeyExpired = "apikey:expired" )
const PluginID = "api-key"
PluginID is the unique string identifier for the API Key plugin ("api-key").
Variables ¶
var ( // ErrKeyNotFound is returned when an API Key record cannot be located in storage. ErrKeyNotFound = errors.New("apikey: key not found") // ErrKeyDisabled is returned when attempting to authenticate with a disabled API Key. ErrKeyDisabled = errors.New("apikey: key is disabled") // ErrKeyExpired is returned when the API Key has passed its expiration timestamp. ErrKeyExpired = errors.New("apikey: key has expired") // ErrUsageExceeded is returned when the remaining request quota reached zero. ErrUsageExceeded = errors.New("apikey: request quota exceeded") // ErrRateLimitExceeded is returned when request rate exceeds allowed max requests in the time window. ErrRateLimitExceeded = errors.New("apikey: rate limit exceeded") // ErrInvalidPrefix is returned when a provided key prefix does not match allowed format. ErrInvalidPrefix = errors.New("apikey: invalid key prefix") // ErrInvalidName is returned when key name is invalid or empty when required. ErrInvalidName = errors.New("apikey: invalid key name") ErrUnauthorized = errors.New("apikey: unauthorized scope permissions") )
Functions ¶
func CalculateRefill ¶
CalculateRefill checks if quota refill interval has elapsed and updates Remaining and LastRefillAt. Returns true if quota was refilled.
func CheckPermissions ¶
CheckPermissions checks whether granted permissions satisfy all required permissions.
func DefaultKeyGenerator ¶
DefaultKeyGenerator generates a cryptographically secure random alphanumeric string prefixed with prefix.
func DefaultKeyHasher ¶
DefaultKeyHasher computes a SHA-256 digest of the key string and formats it as Base64URL without padding.
Types ¶
type ApiKey ¶
type ApiKey struct {
// ID is the unique record identifier (UUID/cuid).
ID string `json:"id"`
// ConfigID identifies the configuration scope (default: "default").
ConfigID string `json:"configId"`
// Name is an optional human-readable descriptive label for the API Key.
Name *string `json:"name,omitempty"`
// Start contains the initial readable characters of the raw key for UI display (e.g. "sk_live_abc123").
Start string `json:"start"`
// Prefix specifies the key prefix (e.g. "sk_live_").
Prefix string `json:"prefix"`
// Key holds the stored SHA-256 hash in base64url format (or raw plaintext key if hashing is disabled).
Key string `json:"key"`
// ReferenceID identifies the owner entity (e.g., user ID or organization ID).
ReferenceID string `json:"referenceId"`
// ReferenceType specifies the type of reference owner ("user" or "organization").
ReferenceType string `json:"referenceType"`
// RefillInterval is the auto-refill interval duration in milliseconds (optional).
RefillInterval *int64 `json:"refillInterval,omitempty"`
// RefillAmount is the quota amount added during each refill interval (optional).
RefillAmount *int64 `json:"refillAmount,omitempty"`
// LastRefillAt is the timestamp when quota refill was last calculated.
LastRefillAt *time.Time `json:"lastRefillAt,omitempty"`
// Enabled indicates whether the API Key is active for authentication.
Enabled bool `json:"enabled"`
// RateLimitEnabled specifies if rate limiting per time window is active.
RateLimitEnabled bool `json:"rateLimitEnabled"`
// RateLimitTimeWindow specifies the rate limit sliding window duration in milliseconds.
RateLimitTimeWindow *int64 `json:"rateLimitTimeWindow,omitempty"`
// RateLimitMax specifies the maximum allowed requests within the rate limit window.
RateLimitMax *int64 `json:"rateLimitMax,omitempty"`
// RequestCount tracks the number of requests made within the active rate limit window.
RequestCount int64 `json:"requestCount"`
// Remaining tracks remaining overall quota usages (nil indicates unlimited usage).
Remaining *int64 `json:"remaining,omitempty"`
// LastRequest records the timestamp of the most recent API Key usage.
LastRequest *time.Time `json:"lastRequest,omitempty"`
// ExpiresAt specifies when the key expires (nil indicates no expiration).
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
// CreatedAt records when the API Key was issued.
CreatedAt time.Time `json:"createdAt"`
// UpdatedAt records when the API Key metadata was last updated.
UpdatedAt time.Time `json:"updatedAt"`
// Permissions defines granted scope permissions map (e.g. {"users": ["read", "write"]}).
Permissions map[string][]string `json:"permissions,omitempty"`
// Metadata holds arbitrary custom JSON attributes associated with the API Key.
Metadata map[string]any `json:"metadata,omitempty"`
}
ApiKey represents a secure API Key database record.
type ApiKeyCreatedPayload ¶
type ApiKeyCreatedPayload struct {
// ApiKey is the created API Key entity record.
ApiKey *ApiKey
// RawKey is the plaintext unhashed key string.
RawKey string
}
ApiKeyCreatedPayload contains details of a newly created API Key.
type ApiKeyDeletedPayload ¶
type ApiKeyDeletedPayload struct {
// KeyID is the unique identifier of the deleted API Key.
KeyID string
}
ApiKeyDeletedPayload reports an API Key deletion.
type ApiKeyExpiredPayload ¶
type ApiKeyExpiredPayload struct {
// KeyID is the unique identifier of the expired API Key.
KeyID string
}
ApiKeyExpiredPayload reports an expired API Key.
type ApiKeyUpdatedPayload ¶
type ApiKeyUpdatedPayload struct {
// ApiKey is the updated API Key record.
ApiKey *ApiKey
}
ApiKeyUpdatedPayload contains details of an updated API Key.
type ApiKeyVerifiedPayload ¶
type ApiKeyVerifiedPayload struct {
// ApiKey is the retrieved API Key record (if located).
ApiKey *ApiKey
// Valid reports whether authentication succeeded.
Valid bool
// Error reports reason for verification failure if Valid is false.
Error string
}
ApiKeyVerifiedPayload contains details of an API Key authentication check.
type Config ¶
type Config struct {
// ApiKeyHeaders defines HTTP request header names inspected for API Keys (default: ["X-API-Key"]).
ApiKeyHeaders []string
// DefaultKeyLength specifies the byte/char length of generated random keys (default: 32).
DefaultKeyLength int
// DefaultPrefix specifies default string prefix attached to issued keys (e.g. "sk_live_").
DefaultPrefix string
// KeyExpiration specifies default lifetime duration applied to new keys (optional).
KeyExpiration *time.Duration
// RateLimitEnabled enables rate limiting by default for newly created keys.
RateLimitEnabled bool
// RateLimitTimeWindow sets default rate limit sliding window duration.
RateLimitTimeWindow time.Duration
// RateLimitMax sets default max requests per sliding window.
RateLimitMax int64
// DisableKeyHashing when true stores raw plaintext keys in database (NOT recommended for production).
DisableKeyHashing bool
// EnableSessionForAPIKeys populates mock user session context during HTTP middleware processing.
EnableSessionForAPIKeys bool
// DeferUpdates when true updates request counter and usage timestamps asynchronously in goroutines.
DeferUpdates bool
// CustomKeyGenerator overrides standard crypto/rand key generator.
CustomKeyGenerator KeyGeneratorFunc
// CustomKeyHasher overrides standard SHA-256 base64url key hasher.
CustomKeyHasher KeyHasherFunc
}
Config holds operational settings for the API Key plugin.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns recommended production default settings for the API Key plugin.
type CreateApiKeyParams ¶
type CreateApiKeyParams struct {
// ConfigID identifies the configuration scope (default: "default").
ConfigID string `json:"configId,omitempty"`
// Name optionally labels the key.
Name *string `json:"name,omitempty"`
// Prefix customizes key prefix (overrides default config prefix).
Prefix string `json:"prefix,omitempty"`
// KeyLength customizes random string length (default: 32).
KeyLength int `json:"keyLength,omitempty"`
// ReferenceID specifies the owner identifier (userID or organizationID).
ReferenceID string `json:"referenceId"`
// ReferenceType specifies owner entity type ("user" or "organization", default: "user").
ReferenceType string `json:"referenceType,omitempty"`
// RefillInterval optionally configures auto refill interval in milliseconds.
RefillInterval *int64 `json:"refillInterval,omitempty"`
// RefillAmount optionally configures quota increment for each refill.
RefillAmount *int64 `json:"refillAmount,omitempty"`
// RateLimitEnabled enables rate limiting for this key.
RateLimitEnabled bool `json:"rateLimitEnabled,omitempty"`
// RateLimitTimeWindow configures rate limit window in milliseconds.
RateLimitTimeWindow *int64 `json:"rateLimitTimeWindow,omitempty"`
// RateLimitMax configures max requests per rate limit window.
RateLimitMax *int64 `json:"rateLimitMax,omitempty"`
// Remaining sets initial remaining quota (nil = unlimited).
Remaining *int64 `json:"remaining,omitempty"`
// ExpiresAt sets optional key expiration time.
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
// Permissions grants scopes map to this key.
Permissions map[string][]string `json:"permissions,omitempty"`
// Metadata adds custom JSON key-value pairs.
Metadata map[string]any `json:"metadata,omitempty"`
}
CreateApiKeyParams holds input values required to create a new API Key.
type CreateApiKeyResult ¶
type CreateApiKeyResult struct {
// ApiKey is the created entity record (containing hash or metadata).
ApiKey *ApiKey `json:"apiKey"`
// RawKey is the plaintext API Key returned ONCE upon creation.
RawKey string `json:"rawKey"`
}
CreateApiKeyResult contains the persisted API Key entity and the raw unhashed key.
type DeleteApiKeyParams ¶
type DeleteApiKeyParams struct {
// ID is the key record ID to delete.
ID string `json:"id"`
}
DeleteApiKeyParams specifies parameters for revoking an API Key.
type GetApiKeyParams ¶
type GetApiKeyParams struct {
// ID is the unique database record ID.
ID string `json:"id"`
}
GetApiKeyParams specifies input for retrieving a key by ID.
type KeyGeneratorFunc ¶
KeyGeneratorFunc is a custom function signature for generating random API Keys.
type KeyHasherFunc ¶
KeyHasherFunc is a custom function signature for computing key hashes.
type ListApiKeysParams ¶
type ListApiKeysParams struct {
// ConfigID optionally filters by configuration scope (default: "default").
ConfigID string `json:"configId,omitempty"`
// ReferenceID filters keys owned by a specific user or organization ID.
ReferenceID string `json:"referenceId"`
// Limit specifies maximum pagination count (default: 20).
Limit int `json:"limit,omitempty"`
// Offset specifies pagination starting offset.
Offset int `json:"offset,omitempty"`
}
ListApiKeysParams specifies query filters for listing API Keys.
type ListApiKeysResult ¶
type ListApiKeysResult struct {
// ApiKeys is the slice of matching API Key records.
ApiKeys []*ApiKey `json:"apiKeys"`
// Total is the total count of keys matching the reference filter.
Total int64 `json:"total"`
}
ListApiKeysResult contains paginated API Keys and total count.
type Option ¶
type Option func(*Config)
Option configures functional options for the API Key plugin.
func WithCustomKeyGenerator ¶
func WithCustomKeyGenerator(fn KeyGeneratorFunc) Option
WithCustomKeyGenerator overrides standard crypto/rand key generator implementation.
func WithCustomKeyHasher ¶
func WithCustomKeyHasher(fn KeyHasherFunc) Option
WithCustomKeyHasher overrides standard SHA-256 base64url key hasher implementation.
func WithDefaultKeyLength ¶
WithDefaultKeyLength configures the length of randomly generated keys.
func WithDefaultPrefix ¶
WithDefaultPrefix sets the default prefix string prepended to new keys (e.g. "sk_live_").
func WithDeferUpdates ¶
WithDeferUpdates enables asynchronous background updates of key counters (RequestCount, LastRequest, Remaining).
func WithDisableKeyHashing ¶
WithDisableKeyHashing toggles storing plaintext raw keys instead of SHA-256 hashes.
func WithEnableSessionForAPIKeys ¶
WithEnableSessionForAPIKeys configures whether middleware mock user session is populated upon authentication.
func WithExpiration ¶
WithExpiration sets default lifetime expiration duration for issued keys.
func WithHeaderNames ¶
WithHeaderNames customizes HTTP header names checked during HTTP middleware key extraction.
type Plugin ¶
type Plugin struct {
// contains filtered or unexported fields
}
Plugin implements API Key authentication, verification, rate limiting, and management capabilities.
func New ¶
func New(repo Repository, opts ...Option) *Plugin
New instantiates a new API Key plugin instance configured with the specified repository and options.
func (*Plugin) Authenticate ¶ added in v0.20.0
Authenticate returns a standard net/http middleware handler to authenticate API Keys from incoming HTTP request headers.
func (*Plugin) CreateKey ¶
func (p *Plugin) CreateKey(ctx context.Context, params CreateApiKeyParams) (*CreateApiKeyResult, error)
CreateKey issues and persists a new secure API Key record.
func (*Plugin) DeleteAllExpiredKeys ¶
DeleteAllExpiredKeys purges all expired API Keys from persistent storage.
func (*Plugin) DeleteKey ¶
func (p *Plugin) DeleteKey(ctx context.Context, params DeleteApiKeyParams) error
DeleteKey revokes and permanently deletes an API Key.
func (*Plugin) ListKeys ¶
func (p *Plugin) ListKeys(ctx context.Context, params ListApiKeysParams) (*ListApiKeysResult, error)
ListKeys fetches paginated API Keys belonging to a reference owner (user or organization).
func (*Plugin) VerifyKey ¶
func (p *Plugin) VerifyKey(ctx context.Context, params VerifyApiKeyParams) (*VerifyApiKeyResult, error)
VerifyKey authenticates a raw API Key string against stored records, evaluating expiration, rate limits, and quota.
type Repository ¶
type Repository interface {
// CreateApiKey persists a new API Key record in storage.
//
// Function:
// Called during API Key creation endpoint.
//
// Storage:
// Database (GORM / SQL) - Relational persistence for API Key entity.
//
// Arguments:
// - ctx: Request cancellation context.
// - apiKey: ApiKey entity containing key hash, prefix, scopes, rate limits, and owner reference.
//
// Returns:
// - error: Nil on success, or database error.
//
// Example SQL:
// INSERT INTO api_keys (id, config_id, name, prefix, key_hash, start, reference_id, enabled, rate_limit_enabled, rate_limit_time_window, rate_limit_max_requests, request_count, remaining, expires_at, created_at, updated_at)
// VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16);
CreateApiKey(ctx context.Context, apiKey *ApiKey) error
// FindApiKeyByID retrieves an API Key by its unique primary key ID.
//
// Function:
// Used during administrative API Key lookup, updating, or revocation.
//
// Storage:
// Database (GORM / SQL) - Record lookup by primary key ID.
//
// Arguments:
// - ctx: Request cancellation context.
// - id: Unique primary key record ID.
//
// Returns:
// - *ApiKey: Matching API Key entity if found.
// - error: ErrKeyNotFound if missing, or database error.
//
// Example SQL:
// SELECT id, config_id, name, prefix, key_hash, start, reference_id, enabled, rate_limit_enabled, request_count, remaining, expires_at, created_at, updated_at FROM api_keys WHERE id = $1 LIMIT 1;
FindApiKeyByID(ctx context.Context, id string) (*ApiKey, error)
// FindApiKeyByKeyHash retrieves an API Key by matching its stored SHA-256 key hash string.
//
// Function:
// Called during API Key verification on incoming HTTP requests.
//
// Storage:
// Both (Cache-Aside Strategy) - Cached in Redis/Memory (`apikey:hash:<keyHash>`) to avoid DB load on every request.
//
// Arguments:
// - ctx: Request cancellation context.
// - keyHash: Hex-encoded SHA-256 hash of the submitted API key secret.
//
// Returns:
// - *ApiKey: Matching API Key entity if found.
// - error: ErrKeyNotFound if missing, or database error.
//
// Example SQL:
// SELECT id, config_id, name, prefix, key_hash, start, reference_id, enabled, rate_limit_enabled, request_count, remaining, expires_at, created_at, updated_at FROM api_keys WHERE key_hash = $1 LIMIT 1;
//
// Example Cache (Redis):
// val, err := rdb.Get(ctx, "apikey:hash:" + keyHash).Bytes()
FindApiKeyByKeyHash(ctx context.Context, keyHash string) (*ApiKey, error)
// UpdateApiKey updates an existing API Key record's metadata, status, or quota attributes.
//
// Function:
// Called after verifying a key to update request counts, remaining quota, and last request timestamp.
//
// Storage:
// Database (GORM / SQL) - Relational record update.
//
// Arguments:
// - ctx: Request cancellation context.
// - apiKey: Modified ApiKey entity.
//
// Returns:
// - error: Nil on success, or database error.
//
// Example SQL:
// UPDATE api_keys SET request_count = $1, remaining = $2, last_request = $3, updated_at = $4 WHERE id = $5;
UpdateApiKey(ctx context.Context, apiKey *ApiKey) error
// DeleteApiKey permanently removes an API Key record by ID.
//
// Function:
// Called when an owner or admin revokes an API Key.
//
// Storage:
// Database (GORM / SQL) - Persistent record deletion.
//
// Arguments:
// - ctx: Request cancellation context.
// - id: Primary key record ID.
//
// Returns:
// - error: Nil on success, or database error.
//
// Example SQL:
// DELETE FROM api_keys WHERE id = $1;
DeleteApiKey(ctx context.Context, id string) error
// ListApiKeysByReferenceID retrieves paginated API Keys belonging to a given owner reference ID.
//
// Function:
// Used in developer settings UI to display active API Keys for a user or organization.
//
// Storage:
// Database (GORM / SQL) - Relational paginated query.
//
// Arguments:
// - ctx: Request cancellation context.
// - configID: Configuration context identifier.
// - referenceID: Owner identifier (e.g. userID or orgID).
// - limit: Max records per page.
// - offset: Pagination offset.
//
// Returns:
// - []*ApiKey: Slice of API Key records.
// - int64: Total matching record count.
// - error: Nil on success.
//
// Example SQL:
// SELECT id, config_id, name, prefix, key_hash, start, reference_id, enabled, request_count, remaining, expires_at, created_at, updated_at FROM api_keys WHERE reference_id = $1 LIMIT $2 OFFSET $3;
ListApiKeysByReferenceID(ctx context.Context, configID string, referenceID string, limit int, offset int) ([]*ApiKey, int64, error)
// DeleteExpiredApiKeys purges all keys whose expiration date is prior to current time.
//
// Function:
// Called by automated cleanup crons or maintenance routines.
//
// Storage:
// Database (GORM / SQL) - Bulk record deletion.
//
// Arguments:
// - ctx: Request cancellation context.
//
// Returns:
// - int64: Count of deleted keys.
// - error: Nil on success.
//
// Example SQL:
// DELETE FROM api_keys WHERE expires_at IS NOT NULL AND expires_at <= $1;
DeleteExpiredApiKeys(ctx context.Context) (int64, error)
// GetUserByID fetches user details for populating user identity context during authentication.
//
// Function:
// Used when auto-populating user context after verifying an API Key owned by a user.
//
// Storage:
// Database (GORM / SQL) - Relational user entity lookup.
//
// Arguments:
// - ctx: Request cancellation context.
// - userID: Target user identifier.
//
// Returns:
// - *entity.User: Matching user entity if found.
// - error: Nil if optional or missing user, or database error.
//
// Example SQL:
// SELECT id, email, name, email_verified, created_at, updated_at FROM users WHERE id = $1 LIMIT 1;
GetUserByID(ctx context.Context, userID string) (*entity.User, error)
}
Repository defines the storage contract for persisting and retrieving API Key records. Implement this interface on your custom database adapter (e.g. PostgreSQL, MySQL, SQLite, MongoDB, GORM, Redis).
Implementation Example (GORM / database/sql): ¶
type GormApiKeyRepository struct {
db *gorm.DB
}
func (r *GormApiKeyRepository) FindApiKeyByKeyHash(ctx context.Context, keyHash string) (*apikey.ApiKey, error) {
var k apikey.ApiKey
if err := r.db.WithContext(ctx).Where("key_hash = ?", keyHash).First(&k).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, apikey.ErrKeyNotFound
}
return nil, err
}
return &k, nil
}
Storage and Caching Pattern (Decorator / Cache-Aside Strategy) ¶
To achieve high-throughput, low-latency API Key verification during HTTP requests, implementations are strongly encouraged to decorate the underlying database repository with a fast in-memory or Redis caching layer.
Recommended Caching Architecture:
Write-Through / Cache-Aside on FindApiKeyByKeyHash: When `VerifyKey` computes `keyHash`, query a fast cache (e.g. Redis key `apikey:hash:<keyHash>`). If found (Cache Hit), return cached `*ApiKey` immediately. If cache miss, query persistent DB, write to cache with appropriate TTL, and return.
Invalidating Cache on UpdateApiKey / DeleteApiKey: Upon key updating or deletion, evict `apikey:hash:<keyHash>` and `apikey:id:<id>` from cache.
Asynchronous Counter Flush (DeferUpdates): When `DeferUpdates` option is enabled, usage statistics (`RequestCount`, `Remaining`, `LastRequest`) can be updated asynchronously without blocking the caller's execution.
type UpdateApiKeyParams ¶
type UpdateApiKeyParams struct {
// ID is the target key record ID.
ID string `json:"id"`
// Name optionally updates the descriptive label.
Name *string `json:"name,omitempty"`
// Enabled optionally activates or deactivates the key.
Enabled *bool `json:"enabled,omitempty"`
// RateLimitEnabled optionally toggles rate limiting.
RateLimitEnabled *bool `json:"rateLimitEnabled,omitempty"`
// RateLimitTimeWindow optionally updates rate limit sliding window in ms.
RateLimitTimeWindow *int64 `json:"rateLimitTimeWindow,omitempty"`
// RateLimitMax optionally updates max allowed requests per window.
RateLimitMax *int64 `json:"rateLimitMax,omitempty"`
// Remaining optionally sets total usage quota remaining.
Remaining *int64 `json:"remaining,omitempty"`
// RefillInterval optionally updates quota refill interval in ms.
RefillInterval *int64 `json:"refillInterval,omitempty"`
// RefillAmount optionally updates quota refill increment.
RefillAmount *int64 `json:"refillAmount,omitempty"`
// ExpiresAt optionally updates key expiration timestamp.
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
// Permissions optionally replaces granted scopes map.
Permissions map[string][]string `json:"permissions,omitempty"`
// Metadata optionally replaces JSON metadata map.
Metadata map[string]any `json:"metadata,omitempty"`
}
UpdateApiKeyParams specifies parameters for updating an existing key's parameters.
type VerifyApiKeyParams ¶
type VerifyApiKeyParams struct {
// Key is the raw unhashed API Key string extracted from request header/query.
Key string `json:"key"`
// RequiredPermissions optionally specifies required scopes to validate.
RequiredPermissions map[string][]string `json:"requiredPermissions,omitempty"`
}
VerifyApiKeyParams holds parameters to authenticate an incoming request's API Key.
type VerifyApiKeyResult ¶
type VerifyApiKeyResult struct {
// Valid indicates whether the API key is active, unexpired, and within limits.
Valid bool `json:"valid"`
// ApiKey is the retrieved API Key record.
ApiKey *ApiKey `json:"apiKey,omitempty"`
// User is the associated user entity (if ReferenceType is "user" and user exists).
User *entity.User `json:"user,omitempty"`
// Permissions returns the granted permissions map.
Permissions map[string][]string `json:"permissions,omitempty"`
// Error contains a human-readable failure description if Valid is false.
Error string `json:"error,omitempty"`
}
VerifyApiKeyResult contains the outcome of an API Key authentication check.