From 39a1b48eebc48cdfd5a437b9910972ca4dee9dc9 Mon Sep 17 00:00:00 2001 From: Timo Ruohomaki Date: Sun, 8 Nov 2026 21:33:59 +0200 Subject: [PATCH 1/2] MOS-13: Add pgx pool, postgres config block and docker-compose internal/store/postgres/pool.go builds a pgxpool with max/min conns, health checks and a connect timeout, and pings at creation so bad settings fail at startup. Outside development every connection must use sslmode=verify-full (checked on the resulting TLS settings, so PGSSLMODE counts too). Parse errors are withheld because pgx redacts passwords only best-effort; logs name host, database and user only. Config gains a postgres block; DATABASE_URL (backend01 .env name) overrides postgres.url, POSTGRES_* override pool settings, and without a URL the standard PG* variables apply. The generated config never contains a URL. The server connects at startup when a database is configured and exits if it cannot; repositories stay in memory until MOS-16. docker-compose.yml runs postgres:17 on 127.0.0.1 with an openmos_test database for the store tests. Docs cover the config and setup. Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +- dev/postgres-init/01-test-database.sql | 3 + doc/developer-reference.md | 26 ++- docker-compose.yml | 28 +++ src/database.go | 44 +++++ src/internal/config/config.go | 11 ++ src/internal/config/defaults.go | 7 + src/internal/config/env.go | 17 ++ src/internal/config/load_test.go | 4 + src/internal/config/postgres_test.go | 55 ++++++ src/internal/store/postgres/pool.go | 137 +++++++++++++++ src/internal/store/postgres/pool_test.go | 188 +++++++++++++++++++++ src/internal/store/postgres/testdb_test.go | 15 +- src/main.go | 4 + 14 files changed, 538 insertions(+), 8 deletions(-) create mode 100644 dev/postgres-init/01-test-database.sql create mode 100644 docker-compose.yml create mode 100644 src/database.go create mode 100644 src/internal/config/postgres_test.go create mode 100644 src/internal/store/postgres/pool.go create mode 100644 src/internal/store/postgres/pool_test.go diff --git a/README.md b/README.md index 478b68d..2050741 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,11 @@ server: readtimeout: 5s writetimeout: 5s shutdowntimeout: 30s +postgres: # url is a secret: prefer the DATABASE_URL env var + maxconns: 10 + minconns: 1 + connecttimeout: 5s + healthcheckperiod: 30s mos: id: mos01.station.com heartbeatinterval: 30s @@ -106,7 +111,7 @@ go build -o openmos ## Requirements - Go 1.25 or later -- PostgreSQL 17 (once the PostgreSQL store lands; until then no database is needed) +- PostgreSQL 17, optional until the PostgreSQL store is wired in (MOS-16). For local development, `docker compose up -d` starts one (see `docker-compose.yml`) - Network access on port 10540 (default MOS port) ## License diff --git a/dev/postgres-init/01-test-database.sql b/dev/postgres-init/01-test-database.sql new file mode 100644 index 0000000..9636976 --- /dev/null +++ b/dev/postgres-init/01-test-database.sql @@ -0,0 +1,3 @@ +-- Runs once, when the volume is first created. The store tests drop and +-- recreate the openmos schema, so they get a database of their own. +CREATE DATABASE openmos_test; diff --git a/doc/developer-reference.md b/doc/developer-reference.md index 6bb136b..6cc4252 100644 --- a/doc/developer-reference.md +++ b/doc/developer-reference.md @@ -54,7 +54,7 @@ OpenMOS follows a **Clean Layered Architecture** with clear separation of concer | **Server** | `internal/server/` | TCP connections, client management, heartbeat monitoring | | **Service** | `internal/service/` | Business logic, MOS operations, event publishing | | **Repository** | `internal/repository/` | Data access abstraction, CRUD operations | -| **Store** | `internal/store/postgres/` | PostgreSQL schema migrations (pool and repositories to follow) | +| **Store** | `internal/store/postgres/` | PostgreSQL connection pool and schema migrations (repositories to follow) | | **Model** | `internal/model/` | Domain entities and value objects | | **XML** | `internal/xml/` | Message parsing and serialization | | **Events** | `internal/events/` | Pub-sub event bus for real-time notifications | @@ -88,6 +88,7 @@ OpenMOS/ │ │ │ │ │ ├── store/postgres/ │ │ │ ├── migrate.go # Goose migrations (embedded SQL) +│ │ │ ├── pool.go # pgx connection pool, TLS rules │ │ │ └── migrations/ # Schema migrations (00001_init.sql, ...) │ │ │ │ │ ├── server/ @@ -282,6 +283,13 @@ server: writetimeout: 5s # Write timeout duration shutdowntimeout: 30s # Graceful shutdown timeout +postgres: + url: "" # Connection URL; a secret, so use DATABASE_URL instead + maxconns: 10 # Pool size (env POSTGRES_MAX_CONNS) + minconns: 1 # Connections kept open (env POSTGRES_MIN_CONNS) + connecttimeout: 5s # Connect and startup ping timeout (POSTGRES_CONNECT_TIMEOUT) + healthcheckperiod: 30s # Idle connection health checks (POSTGRES_HEALTH_CHECK_PERIOD) + mos: id: mos01.station.com # MOS server identifier heartbeatinterval: 30s # Heartbeat interval @@ -299,6 +307,19 @@ sentry: tracessamplerate: 0.2 # Performance trace sampling rate ``` +### Database connection + +- `DATABASE_URL` (the backend01 `.env` name) overrides `postgres.url`. With + neither set, the standard `PG*` variables (`PGHOST`, `PGUSER`, ...) are used; + with nothing set, the server runs without a database. +- When a database is configured, the server connects and pings it at startup + and exits if that fails. Logs and errors name host, database and user, never + the password. +- Outside `app.environment: development`, connections must use + `sslmode=verify-full` with `sslrootcert` pointing at the server CA (on the + server, `/secrets/aiven-ca.pem`). Connect to Aiven directly, not through + its PgBouncer pool. + ## Development Guidelines ### Code Organization @@ -323,8 +344,7 @@ sentry: They drop and recreate the `openmos` schema, so never point it at real data: ```bash - docker run -d --name openmos-pg -p 127.0.0.1:5432:5432 \ - -e POSTGRES_USER=openmos -e POSTGRES_PASSWORD=openmos -e POSTGRES_DB=openmos_test postgres:17 + docker compose up -d # from the repository root; also creates openmos_test export OPENMOS_TEST_DATABASE_URL='postgres://openmos:openmos@localhost:5432/openmos_test?sslmode=disable' go test ./internal/store/... ``` diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..544536f --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,28 @@ +# Local PostgreSQL for development and tests only. Production uses Aiven +# (verify-full TLS, separate roles); see doc/database-migration.md. +# +# docker compose up -d +# export DATABASE_URL='postgres://openmos:openmos@localhost:5432/openmos?sslmode=disable' +# export OPENMOS_TEST_DATABASE_URL='postgres://openmos:openmos@localhost:5432/openmos_test?sslmode=disable' +# +# sslmode=disable is accepted only with APP_ENV=development (the default). +services: + postgres: + image: postgres:17 + environment: + POSTGRES_USER: openmos + POSTGRES_PASSWORD: openmos # local only, not a secret + POSTGRES_DB: openmos + ports: + - "127.0.0.1:5432:5432" + volumes: + - pgdata:/var/lib/postgresql/data + - ./dev/postgres-init:/docker-entrypoint-initdb.d:ro + healthcheck: + test: ["CMD", "pg_isready", "-U", "openmos", "-d", "openmos"] + interval: 5s + timeout: 5s + retries: 10 + +volumes: + pgdata: diff --git a/src/database.go b/src/database.go new file mode 100644 index 0000000..dd3fbcb --- /dev/null +++ b/src/database.go @@ -0,0 +1,44 @@ +package main + +import ( + "context" + + "airshift/openmos/internal/config" + "airshift/openmos/internal/store/postgres" + "airshift/openmos/pkg/logger" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// connectDatabase opens the PostgreSQL pool if a database is configured +// (DATABASE_URL, postgres.url or the PG* variables) and exits the process if +// it cannot connect. It returns nil when no database is configured. +// +// The repositories still use the in-memory store until MOS-16. The pool is +// opened now so that bad settings or credentials fail at startup. +func connectDatabase(ctx context.Context, cfg *config.Config, log *logger.SentryLogger) *pgxpool.Pool { + if !postgres.Configured(cfg.Postgres.URL) { + log.Info("No PostgreSQL configured (DATABASE_URL or PG* variables); skipping database connection") + return nil + } + + pool, err := postgres.NewPool(ctx, postgres.PoolOptions{ + URL: cfg.Postgres.URL, + MaxConns: cfg.Postgres.MaxConns, + MinConns: cfg.Postgres.MinConns, + ConnectTimeout: cfg.Postgres.ConnectTimeout, + HealthCheckPeriod: cfg.Postgres.HealthCheckPeriod, + // Only local development may connect without verify-full + AllowInsecureTLS: cfg.App.Environment == "development", + }) + if err != nil { + // The error names host, database and user, never the password + log.CaptureException(err, map[string]string{ + "component": "database", + "action": "connect", + }, nil) + log.Fatalf("Failed to connect to PostgreSQL: %v", err) + } + log.Infof("Connected to PostgreSQL %s", postgres.Describe(pool.Config())) + return pool +} diff --git a/src/internal/config/config.go b/src/internal/config/config.go index 6a830b9..2e8bb49 100644 --- a/src/internal/config/config.go +++ b/src/internal/config/config.go @@ -23,6 +23,17 @@ type Config struct { ShutdownTimeout time.Duration } + // PostgreSQL configuration. URL is a secret (it holds the password): set + // it with DATABASE_URL or in a local, gitignored config.yaml. Without a + // URL, the standard PG* environment variables are used. + Postgres struct { + URL string + MaxConns int32 + MinConns int32 + ConnectTimeout time.Duration + HealthCheckPeriod time.Duration + } + // MOS configuration MOS struct { // MOS ID of this server, used in MOS messages diff --git a/src/internal/config/defaults.go b/src/internal/config/defaults.go index 1791608..3f4178e 100644 --- a/src/internal/config/defaults.go +++ b/src/internal/config/defaults.go @@ -19,6 +19,13 @@ func GenerateDefaultConfig(filePath string) error { config.Server.WriteTimeout = 5 * time.Second config.Server.ShutdownTimeout = 30 * time.Second + // PostgreSQL config. The URL stays empty: it is a secret and belongs in + // DATABASE_URL, not in a generated file. + config.Postgres.MaxConns = 10 + config.Postgres.MinConns = 1 + config.Postgres.ConnectTimeout = 5 * time.Second + config.Postgres.HealthCheckPeriod = 30 * time.Second + // MOS config config.MOS.ID = "OpenMOS_Server" config.MOS.HeartbeatInterval = 30 * time.Second diff --git a/src/internal/config/env.go b/src/internal/config/env.go index 0909ca4..3afd566 100644 --- a/src/internal/config/env.go +++ b/src/internal/config/env.go @@ -33,6 +33,23 @@ func applyEnvOverrides(config *Config, yamlLoaded bool) { config.Server.ShutdownTimeout = getEnvAsDuration("SERVER_SHUTDOWN_TIMEOUT", getDefaultDuration(config.Server.ShutdownTimeout, 30*time.Second)) } + // PostgreSQL config. DATABASE_URL matches the backend01 .env convention. + if envVal := getEnv("DATABASE_URL", ""); envVal != "" || !yamlLoaded { + config.Postgres.URL = getEnv("DATABASE_URL", config.Postgres.URL) + } + if envVal := getEnv("POSTGRES_MAX_CONNS", ""); envVal != "" || !yamlLoaded { + config.Postgres.MaxConns = int32(getEnvAsInt("POSTGRES_MAX_CONNS", getDefaultInt(int(config.Postgres.MaxConns), 10))) + } + if envVal := getEnv("POSTGRES_MIN_CONNS", ""); envVal != "" || !yamlLoaded { + config.Postgres.MinConns = int32(getEnvAsInt("POSTGRES_MIN_CONNS", getDefaultInt(int(config.Postgres.MinConns), 1))) + } + if envVal := getEnv("POSTGRES_CONNECT_TIMEOUT", ""); envVal != "" || !yamlLoaded { + config.Postgres.ConnectTimeout = getEnvAsDuration("POSTGRES_CONNECT_TIMEOUT", getDefaultDuration(config.Postgres.ConnectTimeout, 5*time.Second)) + } + if envVal := getEnv("POSTGRES_HEALTH_CHECK_PERIOD", ""); envVal != "" || !yamlLoaded { + config.Postgres.HealthCheckPeriod = getEnvAsDuration("POSTGRES_HEALTH_CHECK_PERIOD", getDefaultDuration(config.Postgres.HealthCheckPeriod, 30*time.Second)) + } + // MOS config if envVal := getEnv("MOS_ID", ""); envVal != "" || !yamlLoaded { config.MOS.ID = getEnv("MOS_ID", getDefaultString(config.MOS.ID, "OpenMOS_Server")) diff --git a/src/internal/config/load_test.go b/src/internal/config/load_test.go index a43af4a..b0d8a6f 100644 --- a/src/internal/config/load_test.go +++ b/src/internal/config/load_test.go @@ -11,6 +11,8 @@ var configEnvKeys = []string{ "CONFIG_FILE", "APP_NAME", "APP_VERSION", "APP_ENV", "SERVER_HOST", "SERVER_PORT", "SERVER_READ_TIMEOUT", "SERVER_WRITE_TIMEOUT", "SERVER_SHUTDOWN_TIMEOUT", + "DATABASE_URL", "POSTGRES_MAX_CONNS", "POSTGRES_MIN_CONNS", "POSTGRES_CONNECT_TIMEOUT", "POSTGRES_HEALTH_CHECK_PERIOD", + "PGHOST", "PGPORT", "PGDATABASE", "PGUSER", "PGPASSWORD", "PGSSLMODE", "PGSSLROOTCERT", "MOS_ID", "MOS_HEARTBEAT_INTERVAL", "MOS_CLIENT_TIMEOUT", "LOG_LEVEL", "SENTRY_DSN", "SENTRY_ENV", "SENTRY_DEBUG", "SENTRY_ATTACH_STACKTRACE", @@ -47,6 +49,8 @@ func TestLoadConfigDefaultsWithoutYAML(t *testing.T) { want.Server.Host, want.Server.Port = "0.0.0.0", 10540 want.Server.ReadTimeout, want.Server.WriteTimeout = 5*time.Second, 5*time.Second want.Server.ShutdownTimeout = 30 * time.Second + want.Postgres.MaxConns, want.Postgres.MinConns = 10, 1 + want.Postgres.ConnectTimeout, want.Postgres.HealthCheckPeriod = 5*time.Second, 30*time.Second want.MOS.ID = "OpenMOS_Server" want.MOS.HeartbeatInterval, want.MOS.ClientTimeout = 30*time.Second, 2*time.Minute want.Logging.Level = "info" diff --git a/src/internal/config/postgres_test.go b/src/internal/config/postgres_test.go new file mode 100644 index 0000000..c291fb3 --- /dev/null +++ b/src/internal/config/postgres_test.go @@ -0,0 +1,55 @@ +package config + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +// DATABASE_URL (the backend01 .env name) overrides postgres.url in YAML, +// and the other postgres fields come from YAML. +func TestDatabaseURLOverridesYAML(t *testing.T) { + dir := isolate(t) + path := filepath.Join(dir, "config.yaml") + yamlDoc := "postgres:\n url: postgres://from-yaml/openmos\n maxconns: 4\n connecttimeout: 3s\n" + if err := os.WriteFile(path, []byte(yamlDoc), 0o600); err != nil { + t.Fatal(err) + } + + cfg, err := LoadConfig() + if err != nil { + t.Fatalf("LoadConfig: %v", err) + } + if cfg.Postgres.URL != "postgres://from-yaml/openmos" || cfg.Postgres.MaxConns != 4 || + cfg.Postgres.ConnectTimeout != 3*time.Second { + t.Errorf("YAML postgres block not loaded: %+v", cfg.Postgres) + } + + t.Setenv("DATABASE_URL", "postgres://from-env/openmos") + t.Setenv("POSTGRES_MAX_CONNS", "7") + cfg, err = LoadConfig() + if err != nil { + t.Fatalf("LoadConfig: %v", err) + } + if cfg.Postgres.URL != "postgres://from-env/openmos" || cfg.Postgres.MaxConns != 7 { + t.Errorf("env did not override: URL %q, MaxConns %d", cfg.Postgres.URL, cfg.Postgres.MaxConns) + } +} + +// The generated default config never contains a database URL. +func TestGeneratedConfigHasNoDatabaseURL(t *testing.T) { + dir := isolate(t) + path := filepath.Join(dir, "generated.yaml") + if err := GenerateDefaultConfig(path); err != nil { + t.Fatalf("GenerateDefaultConfig: %v", err) + } + t.Setenv("CONFIG_FILE", path) + cfg, err := LoadConfig() + if err != nil { + t.Fatalf("LoadConfig: %v", err) + } + if cfg.Postgres.URL != "" || cfg.Postgres.MaxConns != 10 { + t.Errorf("generated postgres block = %+v, want empty URL and defaults", cfg.Postgres) + } +} diff --git a/src/internal/store/postgres/pool.go b/src/internal/store/postgres/pool.go new file mode 100644 index 0000000..a1bbc79 --- /dev/null +++ b/src/internal/store/postgres/pool.go @@ -0,0 +1,137 @@ +package postgres + +import ( + "context" + "crypto/tls" + "errors" + "fmt" + "os" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +// Pool defaults, used for options left at zero. +const ( + DefaultMaxConns = 10 + DefaultMinConns = 1 + DefaultConnectTimeout = 5 * time.Second + DefaultHealthCheckPeriod = 30 * time.Second +) + +// PoolOptions configures the connection pool. Zero values get the defaults. +type PoolOptions struct { + // URL is a libpq connection string or postgres:// URL. It holds the + // password, so it is never logged. Empty means the PG* environment + // variables alone (PGHOST, PGUSER, PGSSLMODE, ...). + URL string + + MaxConns int32 + MinConns int32 + ConnectTimeout time.Duration + HealthCheckPeriod time.Duration + + // AllowInsecureTLS permits any sslmode. Without it, every connection + // must use sslmode=verify-full. Only local development should set it. + AllowInsecureTLS bool +} + +// Configured reports whether a database is configured, through a URL or +// the PG* environment variables. +func Configured(url string) bool { + if url != "" { + return true + } + for _, k := range []string{"PGHOST", "PGDATABASE", "PGSERVICE"} { + if os.Getenv(k) != "" { + return true + } + } + return false +} + +// errInvalidSettings replaces pgx parse errors, which redact passwords only +// on a best-effort basis. +var errInvalidSettings = errors.New("invalid PostgreSQL connection settings (details withheld because they may contain the password)") + +// ParsePoolConfig builds a pool configuration from opts and checks it. It +// does not connect. +func ParsePoolConfig(opts PoolOptions) (*pgxpool.Config, error) { + cfg, err := pgxpool.ParseConfig(opts.URL) + if err != nil { + return nil, errInvalidSettings + } + + cfg.MaxConns = valueOr(opts.MaxConns, DefaultMaxConns) + cfg.MinConns = valueOr(opts.MinConns, DefaultMinConns) + if cfg.MinConns > cfg.MaxConns { + return nil, fmt.Errorf("PostgreSQL min conns (%d) exceeds max conns (%d)", cfg.MinConns, cfg.MaxConns) + } + cfg.HealthCheckPeriod = valueOr(opts.HealthCheckPeriod, DefaultHealthCheckPeriod) + // A connect_timeout in the URL or PGCONNECT_TIMEOUT takes precedence + if cfg.ConnConfig.ConnectTimeout == 0 { + cfg.ConnConfig.ConnectTimeout = valueOr(opts.ConnectTimeout, DefaultConnectTimeout) + } + + if !opts.AllowInsecureTLS { + if err := requireVerifyFull(cfg.ConnConfig); err != nil { + return nil, err + } + } + return cfg, nil +} + +// NewPool creates a connection pool and pings the database, so a bad +// configuration fails at startup. Errors never include the password. +func NewPool(ctx context.Context, opts PoolOptions) (*pgxpool.Pool, error) { + cfg, err := ParsePoolConfig(opts) + if err != nil { + return nil, err + } + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + return nil, fmt.Errorf("create PostgreSQL pool for %s: %w", Describe(cfg), err) + } + pingCtx, cancel := context.WithTimeout(ctx, cfg.ConnConfig.ConnectTimeout) + defer cancel() + if err := pool.Ping(pingCtx); err != nil { + pool.Close() + return nil, fmt.Errorf("connect to PostgreSQL %s: %w", Describe(cfg), err) + } + return pool, nil +} + +// Describe identifies the database for logs: host, port, database and +// user, never the password. +func Describe(cfg *pgxpool.Config) string { + c := cfg.ConnConfig + return fmt.Sprintf("%s:%d/%s (user %s)", c.Host, c.Port, c.Database, c.User) +} + +// requireVerifyFull fails unless every host and fallback uses TLS with +// certificate and host name verification. pgx does not keep the sslmode, +// so it is read from the resulting TLS settings: disable has none, allow +// and prefer fall back to plain connections, and require and verify-ca +// skip host name verification (InsecureSkipVerify). +func requireVerifyFull(c *pgx.ConnConfig) error { + configs := []*tls.Config{c.TLSConfig} + for _, fb := range c.Fallbacks { + configs = append(configs, fb.TLSConfig) + } + for _, t := range configs { + if t == nil || t.InsecureSkipVerify { + return errors.New("PostgreSQL connections must use sslmode=verify-full with sslrootcert " + + "set to the server CA outside local development") + } + } + return nil +} + +func valueOr[T comparable](v, def T) T { + var zero T + if v == zero { + return def + } + return v +} diff --git a/src/internal/store/postgres/pool_test.go b/src/internal/store/postgres/pool_test.go new file mode 100644 index 0000000..9103a4a --- /dev/null +++ b/src/internal/store/postgres/pool_test.go @@ -0,0 +1,188 @@ +package postgres + +import ( + "crypto/tls" + "errors" + "net/url" + "os" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" +) + +// clearPGEnv unsets the PG* variables pgx reads, so the developer's own +// environment cannot change the result. +func clearPGEnv(t *testing.T) { + t.Helper() + for _, k := range []string{"PGHOST", "PGPORT", "PGDATABASE", "PGUSER", "PGPASSWORD", + "PGSERVICE", "PGSSLMODE", "PGSSLROOTCERT", "PGCONNECT_TIMEOUT", "PGSSLSNI"} { + t.Setenv(k, "") + os.Unsetenv(k) + } +} + +func TestParsePoolConfigDefaults(t *testing.T) { + clearPGEnv(t) + cfg, err := ParsePoolConfig(PoolOptions{URL: "postgres://u@db.example/openmos?sslmode=verify-full"}) + if err != nil { + t.Fatal(err) + } + if cfg.MaxConns != DefaultMaxConns || cfg.MinConns != DefaultMinConns || + cfg.HealthCheckPeriod != DefaultHealthCheckPeriod || cfg.ConnConfig.ConnectTimeout != DefaultConnectTimeout { + t.Errorf("defaults not applied: max %d, min %d, health %v, timeout %v", + cfg.MaxConns, cfg.MinConns, cfg.HealthCheckPeriod, cfg.ConnConfig.ConnectTimeout) + } + + // Options override the defaults, and connect_timeout in the URL wins + cfg, err = ParsePoolConfig(PoolOptions{ + URL: "postgres://u@db.example/openmos?sslmode=verify-full&connect_timeout=2", + MaxConns: 4, MinConns: 2, ConnectTimeout: 9 * time.Second, HealthCheckPeriod: time.Minute, + }) + if err != nil { + t.Fatal(err) + } + if cfg.MaxConns != 4 || cfg.MinConns != 2 || cfg.HealthCheckPeriod != time.Minute || + cfg.ConnConfig.ConnectTimeout != 2*time.Second { + t.Errorf("options not applied: max %d, min %d, health %v, timeout %v", + cfg.MaxConns, cfg.MinConns, cfg.HealthCheckPeriod, cfg.ConnConfig.ConnectTimeout) + } + + if _, err := ParsePoolConfig(PoolOptions{URL: "postgres://u@db.example/openmos?sslmode=verify-full", + MaxConns: 2, MinConns: 3}); err == nil { + t.Error("min conns above max conns accepted") + } +} + +func TestParsePoolConfigRequiresVerifyFull(t *testing.T) { + for _, tc := range []struct { + name, url, pgsslmode string + ok bool + }{ + {"verify-full", "postgres://u@db.example/openmos?sslmode=verify-full", "", true}, + {"verify-full from PGSSLMODE", "postgres://u@db.example/openmos", "verify-full", true}, + {"default is prefer", "postgres://u@db.example/openmos", "", false}, + {"disable", "postgres://u@db.example/openmos?sslmode=disable", "", false}, + {"allow", "postgres://u@db.example/openmos?sslmode=allow", "", false}, + {"prefer", "postgres://u@db.example/openmos?sslmode=prefer", "", false}, + {"require", "postgres://u@db.example/openmos?sslmode=require", "", false}, + {"verify-ca", "postgres://u@db.example/openmos?sslmode=verify-ca", "", false}, + {"disable from PGSSLMODE", "postgres://u@db.example/openmos", "disable", false}, + {"keyword form", "host=db.example user=u sslmode=require", "", false}, + {"multiple hosts verify-full", "postgres://u@a.example,b.example/openmos?sslmode=verify-full", "", true}, + {"multiple hosts prefer", "postgres://u@a.example,b.example/openmos?sslmode=prefer", "", false}, + } { + t.Run(tc.name, func(t *testing.T) { + clearPGEnv(t) + if tc.pgsslmode != "" { + t.Setenv("PGSSLMODE", tc.pgsslmode) + } + _, err := ParsePoolConfig(PoolOptions{URL: tc.url}) + if tc.ok && err != nil { + t.Errorf("rejected: %v", err) + } + if !tc.ok && err == nil { + t.Error("accepted without verify-full") + } + // Development may use anything + if _, err := ParsePoolConfig(PoolOptions{URL: tc.url, AllowInsecureTLS: true}); err != nil { + t.Errorf("rejected with AllowInsecureTLS: %v", err) + } + }) + } +} + +func TestParseErrorWithholdsPassword(t *testing.T) { + clearPGEnv(t) + const secret = "s3cret-Passw0rd" + for _, bad := range []string{ + "postgres://u:" + secret + "@db.example:notaport/openmos", + "host=db.example password=" + secret + " port=notaport", + "postgres://u:" + secret + "@db.example/openmos?sslmode=bogus", + } { + _, err := ParsePoolConfig(PoolOptions{URL: bad, AllowInsecureTLS: true}) + if err == nil { + t.Errorf("invalid settings accepted") + continue + } + // pgx redacts only on a best-effort basis, so its error is never passed on + if !errors.Is(err, errInvalidSettings) { + t.Errorf("err = %v, want errInvalidSettings", err) + } + if strings.Contains(err.Error(), secret) { + t.Errorf("error reveals the password: %v", err) + } + } +} + +// A single sslmode applies to every host, so this case cannot come from +// ParseConfig; the check still guards against an insecure fallback. +func TestRequireVerifyFullChecksFallbacks(t *testing.T) { + secure := &tls.Config{ServerName: "a.example"} + c := &pgx.ConnConfig{} + c.TLSConfig = secure + c.Fallbacks = []*pgconn.FallbackConfig{{Host: "b.example", TLSConfig: secure}} + if err := requireVerifyFull(c); err != nil { + t.Errorf("secure fallbacks rejected: %v", err) + } + c.Fallbacks = append(c.Fallbacks, &pgconn.FallbackConfig{Host: "c.example"}) + if err := requireVerifyFull(c); err == nil { + t.Error("plain-text fallback accepted") + } +} + +func TestConfigured(t *testing.T) { + clearPGEnv(t) + if Configured("") { + t.Error("Configured with nothing set") + } + if !Configured("postgres://localhost/openmos") { + t.Error("not Configured with a URL") + } + t.Setenv("PGHOST", "localhost") + if !Configured("") { + t.Error("not Configured with PGHOST") + } +} + +func TestNewPoolConnects(t *testing.T) { + testURL := testDatabaseURL(t) + pool, err := NewPool(t.Context(), PoolOptions{URL: testURL, MaxConns: 3, AllowInsecureTLS: true}) + if err != nil { + t.Fatalf("NewPool: %v", err) + } + defer pool.Close() + if err := pool.Ping(t.Context()); err != nil { + t.Errorf("Ping: %v", err) + } + if got := pool.Stat().MaxConns(); got != 3 { + t.Errorf("MaxConns = %d, want 3", got) + } +} + +func TestNewPoolErrorWithholdsPassword(t *testing.T) { + u, err := url.Parse(testDatabaseURL(t)) + if err != nil { + t.Fatal(err) + } + const wrong = "wr0ng-Passw0rd" + u.User = url.UserPassword(u.User.Username(), wrong) + + _, err = NewPool(t.Context(), PoolOptions{URL: u.String(), ConnectTimeout: 3 * time.Second, AllowInsecureTLS: true}) + if err == nil { + t.Fatal("NewPool with a wrong password succeeded") + } + // Make sure the server checked the password, not just refused a dial + var pgErr *pgconn.PgError + if !errors.As(err, &pgErr) || pgErr.Code != invalidPassword { + t.Fatalf("err = %v, want SQLSTATE %s", err, invalidPassword) + } + if strings.Contains(err.Error(), wrong) { + t.Errorf("error reveals the password: %v", err) + } +} + +// invalidPassword is the SQLSTATE for a failed password authentication. +const invalidPassword = "28P01" diff --git a/src/internal/store/postgres/testdb_test.go b/src/internal/store/postgres/testdb_test.go index 84543d5..e8d2361 100644 --- a/src/internal/store/postgres/testdb_test.go +++ b/src/internal/store/postgres/testdb_test.go @@ -11,9 +11,9 @@ import ( // recreate the openmos schema in it, so never point it at real data. const testDBEnv = "OPENMOS_TEST_DATABASE_URL" -// testDB returns a connection to an empty test database, or skips the test -// if testDBEnv is not set. The openmos schema is dropped before and after. -func testDB(t *testing.T) *sql.DB { +// testDatabaseURL returns the test database URL, or skips the test if +// testDBEnv is not set. +func testDatabaseURL(t *testing.T) string { t.Helper() url := os.Getenv(testDBEnv) if url == "" { @@ -24,7 +24,14 @@ func testDB(t *testing.T) *sql.DB { } t.Skipf("%s not set; skipping PostgreSQL test", testDBEnv) } - db, err := Open(url) + return url +} + +// testDB returns a connection to an empty test database, or skips the test +// if testDBEnv is not set. The openmos schema is dropped before and after. +func testDB(t *testing.T) *sql.DB { + t.Helper() + db, err := Open(testDatabaseURL(t)) if err != nil { t.Fatal(err) } diff --git a/src/main.go b/src/main.go index 3375480..5db7093 100644 --- a/src/main.go +++ b/src/main.go @@ -49,6 +49,10 @@ func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() + if pool := connectDatabase(ctx, cfg, log); pool != nil { + defer pool.Close() + } + tcpServer := newTCPServer(cfg, newRepository(log), log) // Handle signals for graceful shutdown From 1f795ab223efd3ffd3c1208c61a3c5ae2c55571c Mon Sep 17 00:00:00 2001 From: Timo Ruohomaki Date: Sun, 8 Nov 2026 21:39:34 +0200 Subject: [PATCH 2/2] MOS-13: Parse pool sizes as int32 with a range check CodeQL flagged int32(strconv.Atoi(...)) for POSTGRES_MAX_CONNS and POSTGRES_MIN_CONNS: an out-of-range value would wrap around. Parse them with strconv.ParseInt(s, 10, 32) instead, falling back to the default like the other env helpers, and reject negative pool sizes in ParsePoolConfig. Co-Authored-By: Claude Opus 5.5 --- src/internal/config/env.go | 4 ++-- src/internal/config/env_helpers.go | 23 +++++++++++++++++++++++ src/internal/config/postgres_test.go | 21 +++++++++++++++++++++ src/internal/store/postgres/pool.go | 4 ++++ src/internal/store/postgres/pool_test.go | 6 ++++++ 5 files changed, 56 insertions(+), 2 deletions(-) diff --git a/src/internal/config/env.go b/src/internal/config/env.go index 3afd566..8e03fcb 100644 --- a/src/internal/config/env.go +++ b/src/internal/config/env.go @@ -38,10 +38,10 @@ func applyEnvOverrides(config *Config, yamlLoaded bool) { config.Postgres.URL = getEnv("DATABASE_URL", config.Postgres.URL) } if envVal := getEnv("POSTGRES_MAX_CONNS", ""); envVal != "" || !yamlLoaded { - config.Postgres.MaxConns = int32(getEnvAsInt("POSTGRES_MAX_CONNS", getDefaultInt(int(config.Postgres.MaxConns), 10))) + config.Postgres.MaxConns = getEnvAsInt32("POSTGRES_MAX_CONNS", getDefaultInt32(config.Postgres.MaxConns, 10)) } if envVal := getEnv("POSTGRES_MIN_CONNS", ""); envVal != "" || !yamlLoaded { - config.Postgres.MinConns = int32(getEnvAsInt("POSTGRES_MIN_CONNS", getDefaultInt(int(config.Postgres.MinConns), 1))) + config.Postgres.MinConns = getEnvAsInt32("POSTGRES_MIN_CONNS", getDefaultInt32(config.Postgres.MinConns, 1)) } if envVal := getEnv("POSTGRES_CONNECT_TIMEOUT", ""); envVal != "" || !yamlLoaded { config.Postgres.ConnectTimeout = getEnvAsDuration("POSTGRES_CONNECT_TIMEOUT", getDefaultDuration(config.Postgres.ConnectTimeout, 5*time.Second)) diff --git a/src/internal/config/env_helpers.go b/src/internal/config/env_helpers.go index 845a804..1e7099b 100644 --- a/src/internal/config/env_helpers.go +++ b/src/internal/config/env_helpers.go @@ -28,6 +28,22 @@ func getEnvAsInt(key string, defaultValue int) int { return value } +// getEnvAsInt32 parses with a 32-bit limit, so values that do not fit fall +// back to the default instead of being truncated by a conversion. +func getEnvAsInt32(key string, defaultValue int32) int32 { + valueStr := getEnv(key, "") + if valueStr == "" { + return defaultValue + } + + value, err := strconv.ParseInt(valueStr, 10, 32) + if err != nil { + return defaultValue + } + + return int32(value) +} + func getEnvAsDuration(key string, defaultValue time.Duration) time.Duration { valueStr := getEnv(key, "") if valueStr == "" { @@ -85,6 +101,13 @@ func getDefaultInt(current, defaultValue int) int { return current } +func getDefaultInt32(current, defaultValue int32) int32 { + if current == 0 { + return defaultValue + } + return current +} + func getDefaultBool(current, defaultValue bool) bool { // Zero value for bool is false, but can't determine if it's default without context // We'll just use the provided default diff --git a/src/internal/config/postgres_test.go b/src/internal/config/postgres_test.go index c291fb3..5721cd6 100644 --- a/src/internal/config/postgres_test.go +++ b/src/internal/config/postgres_test.go @@ -53,3 +53,24 @@ func TestGeneratedConfigHasNoDatabaseURL(t *testing.T) { t.Errorf("generated postgres block = %+v, want empty URL and defaults", cfg.Postgres) } } + +// Pool sizes that do not fit in an int32 fall back to the default instead +// of wrapping around. +func TestPostgresConnsOutOfRangeFallBack(t *testing.T) { + for _, v := range []string{"2147483648", "99999999999", "-2147483649", "ten"} { + isolate(t) + t.Setenv("POSTGRES_MAX_CONNS", v) + cfg, err := LoadConfig() + if err != nil { + t.Fatalf("LoadConfig: %v", err) + } + if cfg.Postgres.MaxConns != 10 { + t.Errorf("POSTGRES_MAX_CONNS=%s: MaxConns = %d, want default 10", v, cfg.Postgres.MaxConns) + } + } + isolate(t) + t.Setenv("POSTGRES_MAX_CONNS", "2147483647") + if cfg, err := LoadConfig(); err != nil || cfg.Postgres.MaxConns != 2147483647 { + t.Errorf("largest int32 not accepted: %v, %v", cfg.Postgres.MaxConns, err) + } +} diff --git a/src/internal/store/postgres/pool.go b/src/internal/store/postgres/pool.go index a1bbc79..9f3d1a0 100644 --- a/src/internal/store/postgres/pool.go +++ b/src/internal/store/postgres/pool.go @@ -63,6 +63,10 @@ func ParsePoolConfig(opts PoolOptions) (*pgxpool.Config, error) { return nil, errInvalidSettings } + if opts.MaxConns < 0 || opts.MinConns < 0 { + return nil, fmt.Errorf("PostgreSQL max conns (%d) and min conns (%d) must not be negative", + opts.MaxConns, opts.MinConns) + } cfg.MaxConns = valueOr(opts.MaxConns, DefaultMaxConns) cfg.MinConns = valueOr(opts.MinConns, DefaultMinConns) if cfg.MinConns > cfg.MaxConns { diff --git a/src/internal/store/postgres/pool_test.go b/src/internal/store/postgres/pool_test.go index 9103a4a..e7fcab9 100644 --- a/src/internal/store/postgres/pool_test.go +++ b/src/internal/store/postgres/pool_test.go @@ -54,6 +54,12 @@ func TestParsePoolConfigDefaults(t *testing.T) { MaxConns: 2, MinConns: 3}); err == nil { t.Error("min conns above max conns accepted") } + for _, o := range []PoolOptions{{MaxConns: -1}, {MinConns: -1}} { + o.URL = "postgres://u@db.example/openmos?sslmode=verify-full" + if _, err := ParsePoolConfig(o); err == nil { + t.Errorf("negative conns accepted: max %d, min %d", o.MaxConns, o.MinConns) + } + } } func TestParsePoolConfigRequiresVerifyFull(t *testing.T) {