Skip to content

Fix Postgres password command DSN parsing#4531

Merged
akshaydeo merged 2 commits into
maximhq:mainfrom
dani29:codex/pg-password-command-dsn
Jun 19, 2026
Merged

Fix Postgres password command DSN parsing#4531
akshaydeo merged 2 commits into
maximhq:mainfrom
dani29:codex/pg-password-command-dsn

Conversation

@dani29

@dani29 dani29 commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Summary

  • quote libpq keyword DSN values when building Postgres connection strings
  • preserve empty static password fields for password_command without losing dbname parsing
  • add a regression test for a service-account-style username with password_command

Verification

  • go test ./postgresconn
  • go test ./postgresconn ./configstore ./logstore -run '^$'
  • real Postgres verification with BIFROST_POSTGRES_PASSWORD_COMMAND_TEST=1 using a service-account-style username and db bifrost

@greptile-apps

greptile-apps Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge — the change is a narrowly scoped quoting fix with no behavioral impact on the happy path and a direct regression test for the broken scenario.

The escaping logic is correct (backslash escaped before single quote to avoid double-escaping), all six DSN fields are covered, and the password_command flow is unaffected because OptionBeforeConnect overwrites the placeholder empty password at connection time. The new tests validate the exact failing scenario and the two escaping edge cases via pgx.ParseConfig round-trips.

No files require special attention.

Important Files Changed

Filename Overview
framework/postgresconn/postgresconn.go Adds quoteLibpqValue with correct backslash-first escape ordering and applies it to all six fields in BuildDSN; no regressions introduced.
framework/postgresconn/postgresconn_test.go Adds regression test for the @ username trigger and a table-driven suite covering single-quote, backslash, and combined escaping; all validated via pgx.ParseConfig round-trips.

Reviews (4): Last reviewed commit: "Merge branch 'main' into codex/pg-passwo..." | Re-trigger Greptile

Comment thread framework/postgresconn/postgresconn_test.go
@dani29 dani29 force-pushed the codex/pg-password-command-dsn branch from 8f82f05 to 58753f8 Compare June 18, 2026 13:26
@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 81279177-2660-4bde-9d4a-3c338088d9ef

📥 Commits

Reviewing files that changed from the base of the PR and between 58753f8 and 65fdae4.

📒 Files selected for processing (2)
  • framework/postgresconn/postgresconn.go
  • framework/postgresconn/postgresconn_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • framework/postgresconn/postgresconn.go

📝 Walkthrough

Summary by CodeRabbit

Bug Fixes

  • PostgreSQL connection strings now properly escape and quote configuration values to safely handle special characters such as backslashes and quotes, improving reliability when using password commands and complex credentials.

Walkthrough

BuildDSN is updated to wrap all libpq connection parameter values with a new quoteLibpqValue helper that escapes backslashes and single quotes and encloses the result in single quotes. Tests verify DSN round-trip parsing via pgx.ParseConfig and validate handling of special characters.

Changes

DSN Value Quoting

Layer / File(s) Summary
quoteLibpqValue helper, BuildDSN usage, and test
framework/postgresconn/postgresconn.go, framework/postgresconn/postgresconn_test.go
quoteLibpqValue escapes \ as \\ and ' as \', then wraps the value in single quotes. BuildDSN now passes all six parameters (host, port, user, password, dbname, sslmode) through this helper. TestBuildDSNQuotesValuesForPasswordCommandParsing constructs a Config with a PasswordCommand, parses the DSN result via pgx.ParseConfig, and asserts host, user, empty password, and database name. TestBuildDSNQuotesSpecialCharacters is a table-driven test that mutates User, Host, and DBName with single quotes, backslashes, and combinations, then verifies the parsed pgx.ConnConfig fields match the original unescaped values.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐇 A backslash wandered into the DSN,
But the rabbit said "Escape it — and then
Wrap it in quotes so the parser won't frown,
No special char shall bring the connection down!"
Hop hop, the tests pass, all safe and serene. 🌿

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the summary and verification steps but is missing several required template sections: Changes, Type of change, Affected areas, How to test, Breaking changes, Related issues, Security considerations, and Checklist. Complete the description by adding all required template sections. At minimum, include Type of change, Affected areas, and fill out the Checklist items.
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: fixing Postgres password command DSN parsing, which is directly aligned with the changeset's primary objective.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies"


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@dani29 dani29 force-pushed the codex/pg-password-command-dsn branch from 58753f8 to 65fdae4 Compare June 18, 2026 13:29

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
framework/postgresconn/postgresconn_test.go (1)

