Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 39 additions & 20 deletions base/database/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@ import (
"app/base/telemetry"
"app/base/utils"
"context"
"database/sql"
"fmt"
"strconv"
"time"

"github.com/XSAM/otelsql"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/stdlib"
semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
"gorm.io/driver/postgres"
"gorm.io/gorm"
Expand Down Expand Up @@ -92,31 +97,28 @@ func createGormConfig(debug bool) *gorm.Config {

// open database connection
func openPostgreSQL(dbConfig *PostgreSQLConfig) *gorm.DB {
connectString := dataSourceName(dbConfig)
cfg := createGormConfig(dbConfig.Debug)

var db *gorm.DB
var err error
pgCfg, err := ConnConfig(dbConfig)
if err != nil {
panic(err)
}
var sqlDB *sql.DB
if telemetry.SQLEnabled() {
// gorm.io/driver/postgres uses jackc/pgx/v5/stdlib (driver name "pgx")
sqlDB, openErr := otelsql.Open("pgx", connectString,
sqlDB = otelsql.OpenDB(stdlib.GetConnector(*pgCfg),
otelsql.WithAttributes(semconv.DBSystemPostgreSQL),
otelsql.WithSpanOptions(telemetry.SQLSpanOptions()))
if openErr != nil {
panic(openErr)
}
db, err = gorm.Open(postgres.New(postgres.Config{Conn: sqlDB}), cfg)
} else {
db, err = gorm.Open(postgres.Open(connectString), cfg)
sqlDB = OpenDB(pgCfg)
}

db, err := gorm.Open(postgres.New(postgres.Config{Conn: sqlDB}), createGormConfig(dbConfig.Debug))
if err != nil {
panic(err)
}

if dbConfig.Debug {
db = db.Debug()
}
sqlDB, err := db.DB()
sqlDB, err = db.DB()
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -169,15 +171,32 @@ func createPostgreSQLConfig(mode DBMode) PostgreSQLConfig {
return config
}

// create "data source" config string needed for database connection opening
func dataSourceName(dbConfig *PostgreSQLConfig) string {
dbsource := fmt.Sprintf("host=%s port=%d user=%s dbname=%s password=%s sslmode=%s statement_timeout=%d",
dbConfig.Host, dbConfig.Port, dbConfig.User, dbConfig.Database, dbConfig.Passwd, dbConfig.SSLMode,
dbConfig.StatementTimeoutMs)
// ConnConfig builds a pgx config. Address and TLS are parsed from a keyword string so pgx
// can build TLS fallbacks. User, password, database, and statement_timeout are set on the config.
func ConnConfig(dbConfig *PostgreSQLConfig) (*pgx.ConnConfig, error) {
dsn := fmt.Sprintf("host=%s port=%d sslmode=%s",
dbConfig.Host, dbConfig.Port, dbConfig.SSLMode)
if dbConfig.SSLRootCert != "" {
dbsource = fmt.Sprintf("%s sslrootcert=%s", dbsource, dbConfig.SSLRootCert)
dsn += " sslrootcert=" + dbConfig.SSLRootCert
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
}
cfg, err := pgx.ParseConfigWithOptions(dsn, pgx.ParseConfigOptions{
ParseConfigOptions: pgconn.ParseConfigOptions{
ConnStringAllowedKeys: []string{"host", "port", "sslmode", "sslrootcert"},
},
})
if err != nil {
return nil, err
}
return dbsource
cfg.User = dbConfig.User
cfg.Password = dbConfig.Passwd
cfg.Database = dbConfig.Database
cfg.RuntimeParams["statement_timeout"] = strconv.Itoa(dbConfig.StatementTimeoutMs)
return cfg, nil
}

// OpenDB opens a database/sql pool. cfg must come from ConnConfig.
func OpenDB(cfg *pgx.ConnConfig) *sql.DB {
return stdlib.OpenDB(*cfg)
}

func loadAdditionalParamsFromDB() {
Expand Down
55 changes: 55 additions & 0 deletions base/database/setup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,71 @@ package database

import (
"app/base/utils"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"math/big"
"os"
"path/filepath"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestDBCheck(t *testing.T) {
utils.SkipWithoutDB(t)
Configure()
}

func TestConnConfigSetsCredentialsOutsideDSN(t *testing.T) {
certPath := filepath.Join(t.TempDir(), "rootcert.crt")
writeTestCert(t, certPath)

cfg, err := ConnConfig(&PostgreSQLConfig{
Host: "dbhost",
Port: 5433,
User: "user name",
Database: "db name",
Passwd: "secret host=evil.example sslmode=disable",
SSLMode: "verify-ca",
SSLRootCert: certPath,
StatementTimeoutMs: 1500})
require.NoError(t, err)
assert.Equal(t, "dbhost", cfg.Host)
assert.Equal(t, uint16(5433), cfg.Port)
assert.Equal(t, "user name", cfg.User)
assert.Equal(t, "db name", cfg.Database)
assert.Equal(t, "secret host=evil.example sslmode=disable", cfg.Password)
assert.Equal(t, "1500", cfg.RuntimeParams["statement_timeout"])
assert.NotContains(t, cfg.ConnString(), "secret")
assert.NotContains(t, cfg.ConnString(), "user name")
assert.NotContains(t, cfg.ConnString(), "db name")
assert.Contains(t, cfg.ConnString(), "sslrootcert="+certPath)
assert.NotNil(t, cfg.TLSConfig)
assert.NotContains(t, cfg.ConnString(), "statement_timeout")
}

func writeTestCert(t *testing.T, path string) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(1),
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour),
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
require.NoError(t, err)
file, err := os.Create(path)
require.NoError(t, err)
defer file.Close()
require.NoError(t, pem.Encode(file, &pem.Block{Type: "CERTIFICATE", Bytes: der}))
}

func TestAdditionalParams(t *testing.T) {
utils.SkipWithoutDB(t)
Configure()
Expand Down
1 change: 0 additions & 1 deletion conf/aggregator_common.env
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
DB_USER=evaluator
DB_PASSWD=evaluator
4 changes: 2 additions & 2 deletions conf/cdappconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
"rdsCa": "/opt/postgresql/pgca.crt",
"adminPassword": "passwd",
"adminUsername": "admin",
"username": "UNSET",
"password": "UNSET"
"username": "dbuser",
"password": "dbpasswd"
},
"publicPort": 8080,
"privatePort": 9000,
Expand Down
5 changes: 0 additions & 5 deletions conf/database_admin.env
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
DB_ADMIN_USER=admin
DB_ADMIN_PASSWD=passwd

MANAGER_PASSWORD=manager
LISTENER_PASSWORD=listener
VMAAS_SYNC_PASSWORD=vmaas_sync
EVALUATOR_PASSWORD=evaluator

# Optionally set schema_migration=XXX and/or reset_schema
POD_CONFIG=update_users;update_db_config;wait_for_db=empty
1 change: 0 additions & 1 deletion conf/evaluator_common.env
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
DB_USER=evaluator
DB_PASSWD=evaluator
1 change: 0 additions & 1 deletion conf/listener.env
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
DB_USER=listener
DB_PASSWD=listener
CREATED_SYSTEMS_TOPIC=patchman.evaluator.user-evaluation

# template_advisory_eval=false — recalc template systems on advisory change/delete (enable with evaluator pods)
Expand Down
1 change: 0 additions & 1 deletion conf/manager.env
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
DB_USER=manager
DB_PASSWD=manager

MAX_REQUEST_BODY_SIZE=1048576
1 change: 0 additions & 1 deletion conf/vmaas_sync.env
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
DB_USER=vmaas_sync
DB_PASSWD=vmaas_sync

EVAL_TOPIC=patchman.evaluator.recalc
25 changes: 7 additions & 18 deletions database_admin/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"github.com/golang-migrate/migrate/v4/database"
"github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file" // we load migrations from local folder
"github.com/lib/pq"
"github.com/pkg/errors"
)

Expand All @@ -24,25 +23,15 @@ const (
MIGRATE = 3
)

func NewConn(databaseURL string) (database.Driver, *sql.DB, error) {
baseConn, err := pq.NewConnector(databaseURL)
if err != nil {
return nil, nil, err
func NewConn(db *sql.DB) (database.Driver, error) {
if _, err := db.Exec("SET client_min_messages TO NOTICE"); err != nil {
return nil, err
}

loggingConn := pq.ConnectorWithNoticeHandler(baseConn, func(e *pq.Error) {
utils.LogInfo("Notice: " + e.Error())
})

db := sql.OpenDB(loggingConn)
if _, err = db.Exec("SET client_min_messages TO NOTICE"); err != nil {
return nil, nil, err
}
var driver database.Driver
if driver, err = postgres.WithInstance(db, &postgres.Config{}); err != nil {
return nil, nil, err
driver, err := postgres.WithInstance(db, &postgres.Config{})
if err != nil {
return nil, err
}
return driver, db, nil
return driver, nil
}

func MigrateUp(conn database.Driver, sourceURL string) {
Expand Down
56 changes: 43 additions & 13 deletions database_admin/update.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package database_admin

import (
appdb "app/base/database"
"app/base/utils"
"database/sql"
"errors"
Expand All @@ -10,6 +11,8 @@ import (
"time"

"github.com/golang-migrate/migrate/v4/database"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/lib/pq"
log "github.com/sirupsen/logrus"
)
Expand Down Expand Up @@ -148,13 +151,13 @@ func setPgEnv() {

func blockUsers(db *sql.DB) {
for _, user := range lockUsers {
execOrPanic(db, "ALTER USER "+user+" NOLOGIN")
execOrPanic(db, fmt.Sprintf("ALTER USER %s NOLOGIN", pq.QuoteIdentifier(user)))
}
}

func unblockUsers(db *sql.DB) {
for _, user := range lockUsers {
execOrPanic(db, "ALTER USER "+user+" LOGIN")
execOrPanic(db, fmt.Sprintf("ALTER USER %s LOGIN", pq.QuoteIdentifier(user)))
}
}

Expand Down Expand Up @@ -193,22 +196,50 @@ func repairSystemAdvisories0Partition(db *sql.DB) {
unblockUsers(db)
}

func dbConn() (database.Driver, *sql.DB) {
sslModeCert := utils.CoreCfg.DBSslMode
if utils.CoreCfg.DBSslRootCert != "" {
sslModeCert += "&sslrootcert=" + utils.CoreCfg.DBSslRootCert
func corePostgreSQLConfig(user, password string) appdb.PostgreSQLConfig {
return appdb.PostgreSQLConfig{
Host: utils.CoreCfg.DBHost,
Port: utils.CoreCfg.DBPort,
User: user,
Database: utils.CoreCfg.DBName,
Passwd: password,
SSLMode: utils.CoreCfg.DBSslMode,
SSLRootCert: utils.CoreCfg.DBSslRootCert,
}
databaseURL := fmt.Sprintf("postgres://%s/%s?sslmode=%s", utils.CoreCfg.DBHost, utils.CoreCfg.DBName, sslModeCert)
databaseURL += "&tcp_keepalives_idle=60&tcp_keepalives_interval=30&tcp_keepalives_count=5"
}

func coreConnConfig(user, password string) (*pgx.ConnConfig, error) {
cfg := corePostgreSQLConfig(user, password)
return appdb.ConnConfig(&cfg)
}

func dbConn() (database.Driver, *sql.DB) {
setPgEnv()
cfg, err := coreConnConfig(utils.CoreCfg.DBAdminUser, utils.CoreCfg.DBAdminPassword)
if err != nil {
panic(err)
}
cfg.RuntimeParams["tcp_keepalives_idle"] = "60"
cfg.RuntimeParams["tcp_keepalives_interval"] = "30"
cfg.RuntimeParams["tcp_keepalives_count"] = "5"
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
cfg.OnNotice = func(_ *pgconn.PgConn, notice *pgconn.Notice) {
utils.LogInfo("Notice: " + notice.Severity + ": " + notice.Message)
}

conn, db, err := NewConn(databaseURL)
db := appdb.OpenDB(cfg)
conn, err := NewConn(db)
if err != nil {
_ = db.Close()
Comment thread
johnelliott626 marked this conversation as resolved.
Resolved
panic(err)
}
return conn, db
}

func setUserPassword(db *sql.DB, user, password string) {
execOrPanic(db, fmt.Sprintf("ALTER USER %s WITH PASSWORD %s", pq.QuoteIdentifier(user),
pq.QuoteLiteral(password)))
}

func UpdateDB(migrationFilesURL string) {
utils.ConfigureLogging()
conn, db := dbConn()
Expand Down Expand Up @@ -253,10 +284,9 @@ func UpdateDB(migrationFilesURL string) {
log.Info("Setting user passwords")
// Set specific password for each user. If the users are already created, change the password.
// This is performed on each startup in order to ensure users have latest pasword
execOrPanic(db, "ALTER USER listener WITH PASSWORD '"+utils.GetenvOrFail("LISTENER_PASSWORD")+"'")
execOrPanic(db, "ALTER USER evaluator WITH PASSWORD '"+utils.GetenvOrFail("EVALUATOR_PASSWORD")+"'")
execOrPanic(db, "ALTER USER manager WITH PASSWORD '"+utils.GetenvOrFail("MANAGER_PASSWORD")+"'")
execOrPanic(db, "ALTER USER vmaas_sync WITH PASSWORD '"+utils.GetenvOrFail("VMAAS_SYNC_PASSWORD")+"'")
for _, user := range lockUsers {
setUserPassword(db, user, utils.CoreCfg.DBPassword)
Comment thread
MichaelMraka marked this conversation as resolved.
Resolved
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
}
}

if updateDBConfig {
Expand Down
Loading
Loading