feat: authsession service

This commit is contained in:
Ilia Denisov
2026-04-08 16:23:07 +02:00
committed by GitHub
parent 28f04916af
commit 86a68ed9d0
174 changed files with 31732 additions and 112 deletions
@@ -0,0 +1,169 @@
// Package configprovider implements ports.ConfigProvider with Redis-backed
// dynamic auth/session configuration.
package configprovider
import (
"context"
"crypto/tls"
"errors"
"fmt"
"strconv"
"strings"
"time"
"galaxy/authsession/internal/ports"
"github.com/redis/go-redis/v9"
)
// Config configures one Redis-backed config provider instance.
type Config struct {
// Addr is the Redis network address in host:port form.
Addr string
// Username is the optional Redis ACL username.
Username string
// Password is the optional Redis ACL password.
Password string
// DB is the Redis logical database index.
DB int
// TLSEnabled enables TLS with a conservative minimum protocol version.
TLSEnabled bool
// SessionLimitKey identifies the single Redis string key that stores the
// active-session-limit configuration value.
SessionLimitKey string
// OperationTimeout bounds each Redis round trip performed by the adapter.
OperationTimeout time.Duration
}
// Store reads dynamic auth/session configuration from Redis.
type Store struct {
client *redis.Client
sessionLimitKey string
operationTimeout time.Duration
}
// New constructs a Redis-backed config provider from cfg.
func New(cfg Config) (*Store, error) {
switch {
case strings.TrimSpace(cfg.Addr) == "":
return nil, errors.New("new redis config provider: redis addr must not be empty")
case cfg.DB < 0:
return nil, errors.New("new redis config provider: redis db must not be negative")
case strings.TrimSpace(cfg.SessionLimitKey) == "":
return nil, errors.New("new redis config provider: session limit key must not be empty")
case cfg.OperationTimeout <= 0:
return nil, errors.New("new redis config provider: operation timeout must be positive")
}
options := &redis.Options{
Addr: cfg.Addr,
Username: cfg.Username,
Password: cfg.Password,
DB: cfg.DB,
Protocol: 2,
DisableIdentity: true,
}
if cfg.TLSEnabled {
options.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
}
return &Store{
client: redis.NewClient(options),
sessionLimitKey: cfg.SessionLimitKey,
operationTimeout: cfg.OperationTimeout,
}, nil
}
// Close releases the underlying Redis client resources.
func (s *Store) Close() error {
if s == nil || s.client == nil {
return nil
}
return s.client.Close()
}
// Ping verifies that the configured Redis backend is reachable within the
// adapter operation timeout budget.
func (s *Store) Ping(ctx context.Context) error {
operationCtx, cancel, err := s.operationContext(ctx, "ping redis config provider")
if err != nil {
return err
}
defer cancel()
if err := s.client.Ping(operationCtx).Err(); err != nil {
return fmt.Errorf("ping redis config provider: %w", err)
}
return nil
}
// LoadSessionLimit returns the current active-session-limit configuration.
// Missing or invalid Redis values are treated as “limit absent” by policy.
func (s *Store) LoadSessionLimit(ctx context.Context) (ports.SessionLimitConfig, error) {
operationCtx, cancel, err := s.operationContext(ctx, "load session limit from redis")
if err != nil {
return ports.SessionLimitConfig{}, err
}
defer cancel()
value, err := s.client.Get(operationCtx, s.sessionLimitKey).Result()
switch {
case errors.Is(err, redis.Nil):
return ports.SessionLimitConfig{}, nil
case err != nil:
return ports.SessionLimitConfig{}, fmt.Errorf("load session limit from redis: %w", err)
}
config, valid := parseSessionLimitConfig(value)
if !valid {
return ports.SessionLimitConfig{}, nil
}
if err := config.Validate(); err != nil {
return ports.SessionLimitConfig{}, nil
}
return config, nil
}
func (s *Store) operationContext(ctx context.Context, operation string) (context.Context, context.CancelFunc, error) {
if s == nil || s.client == nil {
return nil, nil, fmt.Errorf("%s: nil store", operation)
}
if ctx == nil {
return nil, nil, fmt.Errorf("%s: nil context", operation)
}
operationCtx, cancel := context.WithTimeout(ctx, s.operationTimeout)
return operationCtx, cancel, nil
}
func parseSessionLimitConfig(raw string) (ports.SessionLimitConfig, bool) {
if strings.TrimSpace(raw) == "" || strings.TrimSpace(raw) != raw {
return ports.SessionLimitConfig{}, false
}
for _, symbol := range raw {
if symbol < '0' || symbol > '9' {
return ports.SessionLimitConfig{}, false
}
}
parsed, err := strconv.ParseInt(raw, 10, strconv.IntSize)
if err != nil || parsed <= 0 {
return ports.SessionLimitConfig{}, false
}
limit := int(parsed)
return ports.SessionLimitConfig{
ActiveSessionLimit: &limit,
}, true
}
var _ ports.ConfigProvider = (*Store)(nil)
@@ -0,0 +1,283 @@
package configprovider
import (
"context"
"strconv"
"testing"
"time"
"galaxy/authsession/internal/adapters/contracttest"
"galaxy/authsession/internal/ports"
"github.com/alicebob/miniredis/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestStoreContract(t *testing.T) {
t.Parallel()
contracttest.RunConfigProviderContractTests(t, func(t *testing.T) contracttest.ConfigProviderHarness {
t.Helper()
server := miniredis.RunT(t)
store := newTestStore(t, server, Config{})
return contracttest.ConfigProviderHarness{
Provider: store,
SeedDisabled: func(t *testing.T) {
t.Helper()
server.Del(store.sessionLimitKey)
},
SeedLimit: func(t *testing.T, limit int) {
t.Helper()
server.Set(store.sessionLimitKey, strconv.Itoa(limit))
},
}
})
}
func TestNew(t *testing.T) {
t.Parallel()
server := miniredis.RunT(t)
tests := []struct {
name string
cfg Config
wantErr string
}{
{
name: "valid config",
cfg: Config{
Addr: server.Addr(),
DB: 2,
SessionLimitKey: "authsession:config:active-session-limit",
OperationTimeout: 250 * time.Millisecond,
},
},
{
name: "empty addr",
cfg: Config{
SessionLimitKey: "authsession:config:active-session-limit",
OperationTimeout: 250 * time.Millisecond,
},
wantErr: "redis addr must not be empty",
},
{
name: "negative db",
cfg: Config{
Addr: server.Addr(),
DB: -1,
SessionLimitKey: "authsession:config:active-session-limit",
OperationTimeout: 250 * time.Millisecond,
},
wantErr: "redis db must not be negative",
},
{
name: "empty session limit key",
cfg: Config{
Addr: server.Addr(),
OperationTimeout: 250 * time.Millisecond,
},
wantErr: "session limit key must not be empty",
},
{
name: "non positive timeout",
cfg: Config{
Addr: server.Addr(),
SessionLimitKey: "authsession:config:active-session-limit",
},
wantErr: "operation timeout must be positive",
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
store, err := New(tt.cfg)
if tt.wantErr != "" {
require.Error(t, err)
assert.ErrorContains(t, err, tt.wantErr)
return
}
require.NoError(t, err)
t.Cleanup(func() {
assert.NoError(t, store.Close())
})
})
}
}
func TestStorePing(t *testing.T) {
t.Parallel()
server := miniredis.RunT(t)
store := newTestStore(t, server, Config{})
require.NoError(t, store.Ping(context.Background()))
}
func TestStoreLoadSessionLimit(t *testing.T) {
t.Parallel()
tests := []struct {
name string
seed func(*testing.T, *miniredis.Miniredis, *Store)
wantConfig ports.SessionLimitConfig
}{
{
name: "missing key means disabled",
wantConfig: ports.SessionLimitConfig{},
},
{
name: "valid positive integer",
seed: func(t *testing.T, server *miniredis.Miniredis, store *Store) {
t.Helper()
server.Set(store.sessionLimitKey, "5")
},
wantConfig: configWithLimit(5),
},
{
name: "empty string is invalid and disabled",
seed: func(t *testing.T, server *miniredis.Miniredis, store *Store) {
t.Helper()
server.Set(store.sessionLimitKey, "")
},
wantConfig: ports.SessionLimitConfig{},
},
{
name: "whitespace only is invalid and disabled",
seed: func(t *testing.T, server *miniredis.Miniredis, store *Store) {
t.Helper()
server.Set(store.sessionLimitKey, " ")
},
wantConfig: ports.SessionLimitConfig{},
},
{
name: "whitespace padded integer is invalid and disabled",
seed: func(t *testing.T, server *miniredis.Miniredis, store *Store) {
t.Helper()
server.Set(store.sessionLimitKey, " 5 ")
},
wantConfig: ports.SessionLimitConfig{},
},
{
name: "non integer text is invalid and disabled",
seed: func(t *testing.T, server *miniredis.Miniredis, store *Store) {
t.Helper()
server.Set(store.sessionLimitKey, "five")
},
wantConfig: ports.SessionLimitConfig{},
},
{
name: "zero is invalid and disabled",
seed: func(t *testing.T, server *miniredis.Miniredis, store *Store) {
t.Helper()
server.Set(store.sessionLimitKey, "0")
},
wantConfig: ports.SessionLimitConfig{},
},
{
name: "negative integer is invalid and disabled",
seed: func(t *testing.T, server *miniredis.Miniredis, store *Store) {
t.Helper()
server.Set(store.sessionLimitKey, "-3")
},
wantConfig: ports.SessionLimitConfig{},
},
{
name: "overflow is invalid and disabled",
seed: func(t *testing.T, server *miniredis.Miniredis, store *Store) {
t.Helper()
server.Set(store.sessionLimitKey, "999999999999999999999999999999")
},
wantConfig: ports.SessionLimitConfig{},
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
server := miniredis.RunT(t)
store := newTestStore(t, server, Config{})
if tt.seed != nil {
tt.seed(t, server, store)
}
got, err := store.LoadSessionLimit(context.Background())
require.NoError(t, err)
assert.Equal(t, tt.wantConfig, got)
})
}
}
func TestStoreLoadSessionLimitBackendFailure(t *testing.T) {
t.Parallel()
server := miniredis.RunT(t)
store := newTestStore(t, server, Config{})
server.Close()
_, err := store.LoadSessionLimit(context.Background())
require.Error(t, err)
assert.ErrorContains(t, err, "load session limit from redis")
}
func TestStoreLoadSessionLimitNilContext(t *testing.T) {
t.Parallel()
server := miniredis.RunT(t)
store := newTestStore(t, server, Config{})
_, err := store.LoadSessionLimit(nil)
require.Error(t, err)
assert.ErrorContains(t, err, "nil context")
}
func TestStorePingNilContext(t *testing.T) {
t.Parallel()
server := miniredis.RunT(t)
store := newTestStore(t, server, Config{})
err := store.Ping(nil)
require.Error(t, err)
assert.ErrorContains(t, err, "nil context")
}
func newTestStore(t *testing.T, server *miniredis.Miniredis, cfg Config) *Store {
t.Helper()
if cfg.Addr == "" {
cfg.Addr = server.Addr()
}
if cfg.SessionLimitKey == "" {
cfg.SessionLimitKey = "authsession:config:active-session-limit"
}
if cfg.OperationTimeout == 0 {
cfg.OperationTimeout = 250 * time.Millisecond
}
store, err := New(cfg)
require.NoError(t, err)
t.Cleanup(func() {
assert.NoError(t, store.Close())
})
return store
}
func configWithLimit(limit int) ports.SessionLimitConfig {
return ports.SessionLimitConfig{
ActiveSessionLimit: &limit,
}
}