48-62: ⚡ Quick win

Add a focused assertion for quote/backslash escaping paths.

This test covers IAM username + empty password parsing, but it doesn’t directly exercise the new ' and \ escaping branches in quoteLibpqValue.

Suggested test addition
 func TestBuildDSNQuotesValuesForPasswordCommandParsing(t *testing.T) {
 	cfg := validConfig()
 	cfg.Host = schemas.NewEnvVar("127.0.0.1")
 	cfg.User = schemas.NewEnvVar("service-account@example-project.iam")
 	cfg.Password = schemas.NewEnvVar("")
 	cfg.PasswordCommand = &PasswordCommandConfig{Command: "printf", Args: []string{"unused-iam-auth"}}

 	pgxConfig, err := pgx.ParseConfig(BuildDSN(cfg))

 	require.NoError(t, err)
 	require.Equal(t, "127.0.0.1", pgxConfig.Host)
 	require.Equal(t, "service-account@example-project.iam", pgxConfig.User)
 	require.Equal(t, "", pgxConfig.Password)
 	require.Equal(t, "bifrost", pgxConfig.Database)
 }
+
+func TestBuildDSNEscapesSpecialChars(t *testing.T) {
+	cfg := validConfig()
+	cfg.User = schemas.NewEnvVar(`service\acct`)
+	cfg.DBName = schemas.NewEnvVar(`bifro'st`)
+
+	pgxConfig, err := pgx.ParseConfig(BuildDSN(cfg))
+
+	require.NoError(t, err)
+	require.Equal(t, `service\acct`, pgxConfig.User)
+	require.Equal(t, `bifro'st`, pgxConfig.Database)
+}

As per coding guidelines, framework/** tests should cover edge cases and failure paths.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@framework/postgresconn/postgresconn_test.go` around lines 48 - 62, The test
TestBuildDSNQuotesValuesForPasswordCommandParsing does not directly exercise the
quote and backslash escaping branches in the quoteLibpqValue function. Add test
assertions that explicitly test configuration values containing single quotes
and backslashes (such as in the Host, User, or other DSN fields) to verify that
BuildDSN properly escapes these characters and that pgx.ParseConfig correctly
interprets the escaped values in the resulting DSN string.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@framework/postgresconn/postgresconn_test.go`:
- Around line 48-62: The test TestBuildDSNQuotesValuesForPasswordCommandParsing
does not directly exercise the quote and backslash escaping branches in the
quoteLibpqValue function. Add test assertions that explicitly test configuration
values containing single quotes and backslashes (such as in the Host, User, or
other DSN fields) to verify that BuildDSN properly escapes these characters and
that pgx.ParseConfig correctly interprets the escaped values in the resulting
DSN string.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 413c9786-8ce8-48a4-ba69-f4aed75fcf90

📥 Commits

Reviewing files that changed from the base of the PR and between ca51f4b and 58753f8.

📒 Files selected for processing (2)
  • framework/postgresconn/postgresconn.go
  • framework/postgresconn/postgresconn_test.go

@dani29

dani29 commented Jun 18, 2026

Copy link
Copy Markdown
Contributor Author

cc @akshaydeo, another small follow-up :-( Looks like command parsing is problematic with password command.

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ dani29
❌ akshaydeo
You have signed the CLA already but the status is still pending? Let us recheck it.

@akshaydeo

Copy link
Copy Markdown
Contributor

fixes #4564

@akshaydeo akshaydeo merged commit 367b742 into maximhq:main Jun 19, 2026
5 of 6 checks passed
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.

3 participants