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
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,22 @@ becomes the release notes of the next tag.
`smarttags.Vocabulary`; `smartcomments/catalog.Check` runs it over every
commented object of a catalog.

### Fixed

- `introspect.Introspect` no longer sorts the caller's schema slice in
place (a live boot alphabetised the products' `schema.schemas`, which a
cache boot did not); `Catalog.Schemas` keeps the configured order and
`Hash` ignores it.
- Strict environment loading reports a variable that doubles the
underscore after its section (`PDBQ_ROLES__ALLOWED`) with a did-you-mean
hint instead of ignoring it.
- `confx.ValidateDatabase` rejects a negative `database.max_conns`, a
non-positive `database.connect_timeout` and a negative
`database.statement_timeout`; `ValidateIdentity` rejects a non-positive
`auth.jwt.jwks_cache_ttl` with a JWKS URL (it silently became one hour);
`ValidateWatch` and `watch.New` reject a non-positive poll interval (the
polling fallback panicked).

### Breaking: API hygiene

See [docs/upgrading.md](docs/upgrading.md#api-hygiene).
Expand Down
14 changes: 10 additions & 4 deletions confx/confx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ func TestValidateRejects(t *testing.T) {
return ValidateIdentity(Auth{Mode: "none", JWT: JWT{SecretFile: "/nonexistent/secret"}}, Roles{}, Claims{})
}, "auth.jwt.secret_file: open /nonexistent/secret: no such file or directory"},
"jwks url": {func() []string {
return ValidateIdentity(Auth{Mode: "jwt", JWT: JWT{JWKSURL: "idp.example/jwks", RoleClaimPath: "role"}}, Roles{}, Claims{})
return ValidateIdentity(Auth{Mode: "jwt", JWT: JWT{JWKSURL: "idp.example/jwks", JWKSCacheTTL: time.Hour, RoleClaimPath: "role"}}, Roles{}, Claims{})
}, `auth.jwt.jwks_url: "idp.example/jwks" is not an http(s) URL`},
"leeway": {func() []string {
return ValidateIdentity(Auth{Mode: "none", JWT: JWT{Leeway: -time.Second}}, Roles{}, Claims{})
Expand Down Expand Up @@ -344,15 +344,21 @@ func TestValidateRejects(t *testing.T) {
"headers needs trusted proxies": {func() []string {
return ValidateIdentity(Auth{Mode: "headers", Headers: Headers{Prefix: "X-Pdbq-Claim-", RoleClaim: "role"}}, Roles{}, Claims{})
}, "auth.headers.trusted_proxies is required in auth mode headers: list the gateway addresses allowed to send claim headers"},
"watch channel length": {func() []string { return ValidateWatch(Watch{Enabled: true, Channel: strings.Repeat("c", 64)}, "") },
"watch channel length": {func() []string {
return ValidateWatch(Watch{Enabled: true, PollInterval: time.Second, Channel: strings.Repeat("c", 64)}, "")
},
`watch.channel: "` + strings.Repeat("c", 64) + `" is longer than 63 bytes`},
"isolation": {func() []string { return ValidateTX(TX{Isolation: "chaos"}) },
`transactions.isolation: "chaos" is not 'read_committed', 'repeatable_read' or 'serializable'`},
"max_retries": {func() []string { return ValidateTX(TX{Isolation: "serializable", MaxRetries: -1}) },
"transactions.max_retries must be >= 0"},
"watch+cache": {func() []string { return ValidateWatch(Watch{Enabled: true, Channel: "c"}, "x") },
"watch+cache": {func() []string {
return ValidateWatch(Watch{Enabled: true, PollInterval: time.Second, Channel: "c"}, "x")
},
"watch.enabled cannot be combined with schema.cache_path"},
"watch channel": {func() []string { return ValidateWatch(Watch{Enabled: true, Channel: "bad$$chan"}, "") },
"watch channel": {func() []string {
return ValidateWatch(Watch{Enabled: true, PollInterval: time.Second, Channel: "bad$$chan"}, "")
},
`watch.channel: "bad$$chan" invalid: only letters, digits and underscores are allowed`},
"no schemas": {func() []string { return ValidateSchema(Schema{}) },
"schema.schemas must list at least one schema"},
Expand Down
25 changes: 21 additions & 4 deletions confx/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ func WithFlags(values map[string]any) LoadOption {
// naming the key it moved to (WithMoved), the reason it was removed
// (WithRemoved) or the closest valid key. An environment variable with
// the prefix is checked the same way when its first segment names a
// section of dst (or of a moved or removed key), or nearly does; other
// section of dst (or of a moved or removed key), or nearly does, or when
// it starts with a section name and a doubled underscore
// (PDBQ_ROLES__ALLOWED, a misspelt PDBQ_ROLES_ALLOWED); other
// variables with the prefix (PDBQ_TEST_DATABASE_URL) are ignored. Values
// are decoded with weak typing, so environment strings set booleans,
// numbers, durations and lists. Validation is the caller's job.
Expand Down Expand Up @@ -115,13 +117,28 @@ func Load(envPrefix, path string, dst any, opts ...LoadOption) error {
if schema.known(key) {
continue
}
envPath := func(p string) string { return envName(envPrefix, p) }
top, _, _ := strings.Cut(key, ".")
hintKey := key
if !schema.section(top, o.hints) {
ek.Delete(key)
continue
fixed, ok := schema.underscoredSection(key, o.hints)
if !ok {
ek.Delete(key)
continue
}
hintKey = fixed
}
msg := fmt.Sprintf("unknown environment variable %s (%s)", envVars[key], key)
if hint := schema.unknownKey(key, o.hints, func(p string) string { return envName(envPrefix, p) }); hint != "" {
hint := ""
switch {
case hintKey != key && schema.known(hintKey):
hint = fmt.Sprintf("did you mean %s?", envPath(hintKey))
case hintKey != key:
hint = schema.unknownKey(hintKey, o.hints, envPath)
default:
hint = schema.unknownKey(key, o.hints, envPath)
}
if hint != "" {
msg += ": " + hint
}
errs = append(errs, msg)
Expand Down
6 changes: 3 additions & 3 deletions confx/sections.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ import (
// Database is the connection section.
type Database struct {
URL string `koanf:"url" doc:"PostgreSQL connection URL, e.g. postgres://user:pass@host:5432/db. Also honours standard PG* env vars when empty."`
MaxConns int32 `koanf:"max_conns" doc:"Maximum pooled connections."`
ConnectTimeout time.Duration `koanf:"connect_timeout" doc:"Timeout for establishing a connection."`
MaxConns int32 `koanf:"max_conns" doc:"Maximum pooled connections; 0 uses the pgx pool default (the larger of 4 and the number of CPUs)."`
ConnectTimeout time.Duration `koanf:"connect_timeout" doc:"Timeout for establishing a connection (must be positive)."`
StatementTimeout time.Duration `koanf:"statement_timeout" doc:"Per-statement timeout applied to every request (0 disables). Keep it below the HTTP request timeout so a slow statement fails with SQLSTATE 57014 (a timeout error the client can act on) before the request is cut off."`
}

Expand Down Expand Up @@ -116,7 +116,7 @@ type TX struct {
// Watch is the DDL watch (dev mode) section.
type Watch struct {
Enabled bool `koanf:"enabled" doc:"Re-introspect and hot-swap the schema on DDL changes (dev only; refuses to combine with schema.cache_path)."`
PollInterval time.Duration `koanf:"poll_interval" doc:"Poll interval used when event triggers cannot be installed."`
PollInterval time.Duration `koanf:"poll_interval" doc:"Poll interval used when event triggers cannot be installed (must be positive)."`
Channel string `koanf:"channel" doc:"NOTIFY channel used by the DDL event trigger."`
}

Expand Down
32 changes: 32 additions & 0 deletions confx/strict.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,38 @@ func (s keySchema) section(name string, h hints) bool {
return len(name) >= 4 && closest(name, tops) != ""
}

// underscoredSection reports whether key, an environment key without a
// section of its own, starts with a section name of the schema (or of a
// moved or removed key) followed by "_": the mapping of an environment
// variable that doubled the underscore after the section
// (PREFIX_ROLES__ALLOWED is roles_allowed). It returns key with that "_"
// read as the section separator (roles.allowed), preferring the longest
// section name.
func (s keySchema) underscoredSection(key string, h hints) (string, bool) {
best := ""
consider := func(name string) {
if strings.HasPrefix(key, name+"_") && len(name) > len(best) {
best = name
}
}
for p, kind := range s {
if !strings.Contains(p, ".") && kind != leafKey {
consider(p)
}
}
for _, m := range []map[string]string{h.moved, h.removed} {
for old := range m {
if top, _, ok := strings.Cut(old, "."); ok {
consider(top)
}
}
}
if best == "" {
return "", false
}
return best + "." + key[len(best)+1:], true
}

// unknownKey describes an unknown key: where it moved to, why it was
// removed, or the closest known or moved key; name renders a path for the
// message.
Expand Down
47 changes: 47 additions & 0 deletions confx/strict_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package confx
import (
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -196,3 +197,49 @@ legacy:
}
}
}

func TestLoadRejectsDoubledUnderscoreAfterSection(t *testing.T) {
for env, want := range map[string]string{
"PDBX_ROLES__ALLOWED": "unknown environment variable PDBX_ROLES__ALLOWED (roles_allowed): did you mean PDBX_ROLES_ALLOWED?",
"PDBX_AUTH__MODE": "unknown environment variable PDBX_AUTH__MODE (auth_mode): did you mean PDBX_AUTH_MODE?",
"PDBX_FILTERS__INDEXED__ONLY": "unknown environment variable PDBX_FILTERS__INDEXED__ONLY (filters_indexed_only): did you mean PDBX_FILTERS_INDEXED__ONLY?",
"PDBX_AUTH__JWT_SECRET": "unknown environment variable PDBX_AUTH__JWT_SECRET (auth_jwt.secret): did you mean PDBX_AUTH_JWT_SECRET?",
"PDBX_ROLES__NO__SUCH__THING": "unknown environment variable PDBX_ROLES__NO__SUCH__THING (roles_no_such_thing)",
"PDBX_RLS__ENABLED": "unknown environment variable PDBX_RLS__ENABLED (rls_enabled): moved to PDBX_ROLES_SWITCH",
} {
t.Run(env, func(t *testing.T) {
t.Setenv(env, "x")
cfg := pdbqDefaults()
err := Load("PDBX_", "", &cfg)
if err == nil || !strings.Contains(err.Error(), want) {
t.Fatalf("err = %v, want %q", err, want)
}
})
}
t.Setenv("PDBX_UNRELATED__THING", "1")
t.Setenv("PDBX_TEST_DATABASE_URL", "postgres://test")
cfg := pdbqDefaults()
if err := Load("PDBX_", "", &cfg); err != nil {
t.Fatalf("variables outside every section must stay ignored: %v", err)
}
}

func TestValidateSharedDurations(t *testing.T) {
for want, errs := range map[string][]string{
"database.max_conns must be >= 0": ValidateDatabase(Database{MaxConns: -1, ConnectTimeout: time.Second}),
"database.connect_timeout must be > 0": ValidateDatabase(Database{MaxConns: 1}),
"database.statement_timeout must be >= 0": ValidateDatabase(Database{MaxConns: 1, ConnectTimeout: time.Second, StatementTimeout: -time.Second}),
"auth.jwt.jwks_cache_ttl must be > 0": ValidateIdentity(Auth{Mode: "jwt", JWT: JWT{JWKSURL: "https://idp.example/jwks", RoleClaimPath: "role"}}, Roles{Switch: true}, Claims{}),
"watch.poll_interval must be > 0": ValidateWatch(Watch{Enabled: true, Channel: "c"}, ""),
} {
if !slices.ContainsFunc(errs, func(e string) bool { return strings.HasPrefix(e, want) }) {
t.Errorf("want %q, got %q", want, errs)
}
}
if errs := ValidateDatabase(Database{ConnectTimeout: time.Second}); len(errs) != 0 {
t.Errorf("max_conns 0 or statement_timeout 0 rejected: %q", errs)
}
if errs := ValidateWatch(Watch{Channel: "c"}, ""); len(errs) != 0 {
t.Errorf("disabled watch checked: %q", errs)
}
}
6 changes: 3 additions & 3 deletions confx/testdata/pdbq.example.yaml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
database:
# PostgreSQL connection URL, e.g. postgres://user:pass@host:5432/db. Also honours standard PG* env vars when empty.
url: ""
# Maximum pooled connections.
# Maximum pooled connections; 0 uses the pgx pool default (the larger of 4 and the number of CPUs).
max_conns: 10
# Timeout for establishing a connection.
# Timeout for establishing a connection (must be positive).
connect_timeout: "10s"
# Per-statement timeout applied to every request (0 disables). Keep it below the HTTP request timeout so a slow statement fails with SQLSTATE 57014 (a timeout error the client can act on) before the request is cut off.
statement_timeout: "25s"
Expand Down Expand Up @@ -115,7 +115,7 @@ transactions:
watch:
# Re-introspect and hot-swap the schema on DDL changes (dev only; refuses to combine with schema.cache_path).
enabled: false
# Poll interval used when event triggers cannot be installed.
# Poll interval used when event triggers cannot be installed (must be positive).
poll_interval: "5s"
# NOTIFY channel used by the DDL event trigger.
channel: "pdbq_ddl"
Expand Down
30 changes: 27 additions & 3 deletions confx/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,24 @@ func InvalidConfig(errs []string) error {
return fmt.Errorf("invalid config:\n - %s", strings.Join(errs, "\n - "))
}

// ValidateDatabase checks the database section's numbers: max_conns must
// not be negative (0 uses the pgx pool default), connect_timeout must be
// positive (0 would wait for a connection forever) and statement_timeout
// not negative (0 disables it).
func ValidateDatabase(d Database) []string {
var errs []string
if d.MaxConns < 0 {
errs = append(errs, "database.max_conns must be >= 0 (0 uses the pool default)")
}
if d.ConnectTimeout <= 0 {
errs = append(errs, "database.connect_timeout must be > 0")
}
if d.StatementTimeout < 0 {
errs = append(errs, "database.statement_timeout must be >= 0 (0 disables it)")
}
return errs
}

// ValidateErrors checks errors.detail (see [pgexec.ParseDetail]).
func ValidateErrors(e Errors) []string {
if _, err := pgexec.ParseDetail(e.Detail); err != nil {
Expand All @@ -33,7 +51,7 @@ func ValidateErrors(e Errors) []string {
// ValidateIdentity checks the auth, roles and claims sections together:
// the auth mode; in jwt mode a secret, secret file or JWKS URL (a secret
// file must be readable), the role claim path and a non-negative leeway;
// in headers mode the prefix, the claim names (auth.ValidHeaderClaim) and
// a positive JWKS cache TTL with a JWKS URL; in headers mode the prefix, the claim names (auth.ValidHeaderClaim) and
// at least one trusted proxy; every trusted_proxies entry; mint_type's
// shape and secret; the role names (pgexec.ValidRole), and an anonymous
// role in mode none while roles switch; the claims prefix
Expand Down Expand Up @@ -62,6 +80,9 @@ func ValidateIdentity(a Auth, r Roles, c Claims) []string {
if j.Leeway < 0 {
add("auth.jwt.leeway must be >= 0")
}
if j.JWKSURL != "" && j.JWKSCacheTTL <= 0 {
add("auth.jwt.jwks_cache_ttl must be > 0")
}
if a.Mode == auth.ModeJWT {
if j.Secret == "" && j.SecretFile == "" && j.JWKSURL == "" {
add("auth.jwt.secret, auth.jwt.secret_file or auth.jwt.jwks_url is required in auth mode jwt (use auth.mode: none to accept no credentials)")
Expand Down Expand Up @@ -136,10 +157,13 @@ func ValidateTX(t TX) []string {
return errs
}

// ValidateWatch checks the watch section against schema.cache_path and the
// channel name.
// ValidateWatch checks the enabled watch section: the poll interval, the
// channel name, and that schema.cache_path is not set.
func ValidateWatch(w Watch, cachePath string) []string {
var errs []string
if w.Enabled && w.PollInterval <= 0 {
errs = append(errs, "watch.poll_interval must be > 0")
}
if w.Enabled && cachePath != "" {
errs = append(errs, "watch.enabled cannot be combined with schema.cache_path")
}
Expand Down
12 changes: 12 additions & 0 deletions docs/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,15 @@ Go API changes:
without `Run` writing back into the configuration, and `OnChange` is
`func(ctx context.Context, cat *introspect.Catalog)` with `Run`'s
context.

### Stricter shared validation

- `Catalog.Schemas` is in the order passed to `Introspect` (it used to be
sorted, and the caller's slice with it). Code that relied on the sorted
order must sort a copy.
- `PDBQ_ROLES__ALLOWED`-style variables (a doubled underscore right after
the section) are errors with a did-you-mean hint; they used to be
ignored.
- New `confx.ValidateDatabase`; `ValidateIdentity` checks
`auth.jwt.jwks_cache_ttl` when `auth.jwt.jwks_url` is set, and
`ValidateWatch` checks `watch.poll_interval` when the watch is enabled.
19 changes: 11 additions & 8 deletions introspect/catalog.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,14 @@ type Catalog struct {
// ServerVersionNum is current_setting('server_version_num'), e.g.
// 180001 for 18.1. Gate version-dependent SQL on it rather than parsing
// ServerVersion. [Catalog.Hash] covers its major part only.
ServerVersionNum int `json:"server_version_num"`
Schemas []string `json:"schemas"`
Tables []*Table `json:"tables"`
Enums []*Enum `json:"enums"`
Composites []*Composite `json:"composites"`
ServerVersionNum int `json:"server_version_num"`
// Schemas are the introspected schemas in the order given to
// [Introspect], which products treat as a priority order (the first
// schema is the primary one). [Catalog.Hash] ignores their order.
Schemas []string `json:"schemas"`
Tables []*Table `json:"tables"`
Enums []*Enum `json:"enums"`
Composites []*Composite `json:"composites"`
// [Introspect] orders Functions by schema, then name, then input parameters
// (Args): fewer parameters first, then parameter by parameter by type
// schema and type name. PostgreSQL identifies a function by exactly
Expand Down Expand Up @@ -736,6 +739,7 @@ func (c *Catalog) Hash() (string, error) {
Domains: slices.Clone(c.Domains),
}
v.sortStable()
slices.Sort(v.Schemas)
b, err := json.Marshal(v)
if err != nil {
return "", err
Expand All @@ -744,12 +748,11 @@ func (c *Catalog) Hash() (string, error) {
return hex.EncodeToString(sum[:]), nil
}

// sortStable puts the catalog's top-level slices in the canonical order
// [Introspect] returns: schemas by name; tables, enums, composites, ranges
// sortStable puts the catalog's top-level slices other than Schemas in the
// canonical order [Introspect] returns: tables, enums, composites, ranges
// and domains by schema then name; extensions by name; and functions by
// [compareFunctions].
func (c *Catalog) sortStable() {
slices.Sort(c.Schemas)
byName := func(as, an, bs, bn string) int {
return cmp.Or(strings.Compare(as, bs), strings.Compare(an, bn))
}
Expand Down
13 changes: 13 additions & 0 deletions introspect/hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,16 @@ func TestFunctionOrder(t *testing.T) {
}
}
}

func TestHashIgnoresSchemaOrder(t *testing.T) {
a, b := hashCatalog(), hashCatalog()
b.Schemas = []string{"a", "b"}
ha, _ := a.Hash()
hb, _ := b.Hash()
if ha != hb {
t.Fatalf("hash depends on schema order: %s != %s", ha, hb)
}
if !slices.Equal(a.Schemas, []string{"b", "a"}) {
t.Fatalf("Hash reordered Schemas: %v", a.Schemas)
}
}
2 changes: 1 addition & 1 deletion introspect/introspect.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func Introspect(ctx context.Context, db Querier, schemas []string) (*Catalog, er
if len(schemas) == 0 {
schemas = []string{"public"}
}
cat := &Catalog{FormatVersion: CatalogFormatVersion, Schemas: schemas}
cat := &Catalog{FormatVersion: CatalogFormatVersion, Schemas: slices.Clone(schemas)}

if err := db.QueryRow(ctx, `SELECT current_setting('server_version'), current_setting('server_version_num')::int`).
Scan(&cat.ServerVersion, &cat.ServerVersionNum); err != nil {
Expand Down
Loading
Loading