cache

package
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package cache provides a generic, thread-safe, two-tier TTL cache for validating opaque secrets (API keys, tokens) against a loaded set, using a caller-supplied match function so the package stays dependency-free.

The cache keeps two layers of state:

  1. A per-secret validation result (the entries map) so repeated checks for the same raw secret are fast and skip the loader and the match scan.
  2. The full set of loadable items (the loaded slice), refreshed periodically, so validation can run entirely in memory.

Valid results are cached for a longer TTL while invalid results are cached for a short TTL, which bounds the memory an enumeration attack can consume without holding bad guesses for long. Raw secrets are never stored: they are hashed with SHA-256 before being used as map keys. The package imports only the standard library; any comparison cost (for example a password-hash comparison) lives entirely in the caller-supplied match function.

Index

Constants

View Source
const (
	DefaultTTL        = 60 * time.Second // TTL for valid entries
	DefaultInvalidTTL = 5 * time.Second  // Short TTL for invalid entries (DoS protection)
	DefaultMaxEntries = 10000            // Prevent memory bloat from enumeration attacks
)

Cache configuration defaults.

DefaultTTL defines how long a successful (valid) lookup is kept in the in-memory cache before it must be revalidated.

DefaultInvalidTTL defines how long an invalid lookup is cached. This short TTL helps protect against brute-force and enumeration attacks by temporarily remembering bad secrets but not holding them for long.

DefaultMaxEntries is a safeguard to prevent the cache from growing without bounds in the face of many unique secrets (for example, an attack).

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache[T any] struct {
	// contains filtered or unexported fields
}

Cache provides thread-safe in-memory caching for opaque-secret validation.

It has two main responsibilities:

  1. Cache per-secret validation results in the entries map so that repeated checks for the same raw secret are fast and avoid reloading or re-running the match function.
  2. Cache the full loaded set in the loaded slice, refreshing it periodically, so that validation can run entirely in memory.

Concurrency:

  • All state is guarded by the mu RWMutex.
  • Read-heavy operations use RLock for fast-path cache hits, while write operations acquire the full Lock when modifying maps/slices.

Dependencies:

  • loader: supplies the full set of items to validate against when the loaded set is stale or missing.
  • match: reports whether a raw secret matches a loaded item; all comparison cost lives here, keeping the cache dependency-free.
  • now: injectable clock function used for TTL and age calculations; defaults to time.Now but can be overridden in tests.

The zero value is not safe for direct use; New must be used to initialize the maps and defaults.

func New

func New[T any](l Loader[T], match func(raw string, item T) bool, opts ...Option) *Cache[T]

New constructs and returns a fully initialized Cache.

Inputs:

  • l: the Loader used to load the full set of items to validate against when the loaded set must be refreshed.
  • match: a function reporting whether a raw secret matches a loaded item. All comparison cost (for example a password-hash comparison) lives here, so the package itself stays dependency-free.
  • opts: optional functional options (for example WithTTL, WithInvalidTTL, WithMaxEntries, WithNowFunc) that customize the cache's behavior.

Output:

  • *Cache[T]: a ready-to-use cache instance with internal maps allocated and defaults applied.

The returned cache does not preload anything; the first validation request triggers a call to the loader.

func (*Cache[T]) Invalidate

func (c *Cache[T]) Invalidate()

Invalidate clears all cached entries and forces a fresh load on the next validation call.

Use this method when you know the set of valid secrets has changed materially (for example, after a key rotation, revocation, or bulk update) and you want subsequent validations to reflect those changes immediately.

Behavior:

  • Clears per-secret validation results in entries.
  • Discards the loaded set.
  • Resets the loaded timestamp to the zero time, causing the next validation to reload from the loader.

func (*Cache[T]) InvalidateKey

func (c *Cache[T]) InvalidateKey(rawKey string)

InvalidateKey removes a specific raw secret from the validation cache.

Input:

  • rawKey: the plain-text secret whose cached validation result should be discarded.

Behavior:

  • Next time Validate is called with this secret, the cache will perform a full validation flow (including the match scan) instead of using any previously stored result.

func (*Cache[T]) Stats

func (c *Cache[T]) Stats() Stats

