Добавить сессии в Valkey и вход через Basic с Bearer-токеном
This commit is contained in:
@@ -23,6 +23,8 @@ type Config struct {
|
||||
ShutdownTimeout time.Duration
|
||||
MaxBodyBytes int64
|
||||
DatabaseURL string
|
||||
SessionStoreURL string
|
||||
SessionTTL time.Duration
|
||||
}
|
||||
|
||||
// Lookup reads one variable, reporting whether it was set; os.LookupEnv
|
||||
@@ -37,6 +39,7 @@ func Load(lookup Lookup) (Config, error) {
|
||||
LogLevel: slog.LevelInfo,
|
||||
ShutdownTimeout: 8 * time.Second,
|
||||
MaxBodyBytes: 64 * 1024,
|
||||
SessionTTL: time.Hour,
|
||||
}
|
||||
if v, ok := lookup("APP_HOST"); ok {
|
||||
if strings.TrimSpace(v) == "" {
|
||||
@@ -75,10 +78,20 @@ func Load(lookup Lookup) (Config, error) {
|
||||
}
|
||||
cfg.MaxBodyBytes = n
|
||||
}
|
||||
if v, ok := lookup("SESSION_TTL_SECONDS"); ok {
|
||||
n, err := strconv.ParseUint(v, 10, 32)
|
||||
if err != nil || n == 0 {
|
||||
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS must be a positive whole number of seconds, got %q", v)
|
||||
}
|
||||
cfg.SessionTTL = time.Duration(n) * time.Second
|
||||
}
|
||||
var err error
|
||||
if cfg.DatabaseURL, err = secret(lookup, "DATABASE_URL_FILE"); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if cfg.SessionStoreURL, err = secret(lookup, "SESSION_STORE_URL_FILE"); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -27,12 +27,18 @@ func secretFile(t *testing.T, content string) string {
|
||||
return path
|
||||
}
|
||||
|
||||
const databaseURL = "postgres://app:s3cret@db:5432/messenger"
|
||||
const (
|
||||
databaseURL = "postgres://app:s3cret@db:5432/messenger"
|
||||
sessionStoreURL = "redis://:s3cret@valkey:6379/0"
|
||||
)
|
||||
|
||||
// required holds the variables without defaults, merged with extra.
|
||||
func required(t *testing.T, extra map[string]string) map[string]string {
|
||||
t.Helper()
|
||||
values := map[string]string{"DATABASE_URL_FILE": secretFile(t, databaseURL+"\n")}
|
||||
values := map[string]string{
|
||||
"DATABASE_URL_FILE": secretFile(t, databaseURL+"\n"),
|
||||
"SESSION_STORE_URL_FILE": secretFile(t, sessionStoreURL+"\r\n"),
|
||||
}
|
||||
for k, v := range extra {
|
||||
values[k] = v
|
||||
}
|
||||
@@ -53,26 +59,33 @@ func TestDefaults(t *testing.T) {
|
||||
if cfg.ShutdownTimeout != 8*time.Second || cfg.MaxBodyBytes != 65536 {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
if cfg.DatabaseURL != databaseURL {
|
||||
t.Fatalf("DatabaseURL = %q, want the file content without the newline", cfg.DatabaseURL)
|
||||
if cfg.DatabaseURL != databaseURL || cfg.SessionStoreURL != sessionStoreURL {
|
||||
t.Fatalf("urls = %q, %q; want the file contents without line endings", cfg.DatabaseURL, cfg.SessionStoreURL)
|
||||
}
|
||||
if cfg.SessionTTL != time.Hour {
|
||||
t.Fatalf("SessionTTL = %v, want 1h", cfg.SessionTTL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecretFilesAreRequiredAndNeverEchoed(t *testing.T) {
|
||||
cases := map[string]map[string]string{
|
||||
"unset": nil,
|
||||
"empty path": {"DATABASE_URL_FILE": ""},
|
||||
"no file": {"DATABASE_URL_FILE": filepath.Join(t.TempDir(), "missing")},
|
||||
"blank file": {"DATABASE_URL_FILE": secretFile(t, " \r\n")},
|
||||
}
|
||||
for name, values := range cases {
|
||||
_, err := config.Load(env(values))
|
||||
if err == nil {
|
||||
t.Errorf("%s: want error", name)
|
||||
continue
|
||||
for _, key := range []string{"DATABASE_URL_FILE", "SESSION_STORE_URL_FILE"} {
|
||||
cases := map[string]func(map[string]string){
|
||||
"unset": func(v map[string]string) { delete(v, key) },
|
||||
"empty path": func(v map[string]string) { v[key] = "" },
|
||||
"no file": func(v map[string]string) { v[key] = filepath.Join(t.TempDir(), "missing") },
|
||||
"blank file": func(v map[string]string) { v[key] = secretFile(t, " \r\n") },
|
||||
}
|
||||
if !strings.Contains(err.Error(), "DATABASE_URL_FILE") || strings.Contains(err.Error(), "s3cret") {
|
||||
t.Errorf("%s: error must name the variable and hide the secret: %v", name, err)
|
||||
for name, breakIt := range cases {
|
||||
values := required(t, nil)
|
||||
breakIt(values)
|
||||
_, err := config.Load(env(values))
|
||||
if err == nil {
|
||||
t.Errorf("%s %s: want error", key, name)
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(err.Error(), key) || strings.Contains(err.Error(), "s3cret") {
|
||||
t.Errorf("%s %s: error must name the variable and hide the secret: %v", key, name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,6 +98,7 @@ func TestOverrides(t *testing.T) {
|
||||
"APP_LOG_LEVEL": "debug",
|
||||
"APP_SHUTDOWN_TIMEOUT": "3s",
|
||||
"APP_MAX_BODY_BYTES": "1024",
|
||||
"SESSION_TTL_SECONDS": "300",
|
||||
})))
|
||||
if err != nil {
|
||||
t.Fatalf("Load error: %v", err)
|
||||
@@ -92,7 +106,7 @@ func TestOverrides(t *testing.T) {
|
||||
if cfg.Addr() != "127.0.0.1:9090" || cfg.Env != "dev" || cfg.LogLevel != slog.LevelDebug {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
if cfg.ShutdownTimeout != 3*time.Second || cfg.MaxBodyBytes != 1024 {
|
||||
if cfg.ShutdownTimeout != 3*time.Second || cfg.MaxBodyBytes != 1024 || cfg.SessionTTL != 5*time.Minute {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
}
|
||||
@@ -108,6 +122,10 @@ func TestInvalidValuesAreReported(t *testing.T) {
|
||||
"body zero": {"APP_MAX_BODY_BYTES": "0"},
|
||||
"body text": {"APP_MAX_BODY_BYTES": "big"},
|
||||
"empty host": {"APP_HOST": ""},
|
||||
"ttl zero": {"SESSION_TTL_SECONDS": "0"},
|
||||
"ttl negative": {"SESSION_TTL_SECONDS": "-5"},
|
||||
"ttl text": {"SESSION_TTL_SECONDS": "hour"},
|
||||
"ttl fraction": {"SESSION_TTL_SECONDS": "1.5"},
|
||||
}
|
||||
for name, values := range cases {
|
||||
if _, err := config.Load(env(required(t, values))); err == nil {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// Package valkey connects to the Valkey session store.
|
||||
//
|
||||
// Timeouts are constants: every authenticated request reads a session, so
|
||||
// they bound how long a request can wait when the store is slow. Retries are
|
||||
// disabled for the same reason: a request that cannot reach the store fails
|
||||
// fast with 503 instead of waiting through a backoff.
|
||||
package valkey
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const (
|
||||
dialTimeout = 2 * time.Second
|
||||
ioTimeout = time.Second
|
||||
poolSize = 10
|
||||
noRetries = -1
|
||||
)
|
||||
|
||||
// NewClient connects to url (redis:// scheme) and pings the server. Errors
|
||||
// never include the URL, which carries the password.
|
||||
func NewClient(ctx context.Context, url string) (*redis.Client, error) {
|
||||
opts, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, errors.New("session store url is invalid")
|
||||
}
|
||||
opts.DialTimeout = dialTimeout
|
||||
opts.ReadTimeout = ioTimeout
|
||||
opts.WriteTimeout = ioTimeout
|
||||
opts.PoolSize = poolSize
|
||||
opts.MaxRetries = noRetries
|
||||
|
||||
client := redis.NewClient(opts)
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
_ = client.Close()
|
||||
return nil, fmt.Errorf("ping session store at %s: %w", opts.Addr, err)
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package valkey_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/internal/platform/valkey"
|
||||
"messenger/internal/testenv"
|
||||
)
|
||||
|
||||
func TestNewClientPingsAndBoundsWaiting(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
kv, err := testenv.StartValkey(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer kv.Close()
|
||||
|
||||
client, err := valkey.NewClient(ctx, kv.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient: %v", err)
|
||||
}
|
||||
defer client.Close()
|
||||
opts := client.Options()
|
||||
if opts.DialTimeout != 2*time.Second || opts.ReadTimeout != time.Second || opts.WriteTimeout != time.Second {
|
||||
t.Fatalf("timeouts = %v/%v/%v, want 2s/1s/1s", opts.DialTimeout, opts.ReadTimeout, opts.WriteTimeout)
|
||||
}
|
||||
// go-redis stores the requested -1 ("no retries") as 0 after init; its
|
||||
// default would be 3.
|
||||
if opts.PoolSize != 10 || opts.MaxRetries != 0 {
|
||||
t.Fatalf("PoolSize = %d, MaxRetries = %d; want 10 and 0 (fail fast)", opts.PoolSize, opts.MaxRetries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewClientErrorsNeverEchoTheURL(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
for name, url := range map[string]string{
|
||||
"malformed": "redis://:s3cret@host:port/x",
|
||||
"unreachable": "redis://:s3cret@127.0.0.1:1/0",
|
||||
} {
|
||||
_, err := valkey.NewClient(ctx, url)
|
||||
if err == nil {
|
||||
t.Fatalf("%s: want error", name)
|
||||
}
|
||||
if strings.Contains(err.Error(), "s3cret") {
|
||||
t.Fatalf("%s: error leaks the password: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user