Skip to content

RHINENG-33916: keep database credentials out of the connection string - #2399

Open
MichaelMraka wants to merge 2 commits into
RedHatInsights:masterfrom
MichaelMraka:pr2
Open

MichaelMraka wants to merge 2 commits into
RedHatInsights:masterfrom
MichaelMraka:pr2

Conversation

@MichaelMraka

@MichaelMraka MichaelMraka commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Secure Coding Practices Checklist GitHub Link

Secure Coding Checklist

  • Input Validation
  • Output Encoding
  • Authentication and Password Management
  • Session Management
  • Access Control
  • Cryptographic Practices
  • Error Handling and Logging
  • Data Protection
  • Communication Security
  • System Configuration
  • Database Security
  • File Management
  • Memory Management
  • General Coding Practices

Summary by Sourcery

Keep PostgreSQL credentials out of connection strings while standardizing secure database connection and administration handling.

Enhancements:

  • Build PostgreSQL connections from structured pgx configuration so credentials remain separate from connection strings across application and migration paths.
  • Centralize database connection handling and migrate database administration operations to use the shared PostgreSQL configuration.
  • Safely quote database identifiers and password literals when issuing administrative SQL commands.

Build:

  • Promote pgx to a direct dependency for structured PostgreSQL connection management.

Deployment:

  • Remove per-service database password environment-variable references from deployment configuration in favor of centralized database credentials.

Tests:

  • Add coverage verifying that credentials and connection parameters are not exposed in generated PostgreSQL connection strings.

Set user, password, and database on the pgx config so special characters in those values cannot change the host or TLS settings.
@MichaelMraka
MichaelMraka requested a review from a team as a code owner November 24, 2026 10:50
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.50000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.86%. Comparing base (632ad02) to head (342a628).

Files with missing lines Patch % Lines
base/database/setup.go 87.50% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #2399      +/-   ##
==========================================
+ Coverage   66.82%   66.86%   +0.04%     
==========================================
  Files         158      158              
  Lines        9081     9090       +9     
==========================================
+ Hits         6068     6078      +10     
+ Misses       3011     3010       -1     
  Partials        2        2              
Flag Coverage Δ
unittests 66.86% <87.50%> (+0.04%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sourcery-ai

sourcery-ai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Expose pgx-based connection configuration and database-pool helpers, and change migration connection setup to accept an already-open SQL pool.

  • base/database/setup.go L8-16, L174-199
  • database_admin/migrate.go L17 (removed lines), L26-31

Uses of the API

Build the database-admin connection from structured credentials and pass the resulting pool into migration setup.

  • database_admin/update.go L4, L14-15, L199-232

Implementation

Use the new pgx configuration and pool-opening APIs in the application database connection path.

  • base/database/setup.go L100-113, L121

Quote SQL identifiers and literals when updating database roles and passwords.

  • database_admin/update.go L238-242 (+3 small edits)

Configuration

Remove per-user database password environment variables and secret references in favor of the shared configured database password.

  • conf/cdappconfig.json L10-11
  • conf/aggregator_common.env L2 (removed lines)
  • conf/database_admin.env L4 (removed lines)
  • conf/evaluator_common.env L2 (removed lines)
  • conf/listener.env L2 (removed lines)
  • conf/manager.env L2 (removed lines)
  • conf/vmaas_sync.env L2 (removed lines)
  • deploy/clowdapp.yaml L96-981 (16 small edits)

Tests

Test that credentials and statement timeout are assigned outside the pgx connection string, and update database-admin tests to use structured connection configuration and the shared password.

  • base/database/setup_test.go L5-17, L25-69
  • database_admin/update_test.go L7-136 (6 small edits)

Lock files and vendored code

Promote pgx to a direct module dependency because the connection configuration now imports it directly.

  • go.mod L18, L90 (removed lines)

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 7 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="base/database/setup.go" line_range="180" />
<code_context>
+		dbConfig.Host, dbConfig.Port, dbConfig.SSLMode)
 	if dbConfig.SSLRootCert != "" {
-		dbsource = fmt.Sprintf("%s sslrootcert=%s", dbsource, dbConfig.SSLRootCert)
+		dsn += " sslrootcert=" + dbConfig.SSLRootCert
+	}
+	cfg, err := pgx.ParseConfigWithOptions(dsn, pgx.ParseConfigOptions{
</code_context>
<issue_to_address>
**TLS mode can be overridden**

When `SSLRootCert` contains whitespace followed by a keyword DSN option such as `sslmode=disable`, the root-certificate path is appended unescaped to the keyword DSN, so a value containing a token such as `sslmode=disable` is parsed as another allowed setting and overrides the configured TLS mode. The connection then stops verifying TLS.

Escape or quote DSN values before parsing, or avoid interpolating the certificate path into the connection string.
</issue_to_address>

### Comment 2
<location path="database_admin/update.go" line_range="288" />
<code_context>
-		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)
+		}
 	}
