forked from mtusi2026/mtusi2026lab7
lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
+59
-12
@@ -17,6 +17,8 @@ import (
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"mtusi-messenger/internal/logger"
|
||||
"mtusi-messenger/internal/platform/secretfile"
|
||||
"mtusi-messenger/internal/platform/tlsconfig"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -54,9 +56,7 @@ type Broker struct {
|
||||
ConfirmTimeout time.Duration `mapstructure:"confirm_timeout"`
|
||||
Heartbeat time.Duration `mapstructure:"heartbeat"`
|
||||
Exchange string `mapstructure:"exchange" validate:"required"`
|
||||
DLX string `mapstructure:"dlx" validate:"required"`
|
||||
Queue string `mapstructure:"queue" validate:"required"`
|
||||
DLQ string `mapstructure:"dlq" validate:"required"`
|
||||
Prefetch int `mapstructure:"prefetch" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
@@ -142,6 +142,7 @@ 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"`
|
||||
@@ -180,7 +181,7 @@ type Postgres struct {
|
||||
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,oneof=disable require verify-ca verify-full"`
|
||||
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"`
|
||||
@@ -203,7 +204,11 @@ func (p Postgres) DSN() string {
|
||||
}
|
||||
|
||||
query := url.Values{}
|
||||
query.Set("sslmode", p.SSLMode)
|
||||
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()
|
||||
@@ -217,8 +222,8 @@ var defaults = map[string]any{
|
||||
"server.read_timeout": "60s",
|
||||
"server.shutdown_timeout": "10s",
|
||||
"server.max_body_bytes": 262144,
|
||||
"s3.endpoint": "http://localhost:8333",
|
||||
"s3.public_endpoint": "http://localhost:8333",
|
||||
"s3.endpoint": "https://localhost:8333",
|
||||
"s3.public_endpoint": "https://localhost:8333",
|
||||
"s3.region": "us-east-1",
|
||||
"s3.bucket": "messenger-attachments",
|
||||
"s3.access_key_id": "",
|
||||
@@ -234,9 +239,17 @@ var defaults = map[string]any{
|
||||
"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",
|
||||
@@ -253,15 +266,13 @@ var defaults = map[string]any{
|
||||
"broker.confirm_timeout": "5s",
|
||||
"broker.heartbeat": "10s",
|
||||
"broker.exchange": "attachments.jobs",
|
||||
"broker.dlx": "attachments.dlx",
|
||||
"broker.queue": "attachment.process.v1",
|
||||
"broker.dlq": "attachment.process.dead",
|
||||
"broker.prefetch": 1,
|
||||
"worker.concurrency": 1,
|
||||
"worker.prefetch": 1,
|
||||
"worker.shutdown_timeout": "30s",
|
||||
"worker.health_addr": ":8081",
|
||||
"relay.health_addr": ":8082",
|
||||
"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,
|
||||
@@ -282,6 +293,20 @@ var defaults = map[string]any{
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -308,6 +333,17 @@ func Load() (Config, error) {
|
||||
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 {
|
||||
@@ -350,9 +386,20 @@ func (c Config) validateDependencies() error {
|
||||
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 != "" {
|
||||
if _, err := url.Parse(c.Broker.URL); err != nil {
|
||||
return fmt.Errorf("validate config: broker.url: %w", err)
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
@@ -14,19 +15,6 @@ import (
|
||||
"mtusi-messenger/internal/logger"
|
||||
)
|
||||
|
||||
func TestDefaults(t *testing.T) {
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "0.0.0.0", cfg.Server.Host)
|
||||
assert.Equal(t, 8080, cfg.Server.Port)
|
||||
assert.Equal(t, 10*time.Second, cfg.Server.ReadHeaderTimeout)
|
||||
assert.Equal(t, 10*time.Second, cfg.Server.ShutdownTimeout)
|
||||
assert.Equal(t, "info", cfg.Log.Level)
|
||||
assert.Equal(t, "json", cfg.Log.Format)
|
||||
assert.Equal(t, config.Postgres{}, cfg.Postgres, "postgres defaults live in the adapter")
|
||||
}
|
||||
|
||||
func TestEnvOverridesDefaults(t *testing.T) {
|
||||
t.Setenv("SERVER_HOST", "127.0.0.1")
|
||||
t.Setenv("SERVER_PORT", "9090")
|
||||
@@ -47,16 +35,30 @@ func TestEnvOverridesDefaults(t *testing.T) {
|
||||
}
|
||||
|
||||
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: "disable",
|
||||
SSLMode: "verify-full",
|
||||
}
|
||||
|
||||
assert.Equal(t, "postgres://user:p%40ss%3Aw%2Frd@db:5432/app?sslmode=disable", cfg.DSN())
|
||||
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 {
|
||||
@@ -85,7 +87,7 @@ postgres:
|
||||
database: app
|
||||
user: app
|
||||
password: secret
|
||||
ssl_mode: disable
|
||||
ssl_mode: verify-full
|
||||
max_conns: 7
|
||||
min_conns: 2
|
||||
max_conn_lifetime: 2h
|
||||
@@ -128,7 +130,7 @@ postgres:
|
||||
database: app
|
||||
user: app
|
||||
password: file
|
||||
ssl_mode: disable
|
||||
ssl_mode: verify-full
|
||||
`)
|
||||
|
||||
t.Setenv("APP_CONFIG", path)
|
||||
@@ -188,12 +190,15 @@ postgres:
|
||||
port: 5432
|
||||
database: messenger
|
||||
user: messenger
|
||||
ssl_mode: disable
|
||||
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"},
|
||||
}
|
||||
|
||||
@@ -300,6 +305,8 @@ 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")
|
||||
@@ -311,6 +318,8 @@ func TestRedisEnvOverrides(t *testing.T) {
|
||||
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)
|
||||
@@ -341,3 +350,47 @@ func TestCacheRequiresRedis(t *testing.T) {
|
||||
_, 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