ЛР4: S3-вложения, приватный bucket и согласованность хранилищ (трек 2)

This commit is contained in:
IvanMeln1k
2026-12-04 14:19:19 +03:00
parent ec540a1a72
commit f1fae32722
1134 changed files with 557640 additions and 21 deletions
+375
View File
@@ -0,0 +1,375 @@
// Package config loads the explicit runtime configuration of the lab3
// messenger. The container image stays immutable: the same image is configured
// through environment variables (or files referenced by *_FILE variables for
// operators that do not want secrets in the environment).
package config
import (
"fmt"
"log/slog"
"os"
"strconv"
"strings"
"time"
)
const (
// DefaultSessionTTL is the contract default of contracts/README.md.
DefaultSessionTTL = time.Hour
// MaxShutdownTimeout leaves headroom below the 10 second termination
// window promised by the previous lab and expected by the container
// checks, even if an operator overrides the environment variable.
MaxShutdownTimeout = 9 * time.Second
// MaxStartupTimeout bounds the initial PostgreSQL connectivity wait.
MaxStartupTimeout = 120 * time.Second
)
// Config is validated at startup. The process refuses to start with an
// invalid value instead of silently falling back to a different security or
// durability posture.
type Config struct {
Host string
Port int
Env string
LogLevel slog.Level
ShutdownTimeout time.Duration
ShutdownDrain time.Duration
StartupTimeout time.Duration
MetricsAddr string
DatabaseURL string
CacheURL string
SessionTTL time.Duration
DBMaxConns int32
DBMinConns int32
DBConnectTimeout time.Duration
DBStatementTimeout time.Duration
QueryTimeout time.Duration
CachePoolSize int
CacheTimeout time.Duration
S3Endpoint string
S3Region string
S3Bucket string
S3AccessKey string
S3SecretKey string
S3Timeout time.Duration
MaxUploadBytes int64
MaxImagePixels int64
DecodeConcurrency int
PutConcurrency int
TempDir string
}
// Load reads and validates the full API configuration.
func Load() (Config, error) { return load(true, true) }
// LoadMigrate loads only what the one-shot migration command needs.
func LoadMigrate() (Config, error) { return load(false, false) }
// LoadTool loads the database and S3 configuration used by the offline
// reconciler and the bucket/test tools; Valkey is not required.
func LoadTool() (Config, error) { return load(false, true) }
// load is the shared parser. requireCache and requireS3 select which optional
// dependency blocks are mandatory for the calling command.
func load(requireCache, requireS3 bool) (Config, error) {
cfg := Config{
Host: envString("APP_HOST", "0.0.0.0"),
Env: envString("APP_ENV", "lab"),
ShutdownTimeout: 6 * time.Second,
ShutdownDrain: 3 * time.Second,
StartupTimeout: 30 * time.Second,
QueryTimeout: 3 * time.Second,
MetricsAddr: envString("METRICS_ADDR", "127.0.0.1:9090"),
}
port, err := envInt("APP_PORT", 8080)
if err != nil {
return Config{}, fmt.Errorf("APP_PORT: %w", err)
}
if port < 1 || port > 65535 {
return Config{}, fmt.Errorf("APP_PORT: must be between 1 and 65535")
}
cfg.Port = port
level, err := parseLogLevel(envString("LOG_LEVEL", "info"))
if err != nil {
return Config{}, fmt.Errorf("LOG_LEVEL: %w", err)
}
cfg.LogLevel = level
if strings.TrimSpace(cfg.Host) == "" {
return Config{}, fmt.Errorf("APP_HOST: must not be empty")
}
databaseURL, err := secret("DATABASE_URL")
if err != nil {
return Config{}, err
}
cfg.DatabaseURL = databaseURL
if requireCache {
cacheURL, err := secret("CACHE_URL")
if err != nil {
return Config{}, err
}
cfg.CacheURL = cacheURL
}
seconds, err := envInt("SESSION_TTL_SECONDS", int(DefaultSessionTTL/time.Second))
if err != nil {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: %w", err)
}
if seconds < 1 || seconds > 30*24*60*60 {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: must be between 1 and 2592000")
}
cfg.SessionTTL = time.Duration(seconds) * time.Second
maxConns, err := envInt("DB_MAX_CONNS", 8)
if err != nil {
return Config{}, fmt.Errorf("DB_MAX_CONNS: %w", err)
}
if maxConns < 1 || maxConns > 100 {
return Config{}, fmt.Errorf("DB_MAX_CONNS: must be between 1 and 100")
}
cfg.DBMaxConns = int32(maxConns)
minConns, err := envInt("DB_MIN_CONNS", 1)
if err != nil {
return Config{}, fmt.Errorf("DB_MIN_CONNS: %w", err)
}
if minConns < 0 || minConns > maxConns {
return Config{}, fmt.Errorf("DB_MIN_CONNS: must be between 0 and DB_MAX_CONNS")
}
cfg.DBMinConns = int32(minConns)
if cfg.DBConnectTimeout, err = envDurationSeconds("DB_CONNECT_TIMEOUT_SECONDS", 3, 1, 30); err != nil {
return Config{}, err
}
if cfg.DBStatementTimeout, err = envDurationSeconds("DB_STATEMENT_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
return Config{}, err
}
if cfg.QueryTimeout, err = envDurationSeconds("DB_QUERY_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
return Config{}, err
}
cachePool, err := envInt("CACHE_POOL_SIZE", 8)
if err != nil {
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: %w", err)
}
if cachePool < 1 || cachePool > 100 {
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: must be between 1 and 100")
}
cfg.CachePoolSize = cachePool
if cfg.CacheTimeout, err = envDurationSeconds("CACHE_TIMEOUT_SECONDS", 2, 1, 30); err != nil {
return Config{}, err
}
shutdown, err := envDurationSeconds("SHUTDOWN_TIMEOUT_SECONDS", 6, 1, 60)
if err != nil {
return Config{}, err
}
if shutdown > MaxShutdownTimeout {
shutdown = MaxShutdownTimeout
}
cfg.ShutdownTimeout = shutdown
drain, err := envDurationSeconds("SHUTDOWN_DRAIN_SECONDS", 3, 0, 8)
if err != nil {
return Config{}, err
}
// The drain must finish before the hard shutdown window; otherwise a
// SIGTERM could spend the whole grace period advertising readiness and
// never reach http.Server.Shutdown.
if drain >= shutdown {
return Config{}, fmt.Errorf("SHUTDOWN_DRAIN_SECONDS must be smaller than SHUTDOWN_TIMEOUT_SECONDS")
}
cfg.ShutdownDrain = drain
startup, err := envDurationSeconds("STARTUP_TIMEOUT_SECONDS", 30, 1, 120)
if err != nil {
return Config{}, err
}
cfg.StartupTimeout = startup
if requireS3 {
if err := loadS3(&cfg); err != nil {
return Config{}, err
}
}
return cfg, nil
}
// loadS3 parses the private object store configuration and the image limits
// that must be enforced before any unbounded read or decode.
func loadS3(cfg *Config) error {
endpoint, err := secret("S3_ENDPOINT")
if err != nil {
return err
}
cfg.S3Endpoint = endpoint
cfg.S3Region = envString("S3_REGION", "us-east-1")
cfg.S3Bucket = envString("S3_BUCKET", "messenger-attachments")
if !validBucketName(cfg.S3Bucket) {
return fmt.Errorf("S3_BUCKET: must match [a-z0-9][a-z0-9.-]{1,61}[a-z0-9]")
}
accessKey, err := secret("S3_ACCESS_KEY")
if err != nil {
return err
}
secretKey, err := secret("S3_SECRET_KEY")
if err != nil {
return err
}
cfg.S3AccessKey = accessKey
cfg.S3SecretKey = secretKey
timeout, err := envDurationSeconds("S3_TIMEOUT_SECONDS", 10, 5, 120)
if err != nil {
return err
}
cfg.S3Timeout = timeout
maxUpload, err := envInt64("MAX_UPLOAD_BYTES", 10*1024*1024)
if err != nil {
return fmt.Errorf("MAX_UPLOAD_BYTES: %w", err)
}
if maxUpload < 1 || maxUpload > 10*1024*1024 {
return fmt.Errorf("MAX_UPLOAD_BYTES: must be between 1 and 10485760")
}
cfg.MaxUploadBytes = maxUpload
maxPixels, err := envInt64("MAX_IMAGE_PIXELS", 40_000_000)
if err != nil {
return fmt.Errorf("MAX_IMAGE_PIXELS: %w", err)
}
if maxPixels < 1 || maxPixels > 40_000_000 {
return fmt.Errorf("MAX_IMAGE_PIXELS: must be between 1 and 40000000")
}
cfg.MaxImagePixels = maxPixels
concurrency, err := envInt("UPLOAD_DECODE_CONCURRENCY", 1)
if err != nil {
return fmt.Errorf("UPLOAD_DECODE_CONCURRENCY: %w", err)
}
if concurrency < 1 || concurrency > 4 {
return fmt.Errorf("UPLOAD_DECODE_CONCURRENCY: must be between 1 and 4")
}
cfg.DecodeConcurrency = concurrency
// The single-node SeaweedFS stand was verified stable at one concurrent
// PUT per API replica; two concurrent multi-megabyte writes could restart
// it. Uploads queue after their body was already streamed to a bounded
// temporary file, so queuing does not add unbounded RAM.
putConcurrency, err := envInt("S3_PUT_CONCURRENCY", 1)
if err != nil {
return fmt.Errorf("S3_PUT_CONCURRENCY: %w", err)
}
if putConcurrency != 1 {
return fmt.Errorf("S3_PUT_CONCURRENCY: must be 1 on this single-node stand")
}
cfg.PutConcurrency = putConcurrency
cfg.TempDir = envString("UPLOAD_TEMP_DIR", "")
return nil
}
func validBucketName(value string) bool {
if len(value) < 3 || len(value) > 63 {
return false
}
for i := 0; i < len(value); i++ {
c := value[i]
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '-' {
continue
}
return false
}
return value[0] != '.' && value[0] != '-' && value[len(value)-1] != '.' && value[len(value)-1] != '-'
}
// secret resolves NAME or NAME_FILE. A file is preferred when both are set so
// compose-style file secrets win over inherited environment values. Values are
// never echoed in error messages.
func secret(name string) (string, error) {
if path := strings.TrimSpace(os.Getenv(name + "_FILE")); path != "" {
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("%s_FILE: cannot read referenced file", name)
}
value := strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("%s_FILE: referenced file is empty", name)
}
return value, nil
}
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
return value, nil
}
return "", fmt.Errorf("%s or %s_FILE is required", name, name)
}
func envString(key, fallback string) string {
// An environment variable set to an empty string is treated as unset; this
// keeps container defaults working when compose passes "" for an optional
// setting.
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
return value
}
return fallback
}
func envInt(key string, fallback int) (int, error) {
raw, ok := os.LookupEnv(key)
if !ok || strings.TrimSpace(raw) == "" {
return fallback, nil
}
value, err := strconv.Atoi(strings.TrimSpace(raw))
if err != nil {
return 0, fmt.Errorf("expected an integer, got %q", raw)
}
return value, nil
}
func envInt64(key string, fallback int64) (int64, error) {
raw, ok := os.LookupEnv(key)
if !ok || strings.TrimSpace(raw) == "" {
return fallback, nil
}
value, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
if err != nil {
return 0, fmt.Errorf("expected an integer, got %q", raw)
}
return value, nil
}
func envDurationSeconds(key string, fallback, minimum, maximum int) (time.Duration, error) {
value, err := envInt(key, fallback)
if err != nil {
return 0, fmt.Errorf("%s: %w", key, err)
}
if value < minimum || value > maximum {
return 0, fmt.Errorf("%s: must be between %d and %d", key, minimum, maximum)
}
return time.Duration(value) * time.Second, nil
}
func parseLogLevel(raw string) (slog.Level, error) {
switch strings.ToLower(strings.TrimSpace(raw)) {
case "debug":
return slog.LevelDebug, nil
case "info":
return slog.LevelInfo, nil
case "warn", "warning":
return slog.LevelWarn, nil
case "error":
return slog.LevelError, nil
default:
return 0, fmt.Errorf("expected debug, info, warn or error, got %q", raw)
}
}
+178
View File
@@ -0,0 +1,178 @@
package config
import (
"os"
"path/filepath"
"testing"
"time"
)
var allKeys = []string{
"APP_HOST", "APP_PORT", "APP_ENV", "LOG_LEVEL", "SESSION_TTL_SECONDS",
"DB_MAX_CONNS", "DB_MIN_CONNS", "DB_CONNECT_TIMEOUT_SECONDS",
"DB_STATEMENT_TIMEOUT_SECONDS", "DB_QUERY_TIMEOUT_SECONDS",
"CACHE_POOL_SIZE", "CACHE_TIMEOUT_SECONDS", "SHUTDOWN_TIMEOUT_SECONDS",
"STARTUP_TIMEOUT_SECONDS", "DATABASE_URL", "DATABASE_URL_FILE",
"CACHE_URL", "CACHE_URL_FILE",
"S3_ENDPOINT", "S3_ENDPOINT_FILE", "S3_REGION", "S3_BUCKET",
"S3_ACCESS_KEY", "S3_ACCESS_KEY_FILE", "S3_SECRET_KEY", "S3_SECRET_KEY_FILE",
"S3_TIMEOUT_SECONDS", "MAX_UPLOAD_BYTES", "MAX_IMAGE_PIXELS",
"UPLOAD_DECODE_CONCURRENCY", "S3_PUT_CONCURRENCY", "UPLOAD_TEMP_DIR",
}
func clearEnvironment(t *testing.T) {
t.Helper()
for _, key := range allKeys {
t.Setenv(key, "")
}
}
func baseEnvironment(t *testing.T) {
t.Helper()
clearEnvironment(t)
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres:5432/db?sslmode=disable")
t.Setenv("CACHE_URL", "redis://:pass@valkey:6379/0")
t.Setenv("S3_ENDPOINT", "http://s3:8333")
t.Setenv("S3_BUCKET", "messenger-attachments")
t.Setenv("S3_ACCESS_KEY", "local-test-access")
t.Setenv("S3_SECRET_KEY", "local-test-secret")
}
func TestLoadDefaults(t *testing.T) {
baseEnvironment(t)
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Port != 8080 || cfg.SessionTTL != time.Hour {
t.Fatalf("unexpected defaults: %+v", cfg)
}
if cfg.DBMaxConns != 8 || cfg.DBMinConns != 1 || cfg.QueryTimeout != 3*time.Second {
t.Fatalf("unexpected pool defaults: %+v", cfg)
}
if cfg.MaxUploadBytes != 10*1024*1024 || cfg.MaxImagePixels != 40_000_000 || cfg.DecodeConcurrency != 1 {
t.Fatalf("unexpected upload defaults: %+v", cfg)
}
if cfg.S3Bucket != "messenger-attachments" || cfg.S3Region != "us-east-1" {
t.Fatalf("unexpected S3 defaults: %+v", cfg)
}
}
func TestLoadReadsSecretsFromFiles(t *testing.T) {
clearEnvironment(t)
directory := t.TempDir()
databaseFile := filepath.Join(directory, "database_url")
cacheFile := filepath.Join(directory, "cache_url")
if err := os.WriteFile(databaseFile, []byte("postgres://file:secret@postgres/db\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(cacheFile, []byte("redis://:file-secret@valkey:6379/0\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("DATABASE_URL_FILE", databaseFile)
t.Setenv("CACHE_URL_FILE", cacheFile)
t.Setenv("S3_ENDPOINT", "http://s3:8333")
t.Setenv("S3_ACCESS_KEY", "file-test-access")
t.Setenv("S3_SECRET_KEY", "file-test-secret")
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.DatabaseURL != "postgres://file:secret@postgres/db" {
t.Fatalf("database URL was not read from file: %q", cfg.DatabaseURL)
}
if cfg.CacheURL != "redis://:file-secret@valkey:6379/0" {
t.Fatalf("cache URL was not read from file: %q", cfg.CacheURL)
}
}
func TestLoadRejectsInvalidValues(t *testing.T) {
cases := []struct {
name string
key string
value string
}{
{"zero ttl", "SESSION_TTL_SECONDS", "0"},
{"huge ttl", "SESSION_TTL_SECONDS", "99999999"},
{"zero port", "APP_PORT", "0"},
{"bad log level", "LOG_LEVEL", "verbose"},
{"zero max conns", "DB_MAX_CONNS", "0"},
{"min above max", "DB_MIN_CONNS", "9"},
{"bad timeout", "DB_QUERY_TIMEOUT_SECONDS", "0"},
{"bad int", "APP_PORT", "eighty"},
{"upload above contract", "MAX_UPLOAD_BYTES", "10485761"},
{"pixels above contract", "MAX_IMAGE_PIXELS", "40000001"},
{"zero decode concurrency", "UPLOAD_DECODE_CONCURRENCY", "0"},
{"zero put concurrency", "S3_PUT_CONCURRENCY", "0"},
{"unsafe put concurrency", "S3_PUT_CONCURRENCY", "2"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
baseEnvironment(t)
t.Setenv(tc.key, tc.value)
if _, err := Load(); err == nil {
t.Fatalf("Load accepted %s=%q", tc.key, tc.value)
}
})
}
}
func TestLoadRequiresDatabaseAndCacheURLs(t *testing.T) {
clearEnvironment(t)
if _, err := Load(); err == nil {
t.Fatal("Load accepted missing DATABASE_URL/CACHE_URL")
}
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres/db")
if _, err := Load(); err == nil {
t.Fatal("Load accepted missing CACHE_URL")
}
}
func TestLoadRequiresS3Configuration(t *testing.T) {
baseEnvironment(t)
t.Setenv("S3_ACCESS_KEY", "")
if _, err := Load(); err == nil {
t.Fatal("Load accepted missing S3_ACCESS_KEY")
}
t.Setenv("S3_ACCESS_KEY", "local-test-access")
t.Setenv("S3_BUCKET", "Invalid_Bucket")
if _, err := Load(); err == nil {
t.Fatal("Load accepted an invalid S3 bucket name")
}
}
func TestMigrateConfigurationDoesNotRequireCacheOrS3(t *testing.T) {
clearEnvironment(t)
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres:5432/db?sslmode=disable")
cfg, err := LoadMigrate()
if err != nil {
t.Fatalf("LoadMigrate: %v", err)
}
if cfg.DatabaseURL == "" || cfg.CacheURL != "" || cfg.S3Endpoint != "" {
t.Fatalf("unexpected migrate configuration: %+v", cfg)
}
}
func TestShutdownTimeoutIsClamped(t *testing.T) {
baseEnvironment(t)
t.Setenv("SHUTDOWN_TIMEOUT_SECONDS", "60")
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.ShutdownTimeout != MaxShutdownTimeout {
t.Fatalf("shutdown timeout = %v, want clamp to %v", cfg.ShutdownTimeout, MaxShutdownTimeout)
}
}
func TestSecretFileErrorsDoNotLeakThePath(t *testing.T) {
clearEnvironment(t)
t.Setenv("DATABASE_URL_FILE", "/nonexistent/path/database_url")
_, err := Load()
if err == nil {
t.Fatal("Load accepted a missing secret file")
}
if got := err.Error(); got != "DATABASE_URL_FILE: cannot read referenced file" {
t.Fatalf("error leaks path: %q", got)
}
}