Skip to content

Auth Server: Add Redis Storage Integration Tests with Testcontainers (Phase 2) #3629

Closed

Description

@tgrunnagle

Description

Add integration tests for the Redis storage implementation that run against real Redis Sentinel instances using testcontainers. This ensures the RedisStorage implementation works correctly with actual Redis behavior, including Sentinel failover, ACL authentication, and proper TTL handling that cannot be fully tested with the miniredis mock.

Context

TASK-001 implemented the RedisStorage struct with comprehensive unit tests using miniredis. While miniredis is excellent for fast unit testing, it does not fully replicate Redis Sentinel behavior, ACL user authentication, or real network conditions. Integration tests against real Redis are essential to validate the implementation works correctly in production-like environments.

Parent Issue: https://github.com/stacklok/stacklok-epics/issues/197
Dependencies: #3628 (Redis Storage: Core Implementation - Phase 1)
Blocks: TASK-003 (Documentation & Operator CRD Updates - Phases 3+4)

Acceptance Criteria

  • Integration tests run against real Redis Sentinel setup via testcontainers
  • Tests cover all Storage interface methods with real Redis
  • Tests verify Sentinel failover behavior (primary switchover)
  • Tests verify ACL user authentication
  • Tests verify TTL-based expiration with real Redis
  • Tests are tagged appropriately for CI (e.g., //go:build integration)
  • task test-all passes (or tests are skipped when testcontainers/Docker unavailable)
  • Code follows existing integration test patterns in test/integration/authserver/

Technical Approach

Recommended Implementation

Create a testcontainers-based setup that spins up a Redis Sentinel cluster (1 primary + 2 replicas + 3 sentinels) and runs the full Storage interface test suite against it. Follow the existing integration test patterns in test/integration/authserver/ and pkg/authserver/storage/memory_test.go.

Key considerations:

  1. Use testcontainers-go to manage Redis containers
  2. Configure Redis Sentinel with ACL user authentication
  3. Reuse test helpers and patterns from memory_test.go (mock types, table-driven tests)
  4. Add build tags to separate from unit tests
  5. Handle Docker availability gracefully (skip tests when unavailable)

Patterns & Frameworks

  • testcontainers-go: Container management for integration tests (github.com/testcontainers/testcontainers-go)
  • Redis Sentinel module: Use testcontainers Redis module or custom container setup for Sentinel
  • Build tags: Use //go:build integration to separate from unit tests
  • Table-driven tests: Follow patterns from memory_test.go for comprehensive coverage
  • Test fixtures: Follow patterns from test/integration/authserver/helpers/ for reusable test setup

Code Pointers

  • pkg/authserver/storage/memory_test.go - Test patterns, mock types (mockSession, mockClient, mockRequester), and table-driven test structure to follow
  • pkg/authserver/storage/types.go - Storage interface definition (all methods to test)
  • pkg/authserver/storage/redis.go - Redis storage implementation to test (created in TASK-001)
  • test/integration/authserver/helpers/authserver.go - Integration test helper patterns to follow
  • test/integration/authserver/authserver_integration_test.go - Example integration test structure
  • docs/proposals/THV-0035-auth-server-redis-storage.md - RFC with testing strategy

Component Interfaces

Test Container Setup

// pkg/authserver/storage/redis_integration_test.go

//go:build integration

package storage_test

import (
    "context"
    "testing"
    "time"

    "github.com/testcontainers/testcontainers-go"
    // ... other imports
)

// RedisSentinelCluster represents a test Redis Sentinel cluster.
type RedisSentinelCluster struct {
    PrimaryContainer   testcontainers.Container
    Replica1Container  testcontainers.Container
    Replica2Container  testcontainers.Container
    Sentinel1Container testcontainers.Container
    Sentinel2Container testcontainers.Container
    Sentinel3Container testcontainers.Container

    SentinelAddrs []string
    MasterName    string
    Username      string
    Password      string
}

// NewRedisSentinelCluster creates a Redis Sentinel cluster for testing.
// Returns a cluster with 1 primary + 2 replicas + 3 sentinels.
func NewRedisSentinelCluster(ctx context.Context, t *testing.T) *RedisSentinelCluster

// Close terminates all containers.
func (c *RedisSentinelCluster) Close(ctx context.Context) error

// TriggerFailover forces a Sentinel failover for testing.
func (c *RedisSentinelCluster) TriggerFailover(ctx context.Context) error

Storage Test Helper

// withRedisStorage creates a RedisStorage for testing and handles cleanup.
func withRedisStorage(t *testing.T, cluster *RedisSentinelCluster, fn func(context.Context, *RedisStorage)) {
    t.Helper()
    ctx := context.Background()

    cfg := RedisConfig{
        SentinelConfig: &SentinelConfig{
            MasterName:    cluster.MasterName,
            SentinelAddrs: cluster.SentinelAddrs,
            DB:            0,
        },
        ACLUserConfig: &ACLUserConfig{
            Username: cluster.Username,
            Password: cluster.Password,
        },
        KeyPrefix: DeriveKeyPrefix("test-ns", "test-server"),
    }

    storage, err := NewRedisStorage(ctx, cfg)
    require.NoError(t, err)
    defer storage.Close()

    fn(ctx, storage)
}

Testing Strategy

Integration Tests (using testcontainers)

Storage Interface Methods:

  • RegisterClient / GetClient - Client registration and retrieval
  • ClientAssertionJWTValid / SetClientAssertionJWT - JWT assertion tracking
  • CreateAuthorizeCodeSession / GetAuthorizeCodeSession / InvalidateAuthorizeCodeSession - Auth code flow
  • CreateAccessTokenSession / GetAccessTokenSession / DeleteAccessTokenSession - Access tokens
  • CreateRefreshTokenSession / GetRefreshTokenSession / DeleteRefreshTokenSession - Refresh tokens
  • RotateRefreshToken - Token rotation
  • RevokeAccessToken / RevokeRefreshToken / RevokeRefreshTokenMaybeGracePeriod - Token revocation (RFC 7009)
  • CreatePKCERequestSession / GetPKCERequestSession / DeletePKCERequestSession - PKCE flow
  • StoreUpstreamTokens / GetUpstreamTokens / DeleteUpstreamTokens - Upstream IDP tokens
  • StorePendingAuthorization / LoadPendingAuthorization / DeletePendingAuthorization - Pending auth
  • CreateUser / GetUser / DeleteUser - User management
  • CreateProviderIdentity / GetProviderIdentity / UpdateProviderIdentityLastUsed / GetUserProviderIdentities - Provider identities

Sentinel-Specific Tests:

  • Test connection via Sentinel addresses (not direct Redis)
  • Test automatic reconnection after primary failover
  • Test operation continuity during failover
  • Test quorum-based failover detection

ACL Authentication Tests:

  • Test successful authentication with valid ACL credentials
  • Test authentication failure with invalid username
  • Test authentication failure with invalid password
  • Test key pattern restrictions (operations on thv:auth:* succeed, others fail)

TTL and Expiration Tests:

  • Test token expiration via Redis TTL (not cleanup goroutine)
  • Test that expired tokens return appropriate errors
  • Verify TTL values match session expiration times

Concurrent Access Tests:

  • Test concurrent writes to different keys
  • Test concurrent reads and writes
  • Test concurrent client registration and lookup

Edge Cases

  • Connection timeout handling
  • Network partition recovery
  • Redis restart during operation
  • Large payload serialization/deserialization
  • Unicode characters in user IDs and provider subjects

Out of Scope

  • E2E tests for the full auth server with Redis (covered in future work)
  • Operator/CRD integration tests (covered in TASK-003 and Phase 5)
  • Performance benchmarks (future enhancement)
  • TLS/mTLS testing for Redis connections (future enhancement per RFC)
  • Multi-tenant isolation testing across different key prefixes (covered by unit tests)

References

Activity

  1. added
    enhancement
    go
    on Feb 5, 2026
  2. self-assigned this
    on Feb 5, 2026
  3. changed the title [-]Add Redis Storage Integration Tests with Testcontainers (Phase 2)[/-] [+]Auth Server: Add Redis Storage Integration Tests with Testcontainers (Phase 2)[/+] on Feb 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

applied-aiauthenticationenhancementgo

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions