beads/internal/storage/postgres/credential.go
Test User 1fc38ba778 feat: choose your own storage backend (Postgres / MySQL / SQLite) — rebased on main
Rebase of PR #4601 (feat/choose-your-own-backend) onto current origin/main,
squashed to a single commit because the original 73-commit history built and then
removed the uowStore derisk spike incrementally, which does not replay cleanly
over the 125 commits main has since advanced (notably #4679, the ready-work
counts fix, which merged to main and is now inherited rather than re-applied).
The full pre-rebase history remains on the original branch tip for reference.

Contents (multi-backend feature + the six review follow-ups):
- bd init --backend=postgres|mysql|sqlite provisioning behind the Dolt-parity
  seam; the three SQL backends share *sqlkit.Store over pluggable dialects and
  carry a generated typed-unsupported shell for the non-core surface.
- Passwords in init DSNs are redacted before persisting to metadata.json (driver
  parser + re-parse verification), with a negative-test matrix proving no secret
  survives (pgdialect + mysql).
- The uowStore derisk spike and its report artifacts are removed; the shell
  generator now lives in internal/storage/unsupportedgen (neutral name).
- Compile-time guard `var _ storage.DoltStorage = (*Store)(nil)` on each backend
  plus a regen-idempotence test keep the generated skip lists honest.
- sqlkit exposes CountReadyWork so every SQL backend satisfies
  storage.ReadyWorkCounter and inherits the shared page-pushed ready-counts path.
- Commercial/product names scrubbed from the feature's own code for vendor
  neutrality.

Rebase reconciliations: adopted main's metadata-load hardening in the store
factories alongside the backend dispatch; combined the config interface
(GetMetadata + ReconcileVersion) and the conformance registrations (ReadyCounts +
Claim/lease); took main's versions of the shared-infra concurrency (uow
doltserver_tx) and delete-cascade (domain/issue_delete) evolutions; implemented
the interface's new UnclaimIssue on sqlkit (delegating to issueops) and added it
to the skip lists.

Verified: go build (cgo + CGO_ENABLED=0) and go vet clean; unit tests
(sqlbuild/issueops/pgdialect/mysql/unsupportedgen) and the SQLite conformance
suite green (RunAll, incl. ReadyCounts equivalence and Claim/lease on the real
sqlkit backend).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 17:44:37 +00:00

67 lines
3.4 KiB
Go

package postgres
import (
"context"
"fmt"
"os"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/creds"
"github.com/steveyegge/beads/internal/storage/pgdialect"
)
// resolveDSNCredential returns baseDSN with a credential resolved and placed, ready to
// connect. The precedence, high to low:
//
// - BEADS_PG_CREDENTIAL_COMMAND set is a hard error: an identity credential is
// presented as a username to a gateway, and this backend connects directly;
// - the DSN already carries a password (a full BEADS_POSTGRES_URL, or an explicit
// --pg-url) — it wins outright, no ladder is applied;
// - BEADS_PG_PASSWORD_COMMAND — a credential command (e.g. Vault / RDS-IAM / GCP-IAM);
// run at open time, cached until near expiry;
// - BEADS_PG_PASSWORD — a static password;
// - the credentials file [host:port] ($BEADS_CREDENTIALS_FILE or
// ~/.config/beads/credentials);
// - nothing configured — baseDSN is returned untouched so pgx's own libpq
// fallbacks (PGPASSWORD, ~/.pgpass, PGPASSFILE) still apply.
//
// It fails closed: if a configured credential command errors, the open aborts — it
// never silently downgrades to a lower rung.
func resolveDSNCredential(ctx context.Context, cfg *configfile.Config, baseDSN string) (string, error) {
if os.Getenv("BEADS_PG_CREDENTIAL_COMMAND") != "" {
return "", fmt.Errorf("postgres: BEADS_PG_CREDENTIAL_COMMAND is reserved: an identity credential is presented as a username to a gateway, and the postgres backend connects directly to the database with no gateway to present it to; use BEADS_PG_PASSWORD_COMMAND for a helper that produces a password")
}
// host:port keys the credentials-file lookup; ok=false (unix socket / unparseable)
// leaves the file rung not-configured (zero Host/Port), never failing.
host, port, _ := pgdialect.HostPort(baseDSN)
return resolveDSNWithSources(ctx, baseDSN,
creds.CommandSource{Command: cfg.GetPostgresPasswordCommand(), Kind: creds.KindSecret, Label: "BEADS_PG_PASSWORD_COMMAND"},
creds.EnvSource{Var: "BEADS_PG_PASSWORD"},
creds.FileSource{Host: host, Port: port, Lookup: configfile.LookupCredentialsPassword, Label: "credentials-file"},
)
}
// resolveDSNWithSources is the testable core of resolveDSNCredential: it applies the
// given credential ladder to baseDSN. A DSN that already carries a password wins
// outright; otherwise the first configured source supplies the credential, and
// nothing-configured leaves the DSN untouched for pgx's libpq fallbacks.
func resolveDSNWithSources(ctx context.Context, baseDSN string, sources ...creds.Source) (string, error) {
if pgdialect.HasPassword(baseDSN) {
return baseDSN, nil
}
cred, ok, err := creds.ResolveLadder(ctx, sources...)
if err != nil {
return "", err
}
if !ok {
return baseDSN, nil
}
// The SQL backends take a secret in the password slot; an identity credential
// (presented as a username to a gateway) has no home on a direct connection, so
// refuse it loudly rather than land a token where a password belongs. Defense in
// depth behind the BEADS_PG_CREDENTIAL_COMMAND reject above.
if cred.Kind != creds.KindSecret {
return "", fmt.Errorf("postgres: credential from %s is an identity, not a password; the postgres backend connects directly and has no gateway to present it to", cred.Source)
}
return pgdialect.WithCredential(baseDSN, cred.Username, cred.Value)
}