Stats returns a point-in-time snapshot of the cache's internal metrics.

Output:

  • Stats: a value populated with counts and ages computed at the moment Stats is called.

Concurrency:

  • Uses a read lock so that stats can be gathered concurrently with in-flight validation operations.

func (*Cache[T]) Validate

func (c *Cache[T]) Validate(ctx context.Context, rawKey string) (*T, error)

Validate checks whether the provided raw secret is currently recognized as valid according to the cached state (and, if necessary, the loader).

Inputs:

  • ctx: context for cancellation and deadlines passed down to the loader when refreshing the loaded set.
  • rawKey: the plain-text secret provided by the caller (for example, from an HTTP header).

Outputs:

  • *T: the matching item if the secret is valid; nil if the secret is invalid or not found.
  • error: non-nil only if there was an issue loading the set from the loader. A nil error with a nil *T indicates a clean "not found" result.

Behavior:

  • Fast path: first attempts a read-only lookup in the entries map. If a non-expired entry is found, it is returned immediately.
  • Slow path: on cache miss or expired entry, acquires a write lock, refreshes the loaded set if needed, runs the match function against each loaded item, caches the result, and returns it.

type Loader

type Loader[T any] interface {
	LoadAll(ctx context.Context) ([]T, error)
}

Loader supplies the full set of items the cache validates against.

LoadAll returns every item that should be considered a valid match target. The loader is responsible for any filtering semantics (for example, omitting disabled or expired items); the cache treats whatever is returned as the authoritative set. It is called on the slow path when the loaded set is missing or stale.

type Option

type Option func(*config)

Option is a functional option used to configure a Cache during construction.

Each Option receives a pointer to the internal config and may mutate its fields (TTLs, max entries, clock function) before the cache is built. This pattern avoids constructors with many positional parameters.

func WithInvalidTTL

func WithInvalidTTL(ttl time.Duration) Option

WithInvalidTTL overrides the default TTL used for invalid cache entries.

Input:

  • ttl: duration to use for future invalid entries. A short value limits how long the cache remembers bad secrets, which bounds enumeration-attack memory while still absorbing repeated bad guesses.

Behavior:

  • Does not affect existing entries, only entries created after the cache is constructed.

func WithMaxEntries

func WithMaxEntries(n int) Option

WithMaxEntries overrides the default maximum number of cached validation entries.

Input:

  • n: the maximum number of entries to retain before the cache evicts expired and, if necessary, the oldest entries to make room.

Behavior:

  • Bounds the memory the entries map can consume in the face of many unique secrets.

func WithNowFunc

func WithNowFunc(fn func() time.Time) Option

WithNowFunc injects a custom clock function into the cache.

This is primarily intended for tests, where deterministic control over time is important. In production, the default is time.Now.

Input:

  • fn: a function returning the current time to use for TTL comparisons and age calculations.

func WithTTL

func WithTTL(ttl time.Duration) Option

WithTTL overrides the default TTL used for valid cache entries.

Input:

  • ttl: duration to use for future valid entries.

Behavior:

  • Does not affect existing entries, only entries created after the cache is constructed.
  • Can be chained with other Option values in New.

type Stats

type Stats struct {
	EntryCount     int           // Number of cached validation results
	LoadedCount    int           // Number of loaded items
	LoadedAge      time.Duration // Age of the loaded set
	OldestEntry    time.Duration // Age of the oldest cache entry
	ValidEntries   int           // Count of valid (matched) entries
	InvalidEntries int           // Count of invalid (unmatched) entries
}

Stats holds a snapshot of the current cache state that can be used for debugging, observability, or health checks.

Fields:

  • EntryCount: total number of per-secret validation entries currently in the cache (both valid and invalid).
  • LoadedCount: number of items currently loaded in memory.
  • LoadedAge: how long ago the loaded set was last refreshed.
  • OldestEntry: age of the oldest entry; zero if there are no entries.
  • ValidEntries: number of entries marked as valid.
  • InvalidEntries: number of entries marked as invalid.

This struct is read-only from the caller's perspective and is always returned as a value, so callers cannot mutate the internal cache by modifying it.

Jump to

Keyboard shortcuts

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