Repository navigation
Description
Description
Implement a Redis Sentinel-backed storage backend for the embedded authorization server that satisfies the existing Storage interface. This enables horizontal scaling of ToolHive auth servers by allowing multiple instances to share authentication state via Redis, supporting high-availability deployments with automatic failover.
This is Phase 1 of the Redis Storage feature, focusing on core implementation with unit tests using miniredis for mocking.
Context
The current MemoryStorage implementation stores all OAuth2 tokens, authorization codes, user data, and pending authorizations in memory. This prevents horizontal scaling and causes state loss on restarts. This task adds RedisStorage as an alternative backend that implements the same Storage interface, enabling distributed deployments.
Parent Issue: https://github.com/stacklok/stacklok-epics/issues/197
Dependencies: None (this is the first task in the epic)
Blocks: TASK-002 (Integration Testing), TASK-003 (Documentation & Operator CRD Updates)
Acceptance Criteria
-
RedisStoragestruct implements all methods of theStorageinterface (verified by compile-time check) - Configuration types support Sentinel-only deployment with ACL user authentication
- Key generation uses hash tags for multi-tenancy (
thv:auth:{ns}:{name}:<type>:<id>) - Unit tests achieve >80% coverage using miniredis
- Connection health checking implemented via Redis PING
-
task lintpasses without errors -
task testpasses without errors - New dependencies added to
go.mod:github.com/redis/go-redis/v9andgithub.com/alicebob/miniredis/v2
Technical Approach
Recommended Implementation
Follow the patterns established by MemoryStorage in pkg/authserver/storage/memory.go. The Redis implementation should:
- Use
redis.UniversalClientfrom go-redis to support Sentinel failover - Serialize
fosite.Requesterand other types to JSON for storage - Use Redis TTL (SETEX/PSETEX) for automatic expiration instead of background cleanup
- Implement secondary indexes for request ID lookups required by RFC 7009 token revocation
- Use Lua scripts for atomic operations that span multiple keys
Patterns & Frameworks
- go-redis/v9: Official Redis client library with built-in Sentinel support and connection pooling
- miniredis/v2: In-memory Redis mock for unit testing (no external Redis required)
- JSON serialization: Marshal/unmarshal all stored types to JSON (consistent with existing patterns)
- Interface compliance: Use compile-time check pattern from
memory.go:1099-1104 - Defensive copies: Follow pattern from
memory.go:700-712when returning data - Error wrapping: Wrap errors with fosite errors as shown in
memory.go:332-333
Code Pointers
pkg/authserver/storage/types.go-Storageinterface definition (all methods to implement)pkg/authserver/storage/memory.go- Reference implementation to followpkg/authserver/storage/config.go- AddTypeRedisconstant and Redis configuration typespkg/authserver/storage/memory_test.go- Test patterns to follow (mock types, table-driven tests)docs/proposals/THV-0035-auth-server-redis-storage.md- Full RFC with detailed design
Component Interfaces
RedisConfig (Runtime Configuration)
// pkg/authserver/storage/redis.go
// RedisConfig holds Redis connection configuration for runtime use.
type RedisConfig struct {
// SentinelConfig is required - Sentinel-only deployment
SentinelConfig *SentinelConfig
// ACLUserConfig is required - ACL user authentication only
ACLUserConfig *ACLUserConfig
// KeyPrefix for multi-tenancy: "thv:auth:{ns}:{name}:"
KeyPrefix string
// Timeouts (defaults: Dial=5s, Read=3s, Write=3s)
DialTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
}
type SentinelConfig struct {
MasterName string
SentinelAddrs []string
DB int
}
type ACLUserConfig struct {
Username string
Password string
}RedisRunConfig (Serializable Configuration)
// pkg/authserver/storage/config.go
type RedisRunConfig struct {
DeploymentMode string `json:"deploymentMode" yaml:"deploymentMode"` // Must be "sentinel"
SentinelConfig *SentinelRunConfig `json:"sentinelConfig,omitempty" yaml:"sentinelConfig,omitempty"`
AuthType string `json:"authType" yaml:"authType"` // Must be "aclUser"
ACLUserConfig *ACLUserRunConfig `json:"aclUserConfig,omitempty" yaml:"aclUserConfig,omitempty"`
KeyPrefix string `json:"keyPrefix" yaml:"keyPrefix"`
DialTimeout string `json:"dialTimeout,omitempty" yaml:"dialTimeout,omitempty"`
ReadTimeout string `json:"readTimeout,omitempty" yaml:"readTimeout,omitempty"`
WriteTimeout string `json:"writeTimeout,omitempty" yaml:"writeTimeout,omitempty"`
}
type SentinelRunConfig struct {
MasterName string `json:"masterName" yaml:"masterName"`
SentinelAddrs []string `json:"sentinelAddrs" yaml:"sentinelAddrs"`
DB int `json:"db,omitempty" yaml:"db,omitempty"`
}
type ACLUserRunConfig struct {
UsernameEnvVar string `json:"usernameEnvVar" yaml:"usernameEnvVar"`
PasswordEnvVar string `json:"passwordEnvVar" yaml:"passwordEnvVar"`
}RedisStorage Factory
// pkg/authserver/storage/redis.go
type RedisStorage struct {
client redis.UniversalClient
config RedisConfig
}
// NewRedisStorage creates Redis-backed storage with Sentinel failover support.
// Returns error if configuration validation fails or connection cannot be established.
func NewRedisStorage(ctx context.Context, cfg RedisConfig) (*RedisStorage, error)
// Close closes the Redis client connection.
func (s *RedisStorage) Close() error
// Ping checks Redis connectivity (health check).
func (s *RedisStorage) Ping(ctx context.Context) errorKey Generation Utilities
// pkg/authserver/storage/redis_keys.go
// DeriveKeyPrefix creates the key prefix from server namespace and name.
func DeriveKeyPrefix(namespace, name string) string {
return fmt.Sprintf("thv:auth:{%s}:{%s}:", namespace, name)
}
// Key types as constants for type safety
const (
KeyTypeAccess = "access"
KeyTypeRefresh = "refresh"
KeyTypeAuthCode = "authcode"
KeyTypePKCE = "pkce"
KeyTypeClient = "client"
KeyTypeUser = "user"
KeyTypeProvider = "provider"
KeyTypeUpstream = "upstream"
KeyTypePending = "pending"
KeyTypeInvalidated = "invalidated"
KeyTypeJWT = "jwt"
KeyTypeReqIDAccess = "reqid:access"
KeyTypeReqIDRefresh = "reqid:refresh"
)Serializable Requester Wrapper
// pkg/authserver/storage/redis.go
// storedRequest is a serializable wrapper for fosite.Requester
type storedRequest struct {
ClientID string `json:"client_id"`
RequestedAt time.Time `json:"requested_at"`
Scopes []string `json:"scopes"`
GrantedScopes []string `json:"granted_scopes"`
Form url.Values `json:"form"`
Session json.RawMessage `json:"session"`
RequestID string `json:"request_id"`
ExpiresAt time.Time `json:"expires_at"`
}Testing Strategy
Unit Tests (using miniredis)
- Test
NewRedisStoragewith valid and invalid configurations - Test connection health check (
Ping) - Test all
Storageinterface methods:-
RegisterClient/GetClient/ClientAssertionJWTValid/SetClientAssertionJWT -
CreateAuthorizeCodeSession/GetAuthorizeCodeSession/InvalidateAuthorizeCodeSession -
CreateAccessTokenSession/GetAccessTokenSession/DeleteAccessTokenSession -
CreateRefreshTokenSession/GetRefreshTokenSession/DeleteRefreshTokenSession -
RotateRefreshToken -
RevokeAccessToken/RevokeRefreshToken/RevokeRefreshTokenMaybeGracePeriod -
CreatePKCERequestSession/GetPKCERequestSession/DeletePKCERequestSession -
StoreUpstreamTokens/GetUpstreamTokens/DeleteUpstreamTokens -
StorePendingAuthorization/LoadPendingAuthorization/DeletePendingAuthorization -
CreateUser/GetUser/DeleteUser -
CreateProviderIdentity/GetProviderIdentity/UpdateProviderIdentityLastUsed -
GetUserProviderIdentities
-
- Test key generation utilities
- Test JSON serialization/deserialization of
storedRequest - Test TTL handling (tokens expire correctly)
- Test error handling (Redis connection errors, not found, etc.)
Edge Cases
- Empty or nil configuration values
- Invalid Sentinel addresses
- Connection failures during operations
- Expired tokens return appropriate errors
- Concurrent access patterns (similar to
memory_test.goconcurrent tests)
Out of Scope
- Integration tests with real Redis (covered in TASK-002)
- Operator CRD types (covered in TASK-003)
- Runner integration to create storage from config (covered in TASK-003)
- TLS/mTLS configuration for Redis connections (future enhancement)
- Custom connection pool configuration (use go-redis defaults)
- Redis persistence (RDB/AOF) - this implementation is memory-only
References
- Epic: https://github.com/stacklok/stacklok-epics/issues/197
- RFC Design Document:
docs/proposals/THV-0035-auth-server-redis-storage.md - Existing Storage Interface:
pkg/authserver/storage/types.go - Reference Implementation:
pkg/authserver/storage/memory.go - go-redis Documentation: https://redis.uptrace.dev/
- miniredis Documentation: https://github.com/alicebob/miniredis
Activity
Add Redis Sentinel storage backend for auth server
Add Redis Sentinel storage backend for auth server
[-]Implement Redis Storage: Core Implementation (Phase 1)[/-][+]Auth Server: Implement Redis Storage: Core Implementation (Phase 1)[/+]Add Redis Sentinel storage backend for auth server
Add Redis Sentinel storage backend for auth server
Add Operator CRD Types for Auth Server Redis Storage (#3793)
Add operator controller and runner integration for Redis storage (#3823)