lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
@@ -0,0 +1,472 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"mtusi-messenger/internal/logger"
|
||||
"mtusi-messenger/internal/platform/secretfile"
|
||||
"mtusi-messenger/internal/platform/tlsconfig"
|
||||
)
|
||||
|
||||
const (
|
||||
configEnvKey = "APP_CONFIG"
|
||||
envKey = "APP_ENV"
|
||||
configName = "config"
|
||||
defaultEnv = "dev"
|
||||
configDir = "./config/"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Env string `mapstructure:"env" validate:"omitempty,eq=dev"`
|
||||
Server Server `mapstructure:"server"`
|
||||
Log Log `mapstructure:"log"`
|
||||
Postgres Postgres `mapstructure:"postgres"`
|
||||
Redis Redis `mapstructure:"redis"`
|
||||
Cache Cache `mapstructure:"cache"`
|
||||
Session Session `mapstructure:"session"`
|
||||
Idempotency Idempotency `mapstructure:"idempotency"`
|
||||
S3 S3 `mapstructure:"s3"`
|
||||
Broker Broker `mapstructure:"broker"`
|
||||
Worker Worker `mapstructure:"worker"`
|
||||
Relay Relay `mapstructure:"relay"`
|
||||
Outbox Outbox `mapstructure:"outbox"`
|
||||
Processing Processing `mapstructure:"processing"`
|
||||
Staging Staging `mapstructure:"staging"`
|
||||
Admission Admission `mapstructure:"admission"`
|
||||
}
|
||||
|
||||
// Broker carries the AMQP transport settings. The API never publishes; relay
|
||||
// and worker require a non-empty URL at startup.
|
||||
type Broker struct {
|
||||
URL string `mapstructure:"url"`
|
||||
ConnectTimeout time.Duration `mapstructure:"connect_timeout"`
|
||||
ConfirmTimeout time.Duration `mapstructure:"confirm_timeout"`
|
||||
Heartbeat time.Duration `mapstructure:"heartbeat"`
|
||||
Exchange string `mapstructure:"exchange" validate:"required"`
|
||||
Queue string `mapstructure:"queue" validate:"required"`
|
||||
Prefetch int `mapstructure:"prefetch" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
// Worker bounds the process that consumes jobs.
|
||||
type Worker struct {
|
||||
Concurrency int `mapstructure:"concurrency" validate:"required,gt=0,lte=32"`
|
||||
Prefetch int `mapstructure:"prefetch" validate:"required,gt=0,lte=100"`
|
||||
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout" validate:"required,gt=0"`
|
||||
HealthAddr string `mapstructure:"health_addr" validate:"required"`
|
||||
}
|
||||
|
||||
// Relay bounds the outbox publisher and lease reaper.
|
||||
type Relay struct {
|
||||
HealthAddr string `mapstructure:"health_addr" validate:"required"`
|
||||
}
|
||||
|
||||
// Outbox schedules publications and reclaims abandoned relay claims.
|
||||
type Outbox struct {
|
||||
PollInterval time.Duration `mapstructure:"poll_interval" validate:"required,gt=0"`
|
||||
ClaimTTL time.Duration `mapstructure:"claim_ttl" validate:"required,gt=0"`
|
||||
Batch int `mapstructure:"batch" validate:"required,gt=0,lte=1000"`
|
||||
ReaperInterval time.Duration `mapstructure:"reaper_interval" validate:"required,gt=0"`
|
||||
ReconcileAfter time.Duration `mapstructure:"reconcile_after" validate:"omitempty,gt=0"`
|
||||
Retention time.Duration `mapstructure:"retention" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
// Processing holds the shared job contract knobs read by API and worker.
|
||||
type Processing struct {
|
||||
PipelineVersion int `mapstructure:"pipeline_version" validate:"required,gte=1,lte=2"`
|
||||
MaxAttempts int `mapstructure:"max_attempts" validate:"required,gte=1,lte=100"`
|
||||
JobTimeout time.Duration `mapstructure:"job_timeout" validate:"required,gt=0"`
|
||||
LeaseTTL time.Duration `mapstructure:"lease_ttl" validate:"required,gt=0"`
|
||||
Heartbeat time.Duration `mapstructure:"heartbeat" validate:"required,gt=0"`
|
||||
RetryBase time.Duration `mapstructure:"retry_base" validate:"required,gt=0"`
|
||||
RetryCap time.Duration `mapstructure:"retry_cap" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
// Staging controls cleanup of objects that are no longer the active source.
|
||||
type Staging struct {
|
||||
OrphanGrace time.Duration `mapstructure:"orphan_grace" validate:"required,gt=0"`
|
||||
FailedRetention time.Duration `mapstructure:"failed_retention" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
// Admission bounds accepted-but-unfinished work per user and globally.
|
||||
type Admission struct {
|
||||
MaxPendingPerUser int `mapstructure:"max_pending_per_user" validate:"required,gte=0"`
|
||||
MaxPending int `mapstructure:"max_pending" validate:"required,gte=0"`
|
||||
MaxStagedBytes int64 `mapstructure:"max_staged_bytes" validate:"required,gte=0"`
|
||||
MaxConcurrent int `mapstructure:"max_concurrent_uploads" validate:"omitempty,gt=0"`
|
||||
}
|
||||
|
||||
// S3 describes the object store and attachment limits. Access keys are checked
|
||||
// by the object-store constructor rather than the global validator: cmd/migrate
|
||||
// and unit tests load this config without any S3 credentials.
|
||||
type S3 struct {
|
||||
Endpoint string `mapstructure:"endpoint" validate:"required,url"`
|
||||
PublicEndpoint string `mapstructure:"public_endpoint" validate:"omitempty,url"`
|
||||
Region string `mapstructure:"region" validate:"required"`
|
||||
Bucket string `mapstructure:"bucket" validate:"required"`
|
||||
AccessKeyID string `mapstructure:"access_key_id"`
|
||||
SecretAccessKey string `mapstructure:"secret_access_key"`
|
||||
UsePathStyle bool `mapstructure:"use_path_style"`
|
||||
Timeout time.Duration `mapstructure:"timeout" validate:"required,gt=0"`
|
||||
|
||||
MaxUploadBytes int64 `mapstructure:"max_upload_bytes" validate:"required,gt=0,lte=10485760"`
|
||||
MaxImagePixels int64 `mapstructure:"max_image_pixels" validate:"required,gt=0,lte=40000000"`
|
||||
PresignTTL time.Duration `mapstructure:"presign_ttl" validate:"required,gt=0,lte=168h"`
|
||||
SweepInterval time.Duration `mapstructure:"sweep_interval" validate:"required,gt=0"`
|
||||
SweepGrace time.Duration `mapstructure:"sweep_grace" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
TTLSeconds int `mapstructure:"ttl_seconds" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
// Idempotency holds the retention window of a message Idempotency-Key (contract
|
||||
// 1.3.0 requires at least 24 hours).
|
||||
type Idempotency struct {
|
||||
TTLSeconds int `mapstructure:"ttl_seconds" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type Redis struct {
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
Host string `mapstructure:"host" validate:"omitempty,hostname|ip"`
|
||||
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
|
||||
Username string `mapstructure:"username"`
|
||||
Password string `mapstructure:"password"`
|
||||
DB int `mapstructure:"db" validate:"omitempty,gte=0,lte=15"`
|
||||
MaxRetries int `mapstructure:"max_retries" validate:"omitempty,gte=-1"`
|
||||
DialTimeout time.Duration `mapstructure:"dial_timeout" validate:"omitempty,gt=0"`
|
||||
ReadTimeout time.Duration `mapstructure:"read_timeout" validate:"omitempty,gt=0"`
|
||||
WriteTimeout time.Duration `mapstructure:"write_timeout" validate:"omitempty,gt=0"`
|
||||
PoolSize int `mapstructure:"pool_size" validate:"omitempty,gt=0"`
|
||||
}
|
||||
|
||||
type Cache struct {
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
ChatListTTL time.Duration `mapstructure:"chat_list_ttl" validate:"required,gt=0"`
|
||||
LockTTL time.Duration `mapstructure:"lock_ttl" validate:"required,gt=1s"`
|
||||
LockWaitTimeout time.Duration `mapstructure:"lock_wait_timeout" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
Host string `mapstructure:"host" validate:"required,hostname|ip"`
|
||||
Port int `mapstructure:"port" validate:"required,min=1,max=65535"`
|
||||
ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout" validate:"required,gt=0"`
|
||||
ReadTimeout time.Duration `mapstructure:"read_timeout" validate:"required,gt=0"`
|
||||
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout" validate:"required,gt=0"`
|
||||
// MaxBodyBytes bounds a request body before the transport decodes it; uploads
|
||||
// of a later lab raise it explicitly (contract 4: 10 MiB attachments).
|
||||
MaxBodyBytes int64 `mapstructure:"max_body_bytes" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type Log struct {
|
||||
Level string `mapstructure:"level" validate:"required,oneof=debug info warn error"`
|
||||
Format string `mapstructure:"format" validate:"required,oneof=json console"`
|
||||
}
|
||||
|
||||
type Postgres struct {
|
||||
Host string `mapstructure:"host" validate:"omitempty,hostname|ip"`
|
||||
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
|
||||
Database string `mapstructure:"database" validate:"omitempty,min=1"`
|
||||
User string `mapstructure:"user" validate:"omitempty,min=1"`
|
||||
Password string `mapstructure:"password"`
|
||||
SSLMode string `mapstructure:"ssl_mode" validate:"omitempty,eq=verify-full"`
|
||||
MaxConns int32 `mapstructure:"max_conns" validate:"omitempty,gt=0"`
|
||||
MinConns int32 `mapstructure:"min_conns" validate:"omitempty,gte=0"`
|
||||
MaxConnLifetime time.Duration `mapstructure:"max_conn_lifetime" validate:"omitempty,gt=0"`
|
||||
MaxConnIdleTime time.Duration `mapstructure:"max_conn_idle_time" validate:"omitempty,gt=0"`
|
||||
ConnectTimeout time.Duration `mapstructure:"connect_timeout" validate:"omitempty,gt=0"`
|
||||
QueryTimeout time.Duration `mapstructure:"query_timeout" validate:"omitempty,gt=0"`
|
||||
}
|
||||
|
||||
func (p Postgres) DSN() string {
|
||||
u := &url.URL{
|
||||
Scheme: "postgres",
|
||||
Host: net.JoinHostPort(p.Host, strconv.Itoa(p.Port)),
|
||||
Path: "/" + p.Database,
|
||||
}
|
||||
|
||||
if p.Password == "" {
|
||||
u.User = url.User(p.User)
|
||||
} else {
|
||||
u.User = url.UserPassword(p.User, p.Password)
|
||||
}
|
||||
|
||||
query := url.Values{}
|
||||
files := tlsconfig.FilesFromEnv()
|
||||
query.Set("sslmode", "verify-full")
|
||||
query.Set("sslrootcert", files.CA)
|
||||
query.Set("sslcert", files.Cert)
|
||||
query.Set("sslkey", files.Key)
|
||||
u.RawQuery = query.Encode()
|
||||
|
||||
return u.String()
|
||||
}
|
||||
|
||||
var defaults = map[string]any{
|
||||
"env": "dev",
|
||||
"server.host": "0.0.0.0",
|
||||
"server.port": 8080,
|
||||
"server.read_header_timeout": "10s",
|
||||
"server.read_timeout": "60s",
|
||||
"server.shutdown_timeout": "10s",
|
||||
"server.max_body_bytes": 262144,
|
||||
"s3.endpoint": "https://localhost:8333",
|
||||
"s3.public_endpoint": "https://localhost:8333",
|
||||
"s3.region": "us-east-1",
|
||||
"s3.bucket": "messenger-attachments",
|
||||
"s3.access_key_id": "",
|
||||
"s3.secret_access_key": "",
|
||||
"s3.use_path_style": true,
|
||||
"s3.timeout": "30s",
|
||||
"s3.max_upload_bytes": 10485760,
|
||||
"s3.max_image_pixels": 40000000,
|
||||
"s3.presign_ttl": "5m",
|
||||
"s3.sweep_interval": "1m",
|
||||
"s3.sweep_grace": "10m",
|
||||
"log.level": "info",
|
||||
"log.format": "json",
|
||||
"session.ttl_seconds": 3600,
|
||||
"idempotency.ttl_seconds": 86400,
|
||||
"postgres.host": "",
|
||||
"postgres.port": 0,
|
||||
"postgres.database": "",
|
||||
"postgres.user": "",
|
||||
"postgres.password": "",
|
||||
"postgres.ssl_mode": "verify-full",
|
||||
"redis.enabled": false,
|
||||
"redis.host": "localhost",
|
||||
"redis.port": 6379,
|
||||
"redis.username": "",
|
||||
"redis.password": "",
|
||||
"redis.db": 0,
|
||||
"redis.max_retries": -1,
|
||||
"redis.dial_timeout": "300ms",
|
||||
"redis.read_timeout": "200ms",
|
||||
"redis.write_timeout": "200ms",
|
||||
"redis.pool_size": 10,
|
||||
"cache.enabled": false,
|
||||
"cache.chat_list_ttl": "5m",
|
||||
"cache.lock_ttl": "10s",
|
||||
"cache.lock_wait_timeout": "2s",
|
||||
|
||||
"broker.url": "",
|
||||
"broker.connect_timeout": "5s",
|
||||
"broker.confirm_timeout": "5s",
|
||||
"broker.heartbeat": "10s",
|
||||
"broker.exchange": "attachments.jobs",
|
||||
"broker.queue": "attachment.process.v1",
|
||||
"broker.prefetch": 1,
|
||||
"worker.concurrency": 1,
|
||||
"worker.prefetch": 1,
|
||||
"worker.shutdown_timeout": "30s",
|
||||
"worker.health_addr": "127.0.0.1:8081",
|
||||
"relay.health_addr": "127.0.0.1:8082",
|
||||
"outbox.poll_interval": "1s",
|
||||
"outbox.claim_ttl": "30s",
|
||||
"outbox.batch": 20,
|
||||
"outbox.reaper_interval": "15s",
|
||||
"outbox.retention": "168h",
|
||||
"processing.pipeline_version": 1,
|
||||
"processing.max_attempts": 5,
|
||||
"processing.job_timeout": "120s",
|
||||
"processing.lease_ttl": "180s",
|
||||
"processing.heartbeat": "30s",
|
||||
"processing.retry_base": "2s",
|
||||
"processing.retry_cap": "60s",
|
||||
"staging.orphan_grace": "1h",
|
||||
"staging.failed_retention": "168h",
|
||||
"admission.max_pending_per_user": 20,
|
||||
"admission.max_pending": 200,
|
||||
"admission.max_staged_bytes": 2147483648,
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
return load("")
|
||||
}
|
||||
|
||||
// LoadOperator reads the migration credential from an operator-only mounted file.
|
||||
// Application credentials are acquired by Bao before Load instead.
|
||||
func LoadOperator() (Config, error) {
|
||||
path := os.Getenv("POSTGRES_PASSWORD_FILE")
|
||||
if path == "" {
|
||||
return Config{}, errors.New("operator config: postgres_password_file is required")
|
||||
}
|
||||
return load(path)
|
||||
}
|
||||
|
||||
func load(operatorPasswordFile string) (Config, error) {
|
||||
v := viper.New()
|
||||
|
||||
if err := configureSource(v); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
v.AllowEmptyEnv(true)
|
||||
v.AutomaticEnv()
|
||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
|
||||
for key := range defaults {
|
||||
if err := v.BindEnv(key); err != nil {
|
||||
return Config{}, fmt.Errorf("bind env %q: %w", key, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The skeleton suggests MAX_UPLOAD_BYTES / MAX_IMAGE_PIXELS. Keep those
|
||||
// names while storing the values under the S3 section.
|
||||
for key, env := range map[string]string{
|
||||
"s3.max_upload_bytes": "MAX_UPLOAD_BYTES",
|
||||
"s3.max_image_pixels": "MAX_IMAGE_PIXELS",
|
||||
} {
|
||||
if err := v.BindEnv(key, env); err != nil {
|
||||
return Config{}, fmt.Errorf("bind env %q: %w", env, err)
|
||||
}
|
||||
}
|
||||
if operatorPasswordFile != "" {
|
||||
password, err := secretfile.Read(operatorPasswordFile)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("read operator database password: %w", err)
|
||||
}
|
||||
value := strings.TrimRight(string(password), "\r\n")
|
||||
if value == "" {
|
||||
return Config{}, errors.New("operator database password is empty")
|
||||
}
|
||||
v.Set("postgres.password", value)
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
if err := v.Unmarshal(&cfg); err != nil {
|
||||
return Config{}, fmt.Errorf("unmarshal config: %w", err)
|
||||
}
|
||||
|
||||
if err := validate.Struct(cfg); err != nil {
|
||||
return Config{}, fmt.Errorf("validate config: %w", err)
|
||||
}
|
||||
|
||||
if err := cfg.validateDependencies(); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c Config) validateDependencies() error {
|
||||
if c.Cache.Enabled && !c.Redis.Enabled {
|
||||
return errors.New("validate config: cache.enabled requires redis.enabled")
|
||||
}
|
||||
|
||||
if c.S3.SweepGrace <= c.S3.PresignTTL {
|
||||
return errors.New("validate config: s3.sweep_grace must exceed s3.presign_ttl")
|
||||
}
|
||||
|
||||
if c.Processing.LeaseTTL < 3*c.Processing.Heartbeat {
|
||||
return errors.New("validate config: processing.lease_ttl must be at least 3x processing.heartbeat")
|
||||
}
|
||||
|
||||
if c.Processing.JobTimeout >= c.Processing.LeaseTTL {
|
||||
return errors.New("validate config: processing.job_timeout must be below processing.lease_ttl")
|
||||
}
|
||||
|
||||
if c.Processing.RetryCap < c.Processing.RetryBase {
|
||||
return errors.New("validate config: processing.retry_cap must be >= processing.retry_base")
|
||||
}
|
||||
|
||||
if c.Staging.FailedRetention < c.Staging.OrphanGrace {
|
||||
return errors.New("validate config: staging.failed_retention must be >= staging.orphan_grace")
|
||||
}
|
||||
|
||||
for _, endpoint := range []string{c.S3.Endpoint, c.S3.PublicEndpoint} {
|
||||
if endpoint == "" {
|
||||
continue
|
||||
}
|
||||
u, err := url.Parse(endpoint)
|
||||
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil {
|
||||
return errors.New("validate config: s3 endpoints must be https urls without credentials")
|
||||
}
|
||||
}
|
||||
|
||||
if c.Broker.URL != "" {
|
||||
u, err := url.Parse(c.Broker.URL)
|
||||
if err != nil || u.Scheme != "amqps" || u.Hostname() == "" || u.User != nil {
|
||||
return errors.New("validate config: broker.url must be an amqps url without credentials")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func configureSource(v *viper.Viper) error {
|
||||
for key, value := range defaults {
|
||||
v.SetDefault(key, value)
|
||||
}
|
||||
|
||||
v.SetConfigType("yaml")
|
||||
|
||||
if path := os.Getenv(configEnvKey); path != "" {
|
||||
v.SetConfigFile(path)
|
||||
} else {
|
||||
env := os.Getenv(envKey)
|
||||
if env == "" {
|
||||
env = defaultEnv
|
||||
}
|
||||
|
||||
v.SetConfigName(configName)
|
||||
v.AddConfigPath(filepath.Join(configDir, env))
|
||||
}
|
||||
|
||||
if err := v.ReadInConfig(); err != nil {
|
||||
var notFound viper.ConfigFileNotFoundError
|
||||
if errors.As(err, ¬Found) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("read config: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c Config) Addr() string {
|
||||
return net.JoinHostPort(c.Server.Host, strconv.Itoa(c.Server.Port))
|
||||
}
|
||||
|
||||
func (c Config) SlogLevel() slog.Level {
|
||||
level, _ := logger.ParseLevel(c.Log.Level)
|
||||
|
||||
return level
|
||||
}
|
||||
|
||||
func (c Config) LoggerFormat() logger.Format {
|
||||
format, _ := logger.ParseFormat(c.Log.Format)
|
||||
|
||||
return format
|
||||
}
|
||||
|
||||
var validate = newValidator()
|
||||
|
||||
func newValidator() *validator.Validate {
|
||||
v := validator.New(validator.WithRequiredStructEnabled())
|
||||
v.RegisterTagNameFunc(envName)
|
||||
|
||||
return v
|
||||
}
|
||||
|
||||
func envName(field reflect.StructField) string {
|
||||
key := field.Tag.Get("mapstructure")
|
||||
if key == "" {
|
||||
return field.Name
|
||||
}
|
||||
|
||||
return strings.ToUpper(key)
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/logger"
|
||||
)
|
||||
|
||||
func TestEnvOverridesDefaults(t *testing.T) {
|
||||
t.Setenv("SERVER_HOST", "127.0.0.1")
|
||||
t.Setenv("SERVER_PORT", "9090")
|
||||
t.Setenv("SERVER_READ_HEADER_TIMEOUT", "3s")
|
||||
t.Setenv("SERVER_SHUTDOWN_TIMEOUT", "30s")
|
||||
t.Setenv("LOG_LEVEL", "debug")
|
||||
t.Setenv("LOG_FORMAT", "console")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "127.0.0.1", cfg.Server.Host)
|
||||
assert.Equal(t, 9090, cfg.Server.Port)
|
||||
assert.Equal(t, 3*time.Second, cfg.Server.ReadHeaderTimeout)
|
||||
assert.Equal(t, 30*time.Second, cfg.Server.ShutdownTimeout)
|
||||
assert.Equal(t, "debug", cfg.Log.Level)
|
||||
assert.Equal(t, "console", cfg.Log.Format)
|
||||
}
|
||||
|
||||
func TestDsnEncodesCredentials(t *testing.T) {
|
||||
t.Setenv("TLS_CA_FILE", "/identity/ca.crt")
|
||||
t.Setenv("TLS_CERT_FILE", "/identity/tls.crt")
|
||||
t.Setenv("TLS_KEY_FILE", "/identity/tls.key")
|
||||
cfg := config.Postgres{
|
||||
Host: "db",
|
||||
Port: 5432,
|
||||
Database: "app",
|
||||
User: "user",
|
||||
Password: "p@ss:w/rd",
|
||||
SSLMode: "verify-full",
|
||||
}
|
||||
|
||||
dsn, err := url.Parse(cfg.DSN())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "user", dsn.User.Username())
|
||||
password, ok := dsn.User.Password()
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "p@ss:w/rd", password)
|
||||
assert.Equal(t, "db:5432", dsn.Host)
|
||||
assert.Equal(t, "/app", dsn.Path)
|
||||
assert.Equal(t, "verify-full", dsn.Query().Get("sslmode"))
|
||||
assert.Equal(t, "/identity/ca.crt", dsn.Query().Get("sslrootcert"))
|
||||
assert.Equal(t, "/identity/tls.crt", dsn.Query().Get("sslcert"))
|
||||
assert.Equal(t, "/identity/tls.key", dsn.Query().Get("sslkey"))
|
||||
}
|
||||
|
||||
func writeConfig(t *testing.T, body string) string {
|
||||
t.Helper()
|
||||
|
||||
path := filepath.Join(t.TempDir(), "config.yaml")
|
||||
require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
|
||||
|
||||
return path
|
||||
}
|
||||
|
||||
func TestLoadsYAMLFile(t *testing.T) {
|
||||
path := writeConfig(t, `
|
||||
env: dev
|
||||
server:
|
||||
host: 10.0.0.1
|
||||
port: 9999
|
||||
read_header_timeout: 3s
|
||||
shutdown_timeout: 7s
|
||||
log:
|
||||
level: debug
|
||||
format: console
|
||||
postgres:
|
||||
host: db
|
||||
port: 5433
|
||||
database: app
|
||||
user: app
|
||||
password: secret
|
||||
ssl_mode: verify-full
|
||||
max_conns: 7
|
||||
min_conns: 2
|
||||
max_conn_lifetime: 2h
|
||||
max_conn_idle_time: 10m
|
||||
connect_timeout: 2s
|
||||
query_timeout: 3s
|
||||
`)
|
||||
|
||||
t.Setenv("APP_CONFIG", path)
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "10.0.0.1", cfg.Server.Host)
|
||||
assert.Equal(t, 9999, cfg.Server.Port)
|
||||
assert.Equal(t, 3*time.Second, cfg.Server.ReadHeaderTimeout)
|
||||
assert.Equal(t, "debug", cfg.Log.Level)
|
||||
assert.Equal(t, "console", cfg.Log.Format)
|
||||
assert.Equal(t, "db", cfg.Postgres.Host)
|
||||
assert.Equal(t, 5433, cfg.Postgres.Port)
|
||||
assert.Equal(t, "app", cfg.Postgres.Database)
|
||||
assert.Equal(t, int32(7), cfg.Postgres.MaxConns)
|
||||
assert.Equal(t, 2*time.Second, cfg.Postgres.ConnectTimeout)
|
||||
}
|
||||
|
||||
func TestEnvOverridesYAML(t *testing.T) {
|
||||
path := writeConfig(t, `
|
||||
env: dev
|
||||
server:
|
||||
host: 10.0.0.1
|
||||
port: 9999
|
||||
read_header_timeout: 3s
|
||||
shutdown_timeout: 7s
|
||||
log:
|
||||
level: debug
|
||||
format: console
|
||||
postgres:
|
||||
host: db
|
||||
port: 5433
|
||||
database: app
|
||||
user: app
|
||||
password: file
|
||||
ssl_mode: verify-full
|
||||
`)
|
||||
|
||||
t.Setenv("APP_CONFIG", path)
|
||||
t.Setenv("SERVER_HOST", "127.0.0.1")
|
||||
t.Setenv("POSTGRES_PASSWORD", "env")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "127.0.0.1", cfg.Server.Host, "env переопределяет YAML")
|
||||
assert.Equal(t, 9999, cfg.Server.Port)
|
||||
assert.Equal(t, "env", cfg.Postgres.Password)
|
||||
}
|
||||
|
||||
func TestSessionTTLFromContractEnv(t *testing.T) {
|
||||
t.Setenv("SESSION_TTL_SECONDS", "2")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, 2, cfg.Session.TTLSeconds)
|
||||
}
|
||||
|
||||
func TestInvalidValues(t *testing.T) {
|
||||
tests := map[string]map[string]string{
|
||||
"пустой server.host": {"SERVER_HOST": ""},
|
||||
"host не адрес и не имя": {"SERVER_HOST": "не адрес"},
|
||||
"порт ниже диапазона": {"SERVER_PORT": "0"},
|
||||
"порт выше диапазона": {"SERVER_PORT": "65536"},
|
||||
"нулевой read header timeout": {"SERVER_READ_HEADER_TIMEOUT": "0s"},
|
||||
"отрицательный shutdown": {"SERVER_SHUTDOWN_TIMEOUT": "-1s"},
|
||||
"неизвестный log level": {"LOG_LEVEL": "trace"},
|
||||
"неизвестный log format": {"LOG_FORMAT": "xml"},
|
||||
}
|
||||
|
||||
for name, env := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
for key, value := range env {
|
||||
t.Setenv(key, value)
|
||||
}
|
||||
|
||||
_, err := config.Load()
|
||||
require.Error(t, err)
|
||||
|
||||
var validationErrs validator.ValidationErrors
|
||||
require.ErrorAs(t, err, &validationErrs)
|
||||
require.NotEmpty(t, validationErrs)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidPostgresValues(t *testing.T) {
|
||||
path := writeConfig(t, `
|
||||
env: dev
|
||||
postgres:
|
||||
host: db
|
||||
port: 5432
|
||||
database: messenger
|
||||
user: messenger
|
||||
ssl_mode: verify-full
|
||||
max_conns: 10
|
||||
`)
|
||||
|
||||
tests := map[string]map[string]string{
|
||||
"неизвестный ssl mode": {"POSTGRES_SSL_MODE": "bogus"},
|
||||
"plaintext ssl mode": {"POSTGRES_SSL_MODE": "disable"},
|
||||
"unverified ssl mode": {"POSTGRES_SSL_MODE": "require"},
|
||||
"hostname not verified": {"POSTGRES_SSL_MODE": "verify-ca"},
|
||||
"отрицательный max_conns": {"POSTGRES_MAX_CONNS": "-1"},
|
||||
}
|
||||
|
||||
for name, env := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Setenv("APP_CONFIG", path)
|
||||
for key, value := range env {
|
||||
t.Setenv(key, value)
|
||||
}
|
||||
|
||||
_, err := config.Load()
|
||||
require.Error(t, err)
|
||||
|
||||
var validationErrs validator.ValidationErrors
|
||||
require.ErrorAs(t, err, &validationErrs)
|
||||
require.NotEmpty(t, validationErrs)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnparsableValues(t *testing.T) {
|
||||
tests := map[string]map[string]string{
|
||||
"порт не число": {"SERVER_PORT": "не-число"},
|
||||
"timeout не duration": {"SERVER_READ_HEADER_TIMEOUT": "быстро"},
|
||||
}
|
||||
|
||||
for name, env := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
for key, value := range env {
|
||||
t.Setenv(key, value)
|
||||
}
|
||||
|
||||
_, err := config.Load()
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoggerSettings(t *testing.T) {
|
||||
t.Setenv("LOG_LEVEL", "warn")
|
||||
t.Setenv("LOG_FORMAT", "console")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
level, err := logger.ParseLevel(cfg.Log.Level)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, level, cfg.SlogLevel())
|
||||
|
||||
format, err := logger.ParseFormat(cfg.Log.Format)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, format, cfg.LoggerFormat())
|
||||
}
|
||||
|
||||
func TestAddr(t *testing.T) {
|
||||
t.Setenv("SERVER_HOST", "0.0.0.0")
|
||||
t.Setenv("SERVER_PORT", "8080")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "0.0.0.0:8080", cfg.Addr())
|
||||
}
|
||||
|
||||
func TestAddrWithIPv6Host(t *testing.T) {
|
||||
t.Setenv("SERVER_HOST", "::1")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "[::1]:8080", cfg.Addr())
|
||||
}
|
||||
|
||||
func TestLoadIsIndependentOfProcessState(t *testing.T) {
|
||||
t.Setenv("SERVER_PORT", "7070")
|
||||
|
||||
first, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
second, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, first, second)
|
||||
}
|
||||
|
||||
func TestRedisDefaultsDisabled(t *testing.T) {
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.False(t, cfg.Redis.Enabled)
|
||||
assert.Equal(t, "localhost", cfg.Redis.Host)
|
||||
assert.Equal(t, 6379, cfg.Redis.Port)
|
||||
assert.Equal(t, -1, cfg.Redis.MaxRetries)
|
||||
assert.Equal(t, 300*time.Millisecond, cfg.Redis.DialTimeout)
|
||||
assert.Equal(t, 200*time.Millisecond, cfg.Redis.ReadTimeout)
|
||||
assert.Equal(t, 200*time.Millisecond, cfg.Redis.WriteTimeout)
|
||||
assert.False(t, cfg.Cache.Enabled)
|
||||
assert.Equal(t, 5*time.Minute, cfg.Cache.ChatListTTL)
|
||||
assert.Equal(t, 10*time.Second, cfg.Cache.LockTTL)
|
||||
assert.Equal(t, 2*time.Second, cfg.Cache.LockWaitTimeout)
|
||||
}
|
||||
|
||||
func TestRedisEnvOverrides(t *testing.T) {
|
||||
t.Setenv("REDIS_ENABLED", "true")
|
||||
t.Setenv("REDIS_HOST", "cache")
|
||||
t.Setenv("REDIS_PORT", "6380")
|
||||
t.Setenv("REDIS_USERNAME", "api-cache")
|
||||
t.Setenv("REDIS_PASSWORD", "cache-secret")
|
||||
t.Setenv("CACHE_ENABLED", "true")
|
||||
t.Setenv("CACHE_CHAT_LIST_TTL", "1m")
|
||||
t.Setenv("CACHE_LOCK_TTL", "7s")
|
||||
t.Setenv("CACHE_LOCK_WAIT_TIMEOUT", "1500ms")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.True(t, cfg.Redis.Enabled)
|
||||
assert.Equal(t, "cache", cfg.Redis.Host)
|
||||
assert.Equal(t, 6380, cfg.Redis.Port)
|
||||
assert.Equal(t, "api-cache", cfg.Redis.Username)
|
||||
assert.Equal(t, "cache-secret", cfg.Redis.Password)
|
||||
assert.True(t, cfg.Cache.Enabled)
|
||||
assert.Equal(t, time.Minute, cfg.Cache.ChatListTTL)
|
||||
assert.Equal(t, 7*time.Second, cfg.Cache.LockTTL)
|
||||
assert.Equal(t, 1500*time.Millisecond, cfg.Cache.LockWaitTimeout)
|
||||
}
|
||||
|
||||
func TestInvalidCacheTTL(t *testing.T) {
|
||||
for _, key := range []string{
|
||||
"CACHE_CHAT_LIST_TTL",
|
||||
"CACHE_LOCK_TTL",
|
||||
"CACHE_LOCK_WAIT_TIMEOUT",
|
||||
} {
|
||||
for _, value := range []string{"0s", "-1s"} {
|
||||
t.Run(key+"/"+value, func(t *testing.T) {
|
||||
t.Setenv(key, value)
|
||||
_, err := config.Load()
|
||||
require.Error(t, err)
|
||||
var validationErrs validator.ValidationErrors
|
||||
require.ErrorAs(t, err, &validationErrs)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheRequiresRedis(t *testing.T) {
|
||||
t.Setenv("CACHE_ENABLED", "true")
|
||||
|
||||
_, err := config.Load()
|
||||
require.ErrorContains(t, err, "cache.enabled requires redis.enabled")
|
||||
}
|
||||
|
||||
func TestRejectsInsecureDependencyEndpoints(t *testing.T) {
|
||||
for key, value := range map[string]string{
|
||||
"S3_ENDPOINT": "http://seaweedfs:8333",
|
||||
"S3_PUBLIC_ENDPOINT": "http://localhost:8333",
|
||||
"BROKER_URL": "amqp://broker:5672/",
|
||||
} {
|
||||
t.Run(key, func(t *testing.T) {
|
||||
t.Setenv(key, value)
|
||||
_, err := config.Load()
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadOperatorUsesOnlyMountedDatabaseCredential(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "password")
|
||||
require.NoError(t, os.WriteFile(path, []byte("operator-secret\n"), 0o600))
|
||||
t.Setenv("POSTGRES_PASSWORD_FILE", path)
|
||||
t.Setenv("POSTGRES_PASSWORD", "application-secret")
|
||||
t.Setenv("S3_ACCESS_KEY_ID", "")
|
||||
t.Setenv("S3_SECRET_ACCESS_KEY", "")
|
||||
t.Setenv("REDIS_PASSWORD", "")
|
||||
cfg, err := config.LoadOperator()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "operator-secret", cfg.Postgres.Password)
|
||||
assert.Empty(t, cfg.S3.AccessKeyID)
|
||||
assert.Empty(t, cfg.S3.SecretAccessKey)
|
||||
assert.Empty(t, cfg.Redis.Password)
|
||||
}
|
||||
|
||||
func TestLoadOperatorRequiresReadableNonemptyPasswordFile(t *testing.T) {
|
||||
t.Setenv("POSTGRES_PASSWORD_FILE", "")
|
||||
_, err := config.LoadOperator()
|
||||
require.Error(t, err)
|
||||
t.Setenv("POSTGRES_PASSWORD_FILE", filepath.Join(t.TempDir(), "missing"))
|
||||
_, err = config.LoadOperator()
|
||||
require.Error(t, err)
|
||||
path := filepath.Join(t.TempDir(), "empty")
|
||||
require.NoError(t, os.WriteFile(path, []byte("\n"), 0o600))
|
||||
t.Setenv("POSTGRES_PASSWORD_FILE", path)
|
||||
_, err = config.LoadOperator()
|
||||
require.Error(t, err)
|
||||
}
|
||||
Reference in New Issue
Block a user