feat: enforce TLS service identities

This commit is contained in:
2026-11-04 23:05:11 +03:00
parent cb51354889
commit 951e554e06
46 changed files with 681 additions and 165 deletions
+108 -36
View File
@@ -12,41 +12,48 @@ import (
)
type ServerConfig struct {
Address string
DatabaseURL string
CacheURL string
SessionTTL time.Duration
IdempotencyTTL time.Duration
DBMaxConns int32
DBMinConns int32
DBMaxConnectionAge time.Duration
DBMaxConnectionIdle time.Duration
DBHealthCheckPeriod time.Duration
DependencyTimeout time.Duration
RequestTimeout time.Duration
HTTPReadHeaderTimeout time.Duration
HTTPReadTimeout time.Duration
HTTPWriteTimeout time.Duration
HTTPIdleTimeout time.Duration
HTTPShutdownTimeout time.Duration
PasswordMemoryKiB uint32
PasswordIterations uint32
PasswordParallelism uint8
PasswordSaltLength uint32
PasswordKeyLength uint32
SwaggerPort string
S3Endpoint string
S3Region string
S3Bucket string
S3AccessKey string
S3SecretKey string
S3UseTLS bool
S3Timeout time.Duration
AttachmentMaxBytes int64
AttachmentMaxPixels int64
AttachmentBodyMemory int64
AttachmentDecodeMemory int64
PipelineVersion int
Address string
HealthAddress string
MetricsAddress string
TLSCAPath string
TLSCertificatePath string
TLSPrivateKeyPath string
TLSAllowedClientURI string
TLSAllowedMetricsClientURI string
DatabaseURL string
CacheURL string
SessionTTL time.Duration
IdempotencyTTL time.Duration
DBMaxConns int32
DBMinConns int32
DBMaxConnectionAge time.Duration
DBMaxConnectionIdle time.Duration
DBHealthCheckPeriod time.Duration
DependencyTimeout time.Duration
RequestTimeout time.Duration
HTTPReadHeaderTimeout time.Duration
HTTPReadTimeout time.Duration
HTTPWriteTimeout time.Duration
HTTPIdleTimeout time.Duration
HTTPShutdownTimeout time.Duration
PasswordMemoryKiB uint32
PasswordIterations uint32
PasswordParallelism uint8
PasswordSaltLength uint32
PasswordKeyLength uint32
SwaggerPort string
S3Endpoint string
S3Region string
S3Bucket string
S3AccessKey string
S3SecretKey string
S3UseTLS bool
S3Timeout time.Duration
AttachmentMaxBytes int64
AttachmentMaxPixels int64
AttachmentBodyMemory int64
AttachmentDecodeMemory int64
PipelineVersion int
}
type MigrationConfig struct {
@@ -111,6 +118,34 @@ func LoadServer() (ServerConfig, error) {
if err != nil {
return ServerConfig{}, err
}
healthAddress, err := loopbackAddress(values, "server.health_address")
if err != nil {
return ServerConfig{}, err
}
metricsAddress, err := nonLoopbackAddress(values, "server.metrics_address")
if err != nil {
return ServerConfig{}, err
}
tlsCAPath, err := requiredString(values, "server.tls.ca_path")
if err != nil {
return ServerConfig{}, err
}
tlsCertificatePath, err := requiredString(values, "server.tls.certificate_path")
if err != nil {
return ServerConfig{}, err
}
tlsPrivateKeyPath, err := requiredString(values, "server.tls.private_key_path")
if err != nil {
return ServerConfig{}, err
}
tlsAllowedClientURI, err := requiredString(values, "server.tls.allowed_client_uri")
if err != nil {
return ServerConfig{}, err
}
tlsAllowedMetricsClientURI, err := requiredString(values, "server.tls.allowed_metrics_client_uri")
if err != nil {
return ServerConfig{}, err
}
database, err := loadDatabaseConfig(values)
if err != nil {
return ServerConfig{}, err
@@ -216,7 +251,11 @@ func LoadServer() (ServerConfig, error) {
}
return ServerConfig{
Address: net.JoinHostPort(host, port), DatabaseURL: database.url, CacheURL: cacheURL,
Address: net.JoinHostPort(host, port), HealthAddress: healthAddress, MetricsAddress: metricsAddress,
TLSCAPath: tlsCAPath, TLSCertificatePath: tlsCertificatePath,
TLSPrivateKeyPath: tlsPrivateKeyPath, TLSAllowedClientURI: tlsAllowedClientURI,
TLSAllowedMetricsClientURI: tlsAllowedMetricsClientURI,
DatabaseURL: database.url, CacheURL: cacheURL,
SessionTTL: sessionTTL, IdempotencyTTL: idempotencyTTL,
DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle,
@@ -371,6 +410,39 @@ func requiredPort(values *viper.Viper, name string) (string, error) {
return value, nil
}
func loopbackAddress(values *viper.Viper, name string) (string, error) {
value, err := requiredString(values, name)
if err != nil {
return "", err
}
host, port, err := net.SplitHostPort(value)
if err != nil || host != "127.0.0.1" {
return "", fmt.Errorf("%s: must use 127.0.0.1 with an explicit port", name)
}
if _, err := integerValue(port, 1, 65535); err != nil {
return "", fmt.Errorf("%s: %w", name, err)
}
return net.JoinHostPort(host, port), nil
}
func nonLoopbackAddress(values *viper.Viper, name string) (string, error) {
value, err := requiredString(values, name)
if err != nil {
return "", err
}
host, port, err := net.SplitHostPort(value)
if err != nil || host == "" || strings.EqualFold(host, "localhost") {
return "", fmt.Errorf("%s: must use a non-loopback host with an explicit port", name)
}
if address := net.ParseIP(host); address != nil && address.IsLoopback() {
return "", fmt.Errorf("%s: must use a non-loopback host with an explicit port", name)
}
if _, err := integerValue(port, 1, 65535); err != nil {
return "", fmt.Errorf("%s: %w", name, err)
}
return net.JoinHostPort(host, port), nil
}
func duration(values *viper.Viper, name string, minimum, maximum time.Duration) (time.Duration, error) {
value, err := requiredString(values, name)
if err != nil {
+36
View File
@@ -46,6 +46,34 @@ func TestLoadValuesRejectsUnknownVersion(t *testing.T) {
require.ErrorContains(t, err, "version: must be 1")
}
func TestLoadServerLoadsTLSAndHealthSettings(t *testing.T) {
setConfigEnvironment(t, validTestConfig)
settings, err := LoadServer()
require.NoError(t, err)
require.Equal(t, "127.0.0.1:8082", settings.HealthAddress)
require.Equal(t, "0.0.0.0:9091", settings.MetricsAddress)
require.Equal(t, "/run/security/internal-ca/ca.crt", settings.TLSCAPath)
require.Equal(t, "spiffe://mtusi/lab7/load-balancer", settings.TLSAllowedClientURI)
require.Equal(t, "spiffe://mtusi/lab7/prometheus", settings.TLSAllowedMetricsClientURI)
}
func TestLoadServerRejectsNonLoopbackHealthAddress(t *testing.T) {
content := strings.Replace(validTestConfig, "health_address: 127.0.0.1:8082", "health_address: 0.0.0.0:8082", 1)
setConfigEnvironment(t, content)
_, err := LoadServer()
require.ErrorContains(t, err, "server.health_address: must use 127.0.0.1")
}
func TestLoadServerRejectsLoopbackMetricsAddress(t *testing.T) {
content := strings.Replace(validTestConfig, "metrics_address: 0.0.0.0:9091", "metrics_address: 127.0.0.1:9091", 1)
setConfigEnvironment(t, content)
_, err := LoadServer()
require.ErrorContains(t, err, "server.metrics_address: must use a non-loopback host")
}
func setConfigEnvironment(t *testing.T, content string) {
t.Helper()
path := filepath.Join(t.TempDir(), "messenger.yaml")
@@ -64,6 +92,14 @@ func setConfigEnvironment(t *testing.T, content string) {
const validTestConfig = `version: 1
server:
health_address: 127.0.0.1:8082
metrics_address: 0.0.0.0:9091
tls:
ca_path: /run/security/internal-ca/ca.crt
certificate_path: /run/security/api/tls.crt
private_key_path: /run/security/api/tls.key
allowed_client_uri: spiffe://mtusi/lab7/load-balancer
allowed_metrics_client_uri: spiffe://mtusi/lab7/prometheus
session_store: valkey
session_ttl: 1h
idempotency_ttl: 24h
+18 -11
View File
@@ -12,17 +12,24 @@ import (
const supportedConfigVersion = 1
var environmentKeys = map[string]string{
"server.host": "APP_HOST",
"server.port": "APP_PORT",
"server.swagger_port": "SWAGGER_PORT",
"database.url": "DATABASE_URL",
"cache.url": "CACHE_URL",
"object_storage.endpoint": "S3_ENDPOINT",
"object_storage.region": "S3_REGION",
"object_storage.bucket": "S3_BUCKET",
"object_storage.access_key": "S3_ACCESS_KEY",
"object_storage.secret_key": "S3_SECRET_KEY",
"broker.url": "BROKER_URL",
"server.host": "APP_HOST",
"server.port": "APP_PORT",
"server.health_address": "APP_HEALTH_ADDRESS",
"server.metrics_address": "APP_METRICS_ADDRESS",
"server.tls.ca_path": "APP_TLS_CA_PATH",
"server.tls.certificate_path": "APP_TLS_CERTIFICATE_PATH",
"server.tls.private_key_path": "APP_TLS_PRIVATE_KEY_PATH",
"server.tls.allowed_client_uri": "APP_TLS_ALLOWED_CLIENT_URI",
"server.tls.allowed_metrics_client_uri": "APP_TLS_ALLOWED_METRICS_CLIENT_URI",
"server.swagger_port": "SWAGGER_PORT",
"database.url": "DATABASE_URL",
"cache.url": "CACHE_URL",
"object_storage.endpoint": "S3_ENDPOINT",
"object_storage.region": "S3_REGION",
"object_storage.bucket": "S3_BUCKET",
"object_storage.access_key": "S3_ACCESS_KEY",
"object_storage.secret_key": "S3_SECRET_KEY",
"broker.url": "BROKER_URL",
}
func loadValues() (*viper.Viper, error) {