</code_context>
<issue_to_address>
**Shared password erases role isolation**

When an application service is compromised and its database credential is recovered, `setUserPassword` assigns the same `DBPassword` to every login in `lockUsers`, so a compromised service that knows its own database password can authenticate as the other application roles and obtain their database privileges.

Keep distinct passwords for each database role, or use a credential design that prevents one service from authenticating as the other roles.
</issue_to_address>

### Comment 3
<location path="database_admin/update.go" line_range="288" />
<code_context>
-		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)
+		}
 	}
</code_context>
<issue_to_address>
**Application pods lose database access**

When a deployment rotates per-service passwords while old pods still use those credentials, `setUserPassword` assigns the shared `CoreCfg.DBPassword` to every application role, so PostgreSQL rejects reconnects from pods using their previous per-service passwords; components expecting distinct credentials also fail authentication, and application database access is interrupted during the rollout.

Keep each application role's password aligned with the credentials used by its pods throughout the rollout.

Also at `deploy/clowdapp.yaml:96-97`.
</issue_to_address>

### Comment 4
<location path="database_admin/update.go" line_range="288" />
<code_context>
-		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)
+		}
 	}
</code_context>
<issue_to_address>
**New pods fail database authentication**

When `update_users` is unset and existing database role passwords differ from Clowder's password, `UpdateDB` skips `setUserPassword`, leaving the roles' old passwords in place while new pods use Clowder's password; PostgreSQL rejects their connections.

Ensure database roles are synchronized with the credentials supplied to new pods even when `update_users` is unset.

Also at `deploy/clowdapp.yaml:97`.
</issue_to_address>

### Comment 5
<location path="database_admin/update.go" line_range="288" />
<code_context>
-		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)
+		}
 	}
</code_context>
<issue_to_address>
**Some roles keep stale passwords**

When a password update fails after one or more roles have been updated, `setUserPassword` commits each role's change independently, so a later error leaves the roles with mixed passwords and the migration fails; services using the shared credential cannot connect to roles that were not updated.

Update all application-role passwords atomically so a failure leaves every role unchanged.
</issue_to_address>

### Comment 6
<location path="database_admin/update.go" line_range="222-224" />
<code_context>
+	if err != nil {
+		panic(err)
+	}
+	cfg.RuntimeParams["tcp_keepalives_idle"] = "60"
+	cfg.RuntimeParams["tcp_keepalives_interval"] = "30"
+	cfg.RuntimeParams["tcp_keepalives_count"] = "5"
+	cfg.OnNotice = func(_ *pgconn.PgConn, notice *pgconn.Notice) {
+		utils.LogInfo("Notice: " + notice.Severity + ": " + notice.Message)
</code_context>
<issue_to_address>
**Admin connections lose client keepalives**

When an admin connection is idle on a network that drops or silently blackholes database connections, `cfg.RuntimeParams` sends `tcp_keepalives_*` as PostgreSQL startup parameters, configuring server-side settings instead of the admin client's TCP socket; the connection loses the configured client keepalive behavior and can be dropped during idle periods or take longer to detect a blackhole.

Configure the keepalive settings on the admin client's TCP socket instead of passing them through `RuntimeParams`.
</issue_to_address>

### Comment 7
<location path="database_admin/migrate.go" line_range="28" />
<code_context>
-func NewConn(databaseURL string) (database.Driver, *sql.DB, error) {
-	baseConn, err := pq.NewConnector(databaseURL)
-	if err != nil {
-		return nil, nil, err
-	}
-
</code_context>
<issue_to_address>
**Connection error is obscured**

When `db.Exec` or `postgres.WithInstance` fails in `NewConn`, `NewConn` returns a nil `*sql.DB` with the error, so `dbConn` calls `Close` on nil and panics with a nil-pointer error instead of reporting the connection failure; the opened pool is also not closed.

Have `NewConn` return the original `db` on errors, or only close it in `dbConn` when it is non-nil.

Also at `database_admin/update.go:233`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 7 findings to address first, and on database-admin startup, this change assigns the same configured password to every application database role, replacing their separate passwords. Those credentials persist in PostgreSQL after a revert, so restoring the old role-specific access requires explicitly rotating them.

Blocking findings: base/database/setup.go:180, database_admin/update.go:288, database_admin/update.go:288, database_admin/update.go:288, database_admin/update.go:288, and 2 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread base/database/setup.go Resolved
Comment thread database_admin/update.go Resolved
Comment thread database_admin/update.go Resolved
Comment thread database_admin/update.go Resolved
Comment thread database_admin/update.go Resolved
Comment thread database_admin/update.go Resolved
Comment thread database_admin/migrate.go Resolved
@MichaelMraka MichaelMraka changed the title keep database credentials out of the connection string RHINENG-33916: keep database credentials out of the connection string Nov 24, 2026
@johnelliott626 johnelliott626 self-assigned this Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants