diff --git a/README.md b/README.md index ad74994..4102f49 100644 --- a/README.md +++ b/README.md @@ -26,12 +26,12 @@ fixture both products are tested against. | `watch` | `Watcher`: DDL event trigger + `LISTEN/NOTIFY` (`TriggerName`, `Channel`), hash-polling fallback when the trigger cannot be installed → `OnChange(*Catalog)` | | `postgis` | spatial value layer: flavour detection, GeoJSON/WKT/EWKT parsing to one bound parameter, filter `Ops`, derived accessors, transform/simplify/buffer/KNN/distance SQL (`BufferSQL`, metres on geography; `DistanceSQL`, metres on the spheroid with `SpheroidDistanceSQL`), GeoJSON output with a bound coordinate precision (`OutputPrecisionSQL`/`OutputJSONPrecisionSQL`, `CheckPrecision`); `postgis_raster` columns (`IsRaster`): header-only metadata `RasterAccessors` (width, height, bands, SRID, pixel size, envelope as GeoJSON), `RasterValueSQL` (`ST_Value` at a bound point, reprojected to the raster's SRID), `RasterSummaryStatsSQL` (`ST_SummaryStats` of a band as a JSON object), `RasterIntersectsSQL` (served by a GiST index on `ST_ConvexHull(col)`) and `Raster*Cost` weights for cost estimators | | `contrib` | operator vocabularies + value coercion for full-text search (`tsvector`, and `to_tsvector` over text and json/jsonb documents, with `ts_headline` snippets), `pg_trgm`, `unaccent`, `fuzzystrmatch`, `hstore`, `ltree`, `citext`, `intarray`, range/multirange, `inet`/`cidr`, pgvector (`vector`, `halfvec`, `sparsevec`, plus bit distances on `bit`/`varbit`), `cube` and `earthdistance` (`earth` columns, `<@>` on `point`) columns (see [Contrib vocabularies](#contrib-vocabularies)): `ForColumn`/`ForType` lookup bound to the extension's schema, filter `Op`s, ordering `Expr`s (`Expr.Score` marks the selectable similarity/distance values, `Expr.Derived` the per-use parameterised values such as an hstore key's value, `Expr.OrderSQL` the index-served ordering form), `Accessor`s, value `Codec`s, `Op.RankSQL`/`Op.HeadlineSQL` with validated `HeadlineOptions`, `HeadlineDocumentSQL`/`HeadlineDocumentCost` to bound and price a headline's document | -| `auth` | `Authenticator`: JWT (HS*, JWKS RS*/ES* with a kid-matched cache refreshed by one shared background fetch, stale keys served for one extra TTL during endpoint outages, failure backoff, endpoint details logged and never returned to clients), trusted-gateway claim headers with `TrustedProxies` (one spelling per claim: `User-Id` is `user_id`; underscores, repeats and case-folded duplicates are rejected; optional `HeaderClaims` allowlist; the gateway must strip every client-supplied prefixed header), role resolution and allowlist; `ErrInvalidToken` / `ErrRoleNotAllowed` | -| `pgexec` | pool `Connect` (connections to PostgreSQL < 14 fail), `RunTx` (isolation, `SET LOCAL ROLE`, claims via `set_config(prefix.k, v, true)`, 40001/40P01 retries), `QueryTx` (one pipelined round trip), `Savepoint` (run a step in a SAVEPOINT inside a `RunTx` callback; a failure rolls back to it and comes back as `*RolledBackError`, so the transaction goes on), `Observer` (per-attempt duration and error via `TxOptions.Observer`, `Observe` for direct statements), `Identity`, `Classify` PG errors into classes with `dev`/`prod`/`strict` message policies (malformed tsquery/ltree operands, unknown text search configs and raster/geometry SRID mismatches are user input), `QuoteIdent`/`ValidRole`/`ValidClaimKey` | +| `auth` | `Authenticator`: JWT (HS*, JWKS RS*/ES* with a kid-matched cache refreshed by one shared background fetch, stale keys served for one extra TTL during endpoint outages, failure backoff, endpoint details logged and never returned to clients), trusted-gateway claim headers with `TrustedProxies` (one spelling per claim: `User-Id` is `user_id`; underscores, repeats and case-folded duplicates are rejected; optional `HeaderClaims` allowlist; the gateway must strip every client-supplied prefixed header), typed `Mode` (`jwt`, `headers`, `none`; `New` rejects anything else, a headers mode without trusted proxies, and a jwt mode without a key), case-insensitive `Bearer`, clock-skew `Leeway`, role claim paths (`app_metadata.role`, `realm_access.roles[0]`), role resolution and allowlist, optional anonymous access, `SkipRoleSwitch`; `ErrInvalidToken` / `ErrAuthRequired` / `ErrRoleNotAllowed`, and `Challenge` for the `WWW-Authenticate` value | +| `pgexec` | pool `Connect` (connections to PostgreSQL < 14 fail), `RunTx` (isolation, `SET LOCAL ROLE`, claims via `set_config(prefix.k, v, true)` and optionally as one JSON setting, 40001/40P01 retries), `QueryTx` (one pipelined round trip), `Savepoint` (run a step in a SAVEPOINT inside a `RunTx` callback; a failure rolls back to it and comes back as `*RolledBackError`, so the transaction goes on), `Observer` (per-attempt duration and error via `TxOptions.Observer`, `Observe` for direct statements), `Identity`, `Classify` PG errors into classes with `dev`/`prod`/`strict` message policies (21* cardinality violations, malformed tsquery/ltree operands, unknown text search configs and raster/geometry SRID mismatches are user input), `QuoteIdent`/`ValidRole`/`ValidClaimKey` | | `jwtmint` | composite-typed function results → signed HS256 JWT (`MintsFunction`, `Mint`, `Sign`) | -| `httpx` | CORS + preflight, gzip, `Healthz`, `ListenAndServe` with the standard timeouts and graceful shutdown | +| `httpx` | CORS (`CORSPolicy`: origins, preflight methods, exposed headers) + preflight, `AddVary`, gzip, `Healthz`, `ListenAndServe` with the standard timeouts and graceful shutdown | | `metrics` | Prometheus instrumentation on a per-instance registry (or a caller's `Registerer` + `ConstLabels`): HTTP `Middleware` (requests, duration, in flight by route class, method, status class; `SetRoute`), `DBObserver` (a `pgexec.Observer`: duration, errors by SQLSTATE class, retries), `RegisterPool` (pgxpool `Stat`), `SchemaRebuilt`, `ObserveCompile`, product counters via `NewCounter`; `NewRegistry` + `RegisterPoolOn` for several instances (one per contract) on one registry; a nil `*Metrics` records nothing (see [Metrics](#metrics)) | -| `confx` | koanf `Load` (defaults < YAML < env < changed flags), env key mapper (`_` → `.`, `__` → `_`, comma-separated lists), `ExampleYAML` from `koanf`/`doc` tags, `Discover`, `ParseTrustedProxy`, shared config sections (`Database`, `Schema`, `Filters`, `RLS`/`Auth`, `TX`, `Watch`, `Errors`, `Plugins`, `Log`, `Metrics`, `Contract` list entries) + `Validate*` helpers (`ValidateContracts`), `AuthConfig(RLS)` | +| `confx` | strict koanf `Load` (defaults < YAML < env < changed flags; unknown keys are errors naming the key they moved to or the closest valid one, `MovedKeys`/`WithMoved`), env key mapper (`_` → `.`, `__` → `_`, comma-separated lists), `ExampleYAML` from `koanf`/`doc` tags, `Discover`, `ParseTrustedProxy`, shared config sections (`Database`, `Schema`, `Filters`, `Auth`/`JWT`/`Headers`, `Roles`, `Claims`, `TX`, `Watch`, `Errors`, `Plugins[S]` with typed per-plugin settings, `Log`, `Metrics`, `Contract` list entries) + `Validate*` helpers (`ValidateIdentity`, `ValidatePluginNames`, `ValidateContracts`), `AuthConfig(Auth, Roles)`, `IdentityWarnings` | | `plugin` | `Plugin`, `Registry` (priority + registration order), `CatalogHook`, `InflectionHook`, `TransformCatalog`, `Inflector` chain | | `smartcomments/catalog` | catalog half of the smart-comments plugin (`@omit`, `@primaryKey`, `@unique`, `@foreignKey`, `@notNull`, `@filterable`, `@anyelement` / `@anycompatible` on polymorphic functions, `@name` index) — products add their transport half on top | | `testutil` | `FixtureSQL` (embedded DDL) and `FixtureCatalog()`, the one fixture both products test against; `testutil/cmd/fixture` prints the SQL; `drift_test.go` is the fixture drift gate | @@ -52,7 +52,7 @@ cat, _ := introspect.Introspect(ctx, pool, cfg.Schema.Schemas) // or cache.Load( // ... the product builds its schema / routes from cat and runs its own compiler ... err := pgexec.RunTx(ctx, pool, pgexec.TxOptions{Isolation: iso, MaxRetries: 2, RLS: true}, - pgexec.Identity{Role: role, Claims: claims, ClaimsPrefix: "pdbq.claims"}, + pgexec.Identity{Role: role, Claims: claims, ClaimsPrefix: "jwt.claims"}, func(q pgexec.Querier) error { return q.QueryRow(ctx, sql, args...).Scan(&data) }) ``` @@ -81,8 +81,12 @@ Both products embed the `confx` sections in their own `Config` struct (the product owns `Server` and its defaults such as `watch.channel` and the claim header prefix), wrap `plugin.Registry` with their transport-specific hooks, and register `smartcomments/catalog.New()` inside their smart-comments -plugin. `rls.claims_prefix` defaults to `pdbq.claims` in both so RLS policies -work unchanged behind either server; `watch.TriggerName` differs +plugin. `claims.prefix` defaults to `jwt.claims` (PostGraphile's namespace) +in both, and `claims.json_setting` can add PostgREST's `request.jwt.claims`, +so RLS policies work unchanged behind either server. The claim header +prefix stays per product (`X-Pdbq-Claim-` / `X-Pdbr-Claim-`): names SQL +sees are product-neutral so policies port, while names on the wire between +a gateway and the server are namespaced like every other product header; `watch.TriggerName` differs (`pdbq_watch` / `pdbr_watch`) so both can watch one database. Until the first tag lands the products point at a sibling checkout: diff --git a/auth/auth.go b/auth/auth.go index 80f6d78..6e01dda 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -16,14 +16,42 @@ import ( "github.com/golang-jwt/jwt/v5" ) +// Mode is the credential source of an Authenticator. +type Mode string + +const ( + // ModeJWT verifies a bearer JWT: HS* with a shared secret, RS*/ES* + // with keys from a JWKS endpoint. + ModeJWT Mode = "jwt" + // ModeHeaders reads claims from headers set by a trusted gateway. + ModeHeaders Mode = "headers" + // ModeNone accepts no credentials: every request is anonymous. + ModeNone Mode = "none" +) + +// ParseMode returns the Mode spelled s, or an error naming the valid modes. +func ParseMode(s string) (Mode, error) { + switch m := Mode(s); m { + case ModeJWT, ModeHeaders, ModeNone: + return m, nil + } + return "", fmt.Errorf("unknown auth mode %q: use jwt, headers or none", s) +} + // ErrInvalidToken marks a present-but-unusable credential: malformed // Authorization header, bad signature, expired, wrong issuer/audience, JWKS -// miss or outage, claim headers from an untrusted peer, or malformed, -// repeated, conflicting or unlisted claim headers. Products map it to 401. +// miss or outage, a role claim that is not a string, claim headers from an +// untrusted peer, or malformed, repeated, conflicting or unlisted claim +// headers. Products map it to 401. var ErrInvalidToken = errors.New("invalid token") +// ErrAuthRequired marks a request without credentials while anonymous +// access is off (Config.AnonymousRole is empty). Products map it to 401. +var ErrAuthRequired = errors.New("authentication required") + // ErrRoleNotAllowed marks a valid credential whose role claim is outside the -// AllowedRoles policy. Products map it to 403 (or 401 for pdbq parity). +// AllowedRoles policy, or that resolves to no role at all. Products map it +// to 403 (or 401 for pdbq parity). var ErrRoleNotAllowed = errors.New("role not allowed") // authError carries the sentinel for errors.Is while keeping the message @@ -47,14 +75,11 @@ func invalidToken(msg string, cause error) error { return &authError{kind: ErrInvalidToken, cause: cause, msg: msg} } -// Config is the claim-source configuration; products fill it from their own -// config sections (see confx.RLS / confx.Auth). +// Config is the credential and role configuration; products fill it from +// their auth and roles config sections (see confx.AuthConfig). type Config struct { - // Enabled false makes Authenticate a no-op returning no claims and no - // role (the product runs as the connection role). - Enabled bool - // Mode is "jwt", "headers", or "none". - Mode string + // Mode selects the credential source; New rejects any other value. + Mode Mode // JWTSecret verifies HS256/384/512 tokens; ignored when JWKSURL is set. JWTSecret string // JWKSURL enables asymmetric verification (RS*/ES*) with a key cache. @@ -63,6 +88,11 @@ type Config struct { // JWTIssuer / JWTAudience are checked when non-empty. JWTIssuer string JWTAudience string + // Leeway is the clock skew tolerated on exp, nbf and iat. + Leeway time.Duration + // RoleClaimPath locates the role in a JWT's claims (see + // ValidateClaimPath); empty means "role". + RoleClaimPath string // HeaderPrefix is the claim-header prefix in headers mode // (pdbq: X-Pdbq-Claim-, pdbr: X-Pdbr-Claim-), matched // case-insensitively. The rest of the header name must be @@ -77,81 +107,172 @@ type Config struct { // starts with the prefix, in any letter case, before adding its own. HeaderPrefix string // HeaderClaims, when non-empty, lists the claim keys (user_id, not - // User-Id) that claim headers may carry; RoleClaim is always allowed. - // A request with any other claim header is rejected with + // User-Id) that claim headers may carry; HeaderRoleClaim is always + // allowed. A request with any other claim header is rejected with // ErrInvalidToken. HeaderClaims []string - // TrustedProxies gates claim headers by peer address; nil trusts every - // peer, an empty non-nil slice trusts none. + // HeaderRoleClaim is the claim carrying the role in headers mode; + // empty means "role". + HeaderRoleClaim string + // TrustedProxies are the peers allowed to send claim headers; headers + // mode requires at least one. TrustedProxies []netip.Prefix - // RoleClaim names the claim carrying the database role. - RoleClaim string - DefaultRole string + // DefaultRole is the role of an authenticated request without a role + // claim. + DefaultRole string + // AnonymousRole is the role of a request without credentials (and of + // every request in ModeNone, and of an authenticated request when + // DefaultRole is empty too). Empty refuses requests without + // credentials with ErrAuthRequired. AnonymousRole string // AllowedRoles restricts claim-supplied roles; empty allows any. AllowedRoles []string + // SkipRoleSwitch makes Authenticate return "" as the role of every + // accepted request, so it runs as the connection role. Credentials are + // still verified, roles resolved and AllowedRoles enforced. + SkipRoleSwitch bool // Logger receives JWKS fetch failures, with the endpoint URL and cause // that clients never see; nil uses slog.Default(). Logger *slog.Logger } // Authenticator turns an HTTP request into (claims, role) per the configured -// claim source: verified JWT, trusted gateway headers, or none. +// credential source: verified JWT, trusted gateway headers, or none. type Authenticator struct { cfg Config // jwks verifies asymmetric tokens when JWKSURL is set. jwks *jwksCache - // headerClaims is the HeaderClaims allowlist plus RoleClaim; nil + // rolePath locates the role in JWT claims. + rolePath claimPath + // headerClaims is the HeaderClaims allowlist plus HeaderRoleClaim; nil // allows every claim. headerClaims map[string]bool } -// New builds an Authenticator. Invalid TrustedProxies entries cannot occur -// (they are typed); a nil slice means every peer is trusted. -func New(cfg Config) *Authenticator { +// New builds an Authenticator. It returns an error for an unknown mode, a +// JWT mode without a secret or JWKS URL, a headers mode without a header +// prefix or trusted proxies, an invalid role claim path or header role +// claim, and a negative leeway. +func New(cfg Config) (*Authenticator, error) { + if _, err := ParseMode(string(cfg.Mode)); err != nil { + return nil, err + } + if cfg.Leeway < 0 { + return nil, fmt.Errorf("auth: negative leeway %s", cfg.Leeway) + } + if cfg.RoleClaimPath == "" { + cfg.RoleClaimPath = "role" + } + if cfg.HeaderRoleClaim == "" { + cfg.HeaderRoleClaim = "role" + } a := &Authenticator{cfg: cfg} - if cfg.JWKSURL != "" { - log := cfg.Logger - if log == nil { - log = slog.Default() + switch cfg.Mode { + case ModeJWT: + if cfg.JWTSecret == "" && cfg.JWKSURL == "" { + return nil, errors.New("auth: jwt mode needs a JWT secret or a JWKS URL") } - a.jwks = newJWKSCache(cfg.JWKSURL, cfg.JWKSCacheTTL, log) - } - if len(cfg.HeaderClaims) > 0 { - a.headerClaims = make(map[string]bool, len(cfg.HeaderClaims)+1) - for _, c := range cfg.HeaderClaims { - a.headerClaims[c] = true + p, err := parseClaimPath(cfg.RoleClaimPath) + if err != nil { + return nil, err } - if cfg.RoleClaim != "" { - a.headerClaims[cfg.RoleClaim] = true + a.rolePath = p + if cfg.JWKSURL != "" { + log := cfg.Logger + if log == nil { + log = slog.Default() + } + a.jwks = newJWKSCache(cfg.JWKSURL, cfg.JWKSCacheTTL, log) + } + case ModeHeaders: + if cfg.HeaderPrefix == "" { + return nil, errors.New("auth: headers mode needs a claim header prefix") + } + if len(cfg.TrustedProxies) == 0 { + return nil, errors.New("auth: headers mode needs at least one trusted proxy") + } + if !ValidHeaderClaim(cfg.HeaderRoleClaim) { + return nil, fmt.Errorf("auth: role claim %q cannot be sent as a claim header", cfg.HeaderRoleClaim) + } + if len(cfg.HeaderClaims) > 0 { + a.headerClaims = make(map[string]bool, len(cfg.HeaderClaims)+1) + for _, c := range cfg.HeaderClaims { + a.headerClaims[c] = true + } + a.headerClaims[cfg.HeaderRoleClaim] = true } } - return a + return a, nil } +// Mode returns the credential source. +func (a *Authenticator) Mode() Mode { return a.cfg.Mode } + // Authenticate never fails open: a present-but-invalid credential is an -// error; an absent credential yields the anonymous role. Errors wrap -// ErrInvalidToken or ErrRoleNotAllowed. +// error, and an absent one yields the anonymous role, or ErrAuthRequired +// when there is none. Errors wrap ErrInvalidToken, ErrAuthRequired or +// ErrRoleNotAllowed. The role is "" with SkipRoleSwitch. func (a *Authenticator) Authenticate(r *http.Request) (map[string]any, string, error) { - if !a.cfg.Enabled { - return nil, "", nil - } switch a.cfg.Mode { - case "jwt": + case ModeJWT: return a.fromJWT(r) - case "headers": + case ModeHeaders: return a.fromHeaders(r) - default: - return map[string]any{}, a.cfg.AnonymousRole, nil } + return map[string]any{}, a.switchTo(a.cfg.AnonymousRole), nil +} + +// Challenge returns the WWW-Authenticate value (RFC 6750) of the response +// to an Authenticate error: Bearer for ErrAuthRequired, with +// error="invalid_token" for ErrInvalidToken and error="insufficient_scope" +// for ErrRoleNotAllowed; "" for any other error. +func Challenge(err error) string { + switch { + case errors.Is(err, ErrAuthRequired): + return "Bearer" + case errors.Is(err, ErrInvalidToken): + return `Bearer error="invalid_token"` + case errors.Is(err, ErrRoleNotAllowed): + return `Bearer error="insufficient_scope"` + } + return "" +} + +// anonymous answers a request that carries no credentials. +func (a *Authenticator) anonymous() (map[string]any, string, error) { + if a.cfg.AnonymousRole == "" { + return nil, "", &authError{kind: ErrAuthRequired, msg: "authentication required"} + } + return map[string]any{}, a.switchTo(a.cfg.AnonymousRole), nil +} + +func (a *Authenticator) switchTo(role string) string { + if a.cfg.SkipRoleSwitch { + return "" + } + return role +} + +// bearerToken extracts the token of an "Authorization: Bearer " +// header; the scheme is case-insensitive (RFC 7235). +func bearerToken(authz string) (string, bool) { + scheme, token, ok := strings.Cut(authz, " ") + if !ok || !strings.EqualFold(scheme, "Bearer") { + return "", false + } + token = strings.TrimLeft(token, " ") + if token == "" || strings.ContainsAny(token, " \t") { + return "", false + } + return token, true } func (a *Authenticator) fromJWT(r *http.Request) (map[string]any, string, error) { authz := r.Header.Get("Authorization") if authz == "" { - return map[string]any{}, a.cfg.AnonymousRole, nil + return a.anonymous() } - tokenStr, ok := strings.CutPrefix(authz, "Bearer ") + tokenStr, ok := bearerToken(authz) if !ok { return nil, "", invalidToken("malformed Authorization header", nil) } @@ -174,6 +295,7 @@ func (a *Authenticator) fromJWT(r *http.Request) (map[string]any, string, error) parserOpts := []jwt.ParserOption{ jwt.WithValidMethods(methods), jwt.WithExpirationRequired(), + jwt.WithLeeway(a.cfg.Leeway), } if a.cfg.JWTIssuer != "" { parserOpts = append(parserOpts, jwt.WithIssuer(a.cfg.JWTIssuer)) @@ -188,7 +310,23 @@ func (a *Authenticator) fromJWT(r *http.Request) (map[string]any, string, error) } return nil, "", invalidToken("invalid token: "+err.Error(), err) } - return a.resolve(map[string]any(claims)) + role, found, err := a.jwtRole(claims) + if err != nil { + return nil, "", err + } + return a.resolve(map[string]any(claims), role, found) +} + +func (a *Authenticator) jwtRole(claims map[string]any) (string, bool, error) { + v, ok := a.rolePath.lookup(claims) + if !ok { + return "", false, nil + } + s, ok := v.(string) + if !ok || s == "" { + return "", false, invalidToken("invalid token: role claim is not a non-empty string", nil) + } + return s, true, nil } func (a *Authenticator) fromHeaders(r *http.Request) (map[string]any, string, error) { @@ -201,7 +339,7 @@ func (a *Authenticator) fromHeaders(r *http.Request) (map[string]any, string, er } } if !present { - return map[string]any{}, a.cfg.AnonymousRole, nil + return a.anonymous() } if !a.peerTrusted(r.RemoteAddr) { return nil, "", invalidToken("claim headers from untrusted peer", nil) @@ -226,7 +364,11 @@ func (a *Authenticator) fromHeaders(r *http.Request) (map[string]any, string, er } claims[key] = vals[0] } - return a.resolve(claims) + role, found := claims[a.cfg.HeaderRoleClaim].(string) + if found && role == "" { + return nil, "", invalidToken("empty role claim header", nil) + } + return a.resolve(claims, role, found) } func hasPrefixFold(s, prefix string) bool { @@ -274,13 +416,10 @@ func HeaderClaimName(prefix, claim string) string { return http.CanonicalHeaderKey(prefix + strings.ReplaceAll(claim, "_", "-")) } -// peerTrusted reports whether the direct peer may supply claim headers. With -// no trusted proxies configured every peer is trusted (legacy behavior; the -// product logs a startup warning). An unparseable RemoteAddr fails closed. +// peerTrusted reports whether the direct peer may supply claim headers: its +// address lies in a TrustedProxies prefix. An unparseable RemoteAddr fails +// closed. func (a *Authenticator) peerTrusted(remoteAddr string) bool { - if a.cfg.TrustedProxies == nil { - return true - } ap, err := netip.ParseAddrPort(remoteAddr) if err != nil { return false @@ -294,25 +433,24 @@ func (a *Authenticator) peerTrusted(remoteAddr string) bool { return false } -// resolve extracts the database role from claims (falling back to -// DefaultRole, then AnonymousRole) and enforces the AllowedRoles policy on -// claim-supplied roles. -func (a *Authenticator) resolve(claims map[string]any) (map[string]any, string, error) { - role := a.cfg.DefaultRole - fromClaim := false - if v, ok := claims[a.cfg.RoleClaim]; ok { - if s, ok := v.(string); ok && s != "" { - role = s - fromClaim = true +// resolve picks the request role: the claimed role when found, else +// DefaultRole, else AnonymousRole. A claimed role must pass AllowedRoles, +// and a request that resolves to no role is refused unless SkipRoleSwitch +// is set (it would otherwise run as the connection role). +func (a *Authenticator) resolve(claims map[string]any, role string, fromClaim bool) (map[string]any, string, error) { + if !fromClaim { + role = a.cfg.DefaultRole + if role == "" { + role = a.cfg.AnonymousRole } } - if role == "" { - role = a.cfg.AnonymousRole - } if fromClaim && !a.roleAllowed(role) { return nil, "", &authError{kind: ErrRoleNotAllowed, msg: fmt.Sprintf("role %q is not allowed", role)} } - return claims, role, nil + if role == "" && !a.cfg.SkipRoleSwitch { + return nil, "", &authError{kind: ErrRoleNotAllowed, msg: "credential carries no role and no default role is configured"} + } + return claims, a.switchTo(role), nil } // roleAllowed applies AllowedRoles: empty list allows everything; otherwise diff --git a/auth/auth_test.go b/auth/auth_test.go index adb6c7d..fd271ff 100644 --- a/auth/auth_test.go +++ b/auth/auth_test.go @@ -15,15 +15,21 @@ import ( const testSecret = "test-secret" func testAuth() *Authenticator { - return New(Config{ - Enabled: true, + return mustNew(Config{ AnonymousRole: "anonymous", - RoleClaim: "role", Mode: "jwt", JWTSecret: testSecret, }) } +func mustNew(cfg Config) *Authenticator { + a, err := New(cfg) + if err != nil { + panic(err) + } + return a +} + func signToken(t *testing.T, claims jwt.MapClaims) string { t.Helper() tok, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(testSecret)) @@ -82,11 +88,9 @@ func TestJWTValidExpAccepted(t *testing.T) { func TestAllowedRoles(t *testing.T) { newAuth := func(allowed ...string) *Authenticator { - return New(Config{ - Enabled: true, + return mustNew(Config{ AnonymousRole: "anonymous", DefaultRole: "app_default", - RoleClaim: "role", AllowedRoles: allowed, Mode: "jwt", JWTSecret: testSecret, @@ -156,10 +160,8 @@ func headersAuth(trusted ...string) *Authenticator { } prefixes = append(prefixes, p) } - return New(Config{ - Enabled: true, + return mustNew(Config{ AnonymousRole: "anonymous", - RoleClaim: "role", Mode: "headers", HeaderPrefix: "X-Pdbq-Claim-", TrustedProxies: prefixes, @@ -184,17 +186,6 @@ func headersRequest(remoteAddr string) *http.Request { return r } -func TestHeadersNoTrustedProxiesAcceptsAnyPeer(t *testing.T) { - a := headersAuth() - _, role, err := a.Authenticate(headersRequest("203.0.113.7:4444")) - if err != nil { - t.Fatalf("legacy behavior broken: %v", err) - } - if role != "app_user" { - t.Fatalf("role = %q, want app_user", role) - } -} - func TestHeadersTrustedPeerAccepted(t *testing.T) { for _, tc := range []struct{ trusted, remote string }{ {"10.0.0.0/8", "10.1.2.3:9999"}, @@ -253,18 +244,8 @@ func TestMalformedAuthorizationHeader(t *testing.T) { } } -func TestDisabledIsNoop(t *testing.T) { - a := New(Config{Enabled: false, Mode: "jwt"}) - r := httptest.NewRequest("POST", "/graphql", nil) - r.Header.Set("Authorization", "Bearer garbage") - claims, role, err := a.Authenticate(r) - if err != nil || claims != nil || role != "" { - t.Fatalf("disabled auth = (%v, %q, %v), want (nil, \"\", nil)", claims, role, err) - } -} - func TestModeNoneIsAnonymous(t *testing.T) { - a := New(Config{Enabled: true, Mode: "none", AnonymousRole: "anonymous"}) + a := mustNew(Config{Mode: ModeNone, AnonymousRole: "anonymous"}) r := httptest.NewRequest("POST", "/graphql", nil) r.Header.Set("Authorization", "Bearer garbage") _, role, err := a.Authenticate(r) @@ -403,13 +384,13 @@ func TestHeadersEndToEndWireCanonicalization(t *testing.T) { } func TestHeadersClaimAllowlist(t *testing.T) { - a := New(Config{ - Enabled: true, - AnonymousRole: "anonymous", - RoleClaim: "app_role", - Mode: "headers", - HeaderPrefix: "X-Pdbr-Claim-", - HeaderClaims: []string{"user_id"}, + a := mustNew(Config{ + AnonymousRole: "anonymous", + HeaderRoleClaim: "app_role", + TrustedProxies: []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}, + Mode: "headers", + HeaderPrefix: "X-Pdbr-Claim-", + HeaderClaims: []string{"user_id"}, }) r := claimRequest(map[string][]string{"X-Pdbr-Claim-User-Id": {"1"}, "X-Pdbr-Claim-App-Role": {"app_user"}}) claims, role, err := a.Authenticate(r) diff --git a/auth/claimpath.go b/auth/claimpath.go new file mode 100644 index 0000000..90a83c4 --- /dev/null +++ b/auth/claimpath.go @@ -0,0 +1,96 @@ +package auth + +import ( + "fmt" + "strconv" + "strings" +) + +// claimPath is a parsed role claim path: object keys (string) and array +// indexes (int), applied in order. +type claimPath []any + +// ValidateClaimPath checks a role claim path, the subset of PostgREST's +// jwt-role-claim-key syntax pdbcore accepts: object keys separated by dots, +// with an optional leading dot, each a bare name (any characters but +// . [ ] " and spaces) or a double-quoted name (any characters but "), +// optionally followed by array indexes such as [0]. Examples: role, +// .app_metadata.role, realm_access.roles[0], "https://example.com/role". +func ValidateClaimPath(s string) error { + _, err := parseClaimPath(s) + return err +} + +func parseClaimPath(s string) (claimPath, error) { + bad := func(why string) (claimPath, error) { + return nil, fmt.Errorf("invalid role claim path %q: %s", s, why) + } + rest := strings.TrimPrefix(s, ".") + if rest == "" { + return bad("empty") + } + var p claimPath + for { + var key string + if strings.HasPrefix(rest, `"`) { + end := strings.IndexByte(rest[1:], '"') + if end < 0 { + return bad("unterminated quoted name") + } + key, rest = rest[1:end+1], rest[end+2:] + } else { + end := strings.IndexAny(rest, `.[]" `) + if end < 0 { + end = len(rest) + } + key, rest = rest[:end], rest[end:] + } + if key == "" { + return bad("empty name") + } + p = append(p, key) + for strings.HasPrefix(rest, "[") { + end := strings.IndexByte(rest, ']') + if end < 0 { + return bad("unterminated index") + } + n, err := strconv.Atoi(rest[1:end]) + if err != nil || n < 0 || rest[1] == '+' { + return bad("index must be a non-negative integer") + } + p = append(p, n) + rest = rest[end+1:] + } + if rest == "" { + return p, nil + } + if rest[0] != '.' { + return bad(fmt.Sprintf("unexpected %q", rest[0])) + } + rest = rest[1:] + } +} + +// lookup returns the value at p in claims. +func (p claimPath) lookup(claims map[string]any) (any, bool) { + var cur any = claims + for _, seg := range p { + switch s := seg.(type) { + case string: + m, ok := cur.(map[string]any) + if !ok { + return nil, false + } + if cur, ok = m[s]; !ok { + return nil, false + } + case int: + l, ok := cur.([]any) + if !ok || s >= len(l) { + return nil, false + } + cur = l[s] + } + } + return cur, true +} diff --git a/auth/jwks_test.go b/auth/jwks_test.go index 7acf145..4b0ea14 100644 --- a/auth/jwks_test.go +++ b/auth/jwks_test.go @@ -64,10 +64,8 @@ func jwksServer(t *testing.T, keys *[]map[string]string, fetches *atomic.Int32) } func jwksAuth(url string) *Authenticator { - return New(Config{ - Enabled: true, + return mustNew(Config{ AnonymousRole: "anonymous", - RoleClaim: "role", Mode: "jwt", JWKSURL: url, JWKSCacheTTL: time.Hour, @@ -293,10 +291,8 @@ func newJWKSFixture(t *testing.T, ttl time.Duration, gate chan struct{}) *jwksFi s.srv = httptest.NewServer(s) t.Cleanup(s.srv.Close) logs := &logBuffer{} - a := New(Config{ - Enabled: true, + a := mustNew(Config{ AnonymousRole: "anonymous", - RoleClaim: "role", Mode: "jwt", JWKSURL: s.srv.URL + "/internal/idp/jwks.json", JWKSCacheTTL: ttl, diff --git a/auth/modes_test.go b/auth/modes_test.go new file mode 100644 index 0000000..a9c0379 --- /dev/null +++ b/auth/modes_test.go @@ -0,0 +1,240 @@ +package auth + +import ( + "errors" + "net/http/httptest" + "net/netip" + "strings" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" +) + +func TestNewRejectsInvalidConfig(t *testing.T) { + proxies := []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")} + cases := map[string]struct { + cfg Config + want string + }{ + "unknown mode": {Config{Mode: "oauth"}, `unknown auth mode "oauth"`}, + "empty mode": {Config{}, `unknown auth mode ""`}, + "jwt without key": {Config{Mode: ModeJWT}, "jwt mode needs a JWT secret or a JWKS URL"}, + "headers no proxies": {Config{Mode: ModeHeaders, HeaderPrefix: "X-Claim-"}, "headers mode needs at least one trusted proxy"}, + "headers no prefix": {Config{Mode: ModeHeaders, TrustedProxies: proxies}, "headers mode needs a claim header prefix"}, + "headers role claim": {Config{Mode: ModeHeaders, HeaderPrefix: "X-Claim-", TrustedProxies: proxies, HeaderRoleClaim: "App-Role"}, `role claim "App-Role" cannot be sent`}, + "bad role claim path": {Config{Mode: ModeJWT, JWTSecret: testSecret, RoleClaimPath: "a..b"}, "invalid role claim path"}, + "negative leeway": {Config{Mode: ModeNone, Leeway: -time.Second}, "negative leeway"}, + "unterminated quoted": {Config{Mode: ModeJWT, JWTSecret: testSecret, RoleClaimPath: `"abc`}, "unterminated quoted name"}, + "bad index": {Config{Mode: ModeJWT, JWTSecret: testSecret, RoleClaimPath: "roles[x]"}, "index must be"}, + "trailing garbage": {Config{Mode: ModeJWT, JWTSecret: testSecret, RoleClaimPath: "roles[0]x"}, "unexpected"}, + "empty quoted segment": {Config{Mode: ModeJWT, JWTSecret: testSecret, RoleClaimPath: `a.""`}, "empty name"}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + a, err := New(tc.cfg) + if err == nil || !strings.Contains(err.Error(), tc.want) || a != nil { + t.Fatalf("New = (%v, %v), want error containing %q", a, err, tc.want) + } + }) + } +} + +func TestParseMode(t *testing.T) { + for _, s := range []string{"jwt", "headers", "none"} { + if m, err := ParseMode(s); err != nil || string(m) != s { + t.Errorf("ParseMode(%q) = %q, %v", s, m, err) + } + } + if _, err := ParseMode("JWT"); err == nil { + t.Error("ParseMode is case-sensitive") + } +} + +func TestAnonymousRefusedWithoutAnonymousRole(t *testing.T) { + jwtAuth := mustNew(Config{Mode: ModeJWT, JWTSecret: testSecret}) + hdrAuth := mustNew(Config{Mode: ModeHeaders, HeaderPrefix: "X-Claim-", TrustedProxies: []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}}) + for name, a := range map[string]*Authenticator{"jwt": jwtAuth, "headers": hdrAuth} { + r := httptest.NewRequest("GET", "/", nil) + r.RemoteAddr = "10.0.0.1:1" + claims, role, err := a.Authenticate(r) + if !errors.Is(err, ErrAuthRequired) || errors.Is(err, ErrInvalidToken) || claims != nil || role != "" { + t.Fatalf("%s: Authenticate = (%v, %q, %v), want ErrAuthRequired", name, claims, role, err) + } + if got := Challenge(err); got != "Bearer" { + t.Fatalf("%s: Challenge = %q", name, got) + } + } +} + +func TestModeNoneWithoutAnonymousRoleRunsAsConnectionRole(t *testing.T) { + a := mustNew(Config{Mode: ModeNone}) + claims, role, err := a.Authenticate(httptest.NewRequest("GET", "/", nil)) + if err != nil || role != "" || len(claims) != 0 { + t.Fatalf("Authenticate = (%v, %q, %v)", claims, role, err) + } +} + +func TestChallenge(t *testing.T) { + a := testAuth() + r := bearerRequest("garbage") + _, _, err := a.Authenticate(r) + if got := Challenge(err); got != `Bearer error="invalid_token"` { + t.Fatalf("invalid token challenge = %q (err %v)", got, err) + } + notAllowed := &authError{kind: ErrRoleNotAllowed, msg: "x"} + if got := Challenge(notAllowed); got != `Bearer error="insufficient_scope"` { + t.Fatalf("role challenge = %q", got) + } + if got := Challenge(errors.New("other")); got != "" { + t.Fatalf("other challenge = %q", got) + } +} + +func TestBearerSchemeCaseInsensitive(t *testing.T) { + a := testAuth() + tok := signToken(t, jwt.MapClaims{"role": "app_user", "exp": time.Now().Add(time.Hour).Unix()}) + for _, h := range []string{"Bearer " + tok, "bearer " + tok, "BEARER " + tok, "bEaReR " + tok} { + r := httptest.NewRequest("GET", "/", nil) + r.Header.Set("Authorization", h) + if _, role, err := a.Authenticate(r); err != nil || role != "app_user" { + t.Errorf("%q: (%q, %v)", h[:8], role, err) + } + } + for _, h := range []string{"Bearer", "Bearer ", "Bearer a b", "Bearertoken", "Basic " + tok, "Bearer\t" + tok} { + r := httptest.NewRequest("GET", "/", nil) + r.Header.Set("Authorization", h) + if _, _, err := a.Authenticate(r); !errors.Is(err, ErrInvalidToken) { + t.Errorf("%q accepted: %v", h, err) + } + } +} + +func TestLeeway(t *testing.T) { + tok := signToken(t, jwt.MapClaims{"role": "app_user", "exp": time.Now().Add(-10 * time.Second).Unix()}) + strict := testAuth() + if _, _, err := strict.Authenticate(bearerRequest(tok)); !errors.Is(err, ErrInvalidToken) { + t.Fatalf("expired token without leeway: %v", err) + } + lenient := mustNew(Config{Mode: ModeJWT, JWTSecret: testSecret, AnonymousRole: "anonymous", Leeway: 30 * time.Second}) + if _, role, err := lenient.Authenticate(bearerRequest(tok)); err != nil || role != "app_user" { + t.Fatalf("expired token within leeway: (%q, %v)", role, err) + } +} + +func TestRoleClaimPath(t *testing.T) { + exp := time.Now().Add(time.Hour).Unix() + claims := jwt.MapClaims{ + "exp": exp, + "role": "top_role", + "app_metadata": map[string]any{"role": "meta_role"}, + "realm_access": map[string]any{"roles": []any{"first_role", "second_role"}}, + "https://example.com/role": "url_role", + "https://example.com/roles": map[string]any{"db": "url_nested"}, + "num": 7, + } + cases := []struct{ path, want string }{ + {"", "top_role"}, + {"role", "top_role"}, + {".role", "top_role"}, + {"app_metadata.role", "meta_role"}, + {".app_metadata.role", "meta_role"}, + {"realm_access.roles[1]", "second_role"}, + {`"https://example.com/role"`, "url_role"}, + {`."https://example.com/roles".db`, "url_nested"}, + {"missing.role", "default_role"}, + {"realm_access.roles[5]", "default_role"}, + {"role.nested", "default_role"}, + } + for _, tc := range cases { + a := mustNew(Config{Mode: ModeJWT, JWTSecret: testSecret, RoleClaimPath: tc.path, DefaultRole: "default_role"}) + _, role, err := a.Authenticate(bearerRequest(signToken(t, claims))) + if err != nil || role != tc.want { + t.Errorf("path %q: (%q, %v), want %q", tc.path, role, err, tc.want) + } + } + for _, path := range []string{"num", "app_metadata", "realm_access.roles"} { + a := mustNew(Config{Mode: ModeJWT, JWTSecret: testSecret, RoleClaimPath: path, DefaultRole: "default_role"}) + if _, _, err := a.Authenticate(bearerRequest(signToken(t, claims))); !errors.Is(err, ErrInvalidToken) { + t.Errorf("path %q to a non-string: err = %v, want ErrInvalidToken", path, err) + } + } +} + +func TestEmptyRoleClaimRejected(t *testing.T) { + a := testAuth() + tok := signToken(t, jwt.MapClaims{"role": "", "exp": time.Now().Add(time.Hour).Unix()}) + if _, _, err := a.Authenticate(bearerRequest(tok)); !errors.Is(err, ErrInvalidToken) { + t.Fatalf("empty role claim: %v", err) + } + h := mustNew(Config{Mode: ModeHeaders, HeaderPrefix: "X-Claim-", AnonymousRole: "anonymous", TrustedProxies: []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}}) + r := claimRequest(map[string][]string{"X-Claim-Role": {""}}) + if _, _, err := h.Authenticate(r); !errors.Is(err, ErrInvalidToken) { + t.Fatalf("empty role header: %v", err) + } +} + +func TestNoRoleResolvedRefused(t *testing.T) { + a := mustNew(Config{Mode: ModeJWT, JWTSecret: testSecret}) + tok := signToken(t, jwt.MapClaims{"sub": "u1", "exp": time.Now().Add(time.Hour).Unix()}) + if _, _, err := a.Authenticate(bearerRequest(tok)); !errors.Is(err, ErrRoleNotAllowed) { + t.Fatalf("token without role and no default: err = %v, want ErrRoleNotAllowed", err) + } + a = mustNew(Config{Mode: ModeJWT, JWTSecret: testSecret, SkipRoleSwitch: true}) + claims, role, err := a.Authenticate(bearerRequest(tok)) + if err != nil || role != "" || claims["sub"] != "u1" { + t.Fatalf("SkipRoleSwitch: (%v, %q, %v)", claims, role, err) + } +} + +func TestSkipRoleSwitch(t *testing.T) { + a := mustNew(Config{Mode: ModeJWT, JWTSecret: testSecret, AnonymousRole: "anonymous", AllowedRoles: []string{"app_user"}, SkipRoleSwitch: true}) + exp := time.Now().Add(time.Hour).Unix() + claims, role, err := a.Authenticate(bearerRequest(signToken(t, jwt.MapClaims{"role": "app_user", "sub": "u1", "exp": exp}))) + if err != nil || role != "" || claims["sub"] != "u1" { + t.Fatalf("verified token: (%v, %q, %v)", claims, role, err) + } + if _, _, err := a.Authenticate(bearerRequest(signToken(t, jwt.MapClaims{"role": "app_admin", "exp": exp}))); !errors.Is(err, ErrRoleNotAllowed) { + t.Fatalf("disallowed role: %v", err) + } + if _, _, err := a.Authenticate(bearerRequest("garbage")); !errors.Is(err, ErrInvalidToken) { + t.Fatalf("invalid token: %v", err) + } + if _, role, err := a.Authenticate(httptest.NewRequest("GET", "/", nil)); err != nil || role != "" { + t.Fatalf("anonymous: (%q, %v)", role, err) + } + refusing := mustNew(Config{Mode: ModeJWT, JWTSecret: testSecret, SkipRoleSwitch: true}) + if _, _, err := refusing.Authenticate(httptest.NewRequest("GET", "/", nil)); !errors.Is(err, ErrAuthRequired) { + t.Fatalf("anonymous without anonymous role: %v", err) + } +} + +func TestValidateClaimPath(t *testing.T) { + for _, p := range []string{"role", ".role", "a.b.c", "a[0]", "a[0][1].b", `"x.y"`, `"a b".c`, "a-b:c/d"} { + if err := ValidateClaimPath(p); err != nil { + t.Errorf("ValidateClaimPath(%q) = %v", p, err) + } + } + for _, p := range []string{"", ".", "a.", "a..b", "[0]", "a[", "a[-1]", "a[+1]", "a b", `a"b"`, "a]"} { + if err := ValidateClaimPath(p); err == nil { + t.Errorf("ValidateClaimPath(%q) = nil, want an error", p) + } + } +} + +func FuzzClaimPath(f *testing.F) { + for _, s := range []string{"role", ".a.b[0]", `"x.y".z[12]`, "a[", `"`, "[0]"} { + f.Add(s) + } + claims := map[string]any{"a": map[string]any{"b": []any{"r"}}, "role": "x"} + f.Fuzz(func(t *testing.T, s string) { + p, err := parseClaimPath(s) + if err != nil { + return + } + if len(p) == 0 { + t.Fatalf("%q parsed to an empty path", s) + } + p.lookup(claims) + }) +} diff --git a/confx/confx_test.go b/confx/confx_test.go index 9cb1adf..e74f806 100644 --- a/confx/confx_test.go +++ b/confx/confx_test.go @@ -1,6 +1,7 @@ package confx import ( + stdflag "flag" "os" "path/filepath" "slices" @@ -42,48 +43,69 @@ type pdbqTX struct { MaxRetries int `koanf:"max_retries" doc:"Automatic retries of a transactional operation after a serialization failure or deadlock (SQLSTATE 40001/40P01). 0 disables; the whole operation re-runs, which is safe because the failed attempt rolled back."` } +// pdbqPlugins is a plugin settings struct shaped like a product's: one +// section per configurable plugin. +type pdbqPlugins struct { + AdvancedFilters struct { + Relations bool `koanf:"relations" doc:"Filter on related rows."` + MaxDepth int `koanf:"max_depth" doc:"Deepest relation filter."` + } `koanf:"advanced_filters" doc:"advanced_filters plugin."` +} + type pdbqConfig struct { - Database Database `koanf:"database"` - Server pdbqServer `koanf:"server"` - Schema Schema `koanf:"schema"` - Filters Filters `koanf:"filters"` - RLS RLS `koanf:"rls"` - TX pdbqTX `koanf:"transactions"` - Watch Watch `koanf:"watch"` - Errors Errors `koanf:"errors"` - Plugins Plugins `koanf:"plugins"` - Log Log `koanf:"log"` - Metrics Metrics `koanf:"metrics"` + Database Database `koanf:"database"` + Server pdbqServer `koanf:"server"` + Schema Schema `koanf:"schema"` + Filters Filters `koanf:"filters"` + Auth Auth `koanf:"auth"` + Roles Roles `koanf:"roles"` + Claims Claims `koanf:"claims"` + TX pdbqTX `koanf:"transactions"` + Watch Watch `koanf:"watch"` + Errors Errors `koanf:"errors"` + Plugins Plugins[pdbqPlugins] `koanf:"plugins"` + Log Log `koanf:"log"` + Metrics Metrics `koanf:"metrics"` } func pdbqDefaults() pdbqConfig { return pdbqConfig{ - Database: Database{MaxConns: 10, ConnectTimeout: 10 * time.Second, StatementTimeout: 30 * time.Second}, + Database: Database{MaxConns: 10, ConnectTimeout: 10 * time.Second, StatementTimeout: 25 * time.Second}, Server: pdbqServer{ Addr: ":8080", RequestTimeout: 30 * time.Second, MaxBodyBytes: 1 << 20, MaxDepth: 15, MaxCost: 10000, MaxPageSize: 100, }, Schema: Schema{Schemas: []string{"public"}, Functions: true}, Filters: Filters{IndexedOnly: true}, - RLS: RLS{ - Enabled: true, AnonymousRole: "anonymous", RoleClaim: "role", ClaimsPrefix: "pdbq.claims", - Auth: Auth{Mode: "jwt", HeaderPrefix: "X-Pdbq-Claim-", JWKSCacheTTL: time.Hour}, - }, + Auth: DefaultAuth("X-Pdbq-Claim-"), + Roles: DefaultRoles(), + Claims: DefaultClaims(), TX: pdbqTX{Mutations: true, Isolation: "read_committed"}, Watch: Watch{PollInterval: 5 * time.Second, Channel: "pdbq_ddl"}, Errors: Errors{Detail: "prod"}, - Plugins: Plugins{Settings: map[string]map[string]any{}}, + Plugins: Plugins[pdbqPlugins]{}, Log: Log{Level: "info", Format: "text"}, Metrics: DefaultMetrics(), } } +// secretFile holds "file-secret" and a trailing newline. +const secretFile = "testdata/jwt-secret" + +var update = stdflag.Bool("update", false, "rewrite testdata/pdbq.example.yaml") + func TestExampleYAMLMatchesPdbqGolden(t *testing.T) { - want, err := os.ReadFile(filepath.Join("testdata", "pdbq.example.yaml")) + golden := filepath.Join("testdata", "pdbq.example.yaml") + got := ExampleYAML(pdbqDefaults()) + if *update { + if err := os.WriteFile(golden, []byte(got), 0o644); err != nil { + t.Fatal(err) + } + } + want, err := os.ReadFile(golden) if err != nil { t.Fatal(err) } - got := ExampleYAML(pdbqDefaults()) if got != string(want) { t.Fatalf("ExampleYAML drifted from pdbq's example body:\n--- got ---\n%s\n--- want ---\n%s", got, want) } @@ -151,8 +173,8 @@ database: url: "postgres://file/db" server: addr: ":9999" -rls: - enabled: false +roles: + switch: false ` if err := os.WriteFile(path, []byte(yaml), 0o644); err != nil { t.Fatal(err) @@ -185,7 +207,7 @@ rls: if cfg.Server.MaxDepth != 15 { t.Errorf("default lost: %d", cfg.Server.MaxDepth) } - if cfg.RLS.Enabled { + if cfg.Roles.Switch { t.Error("file bool not applied") } } @@ -245,10 +267,10 @@ func TestParseTrustedProxy(t *testing.T) { func TestValidateDefaultsClean(t *testing.T) { cfg := pdbqDefaults() - cfg.RLS.Auth.JWTSecret = "s" + cfg.Auth.JWT.Secret = "s" var errs []string errs = append(errs, ValidateErrors(cfg.Errors)...) - errs = append(errs, ValidateRLS(cfg.RLS)...) + errs = append(errs, ValidateIdentity(cfg.Auth, cfg.Roles, cfg.Claims)...) errs = append(errs, ValidateTX(TX{Isolation: cfg.TX.Isolation, MaxRetries: cfg.TX.MaxRetries})...) errs = append(errs, ValidateWatch(cfg.Watch, cfg.Schema.CachePath)...) errs = append(errs, ValidateSchema(cfg.Schema)...) @@ -273,50 +295,74 @@ func TestValidateRejects(t *testing.T) { }{ "errors.detail": {func() []string { return ValidateErrors(Errors{Detail: "verbose"}) }, `errors.detail: "verbose" is not 'dev', 'prod' or 'strict'`}, - "auth.mode": {func() []string { return ValidateRLS(RLS{Auth: Auth{Mode: "oauth"}}) }, - `rls.auth.mode: "oauth" is not 'jwt', 'headers' or 'none'`}, + "auth.mode": {func() []string { return ValidateIdentity(Auth{Mode: "oauth"}, Roles{}, Claims{}) }, + `auth.mode: "oauth" is not 'jwt', 'headers' or 'none'`}, "jwt secret": {func() []string { - return ValidateRLS(RLS{Enabled: true, AnonymousRole: "a", Auth: Auth{Mode: "jwt"}}) - }, "rls.auth.jwt_secret or rls.auth.jwks_url is required when rls.enabled and auth mode is jwt"}, - "jwt_type needs secret": {func() []string { - return ValidateRLS(RLS{Auth: Auth{Mode: "none", JWTType: "public.jwt"}}) - }, "rls.auth.jwt_type requires rls.auth.jwt_secret: minting signs with the HMAC secret (JWKS keys are verify-only)"}, - "jwt_type qualified": {func() []string { - return ValidateRLS(RLS{Auth: Auth{Mode: "none", JWTType: "jwt", JWTSecret: "s"}}) - }, `rls.auth.jwt_type: "jwt" must be schema-qualified, e.g. public.jwt`}, - "anon role": {func() []string { - return ValidateRLS(RLS{Enabled: true, Auth: Auth{Mode: "none"}}) - }, "rls.anonymous_role is required when rls.enabled: an empty role would run unauthenticated requests as the privileged connection role, bypassing RLS"}, + return ValidateIdentity(Auth{Mode: "jwt", JWT: JWT{RoleClaimPath: "role"}}, Roles{}, Claims{}) + }, "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)"}, + "secret and file": {func() []string { + return ValidateIdentity(Auth{Mode: "none", JWT: JWT{Secret: "s", SecretFile: secretFile}}, Roles{}, Claims{}) + }, "auth.jwt.secret and auth.jwt.secret_file are mutually exclusive"}, + "secret file missing": {func() []string { + 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{}) + }, `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{}) + }, "auth.jwt.leeway must be >= 0"}, + "role claim path": {func() []string { + return ValidateIdentity(Auth{Mode: "jwt", JWT: JWT{Secret: "s", RoleClaimPath: "a..b"}}, Roles{}, Claims{}) + }, `auth.jwt.role_claim_path: invalid role claim path "a..b": empty name`}, + "mint_type needs secret": {func() []string { + return ValidateIdentity(Auth{Mode: "none", MintType: "public.jwt"}, Roles{}, Claims{}) + }, "auth.mint_type requires auth.jwt.secret or auth.jwt.secret_file: minting signs with the HMAC secret (JWKS keys are verify-only)"}, + "mint_type qualified": {func() []string { + return ValidateIdentity(Auth{Mode: "none", MintType: "jwt", JWT: JWT{Secret: "s"}}, Roles{}, Claims{}) + }, `auth.mint_type: "jwt" must be schema-qualified, e.g. public.jwt`}, + "none needs anonymous": {func() []string { + return ValidateIdentity(Auth{Mode: "none"}, Roles{Switch: true}, Claims{}) + }, "roles.anonymous is required in auth mode none while roles.switch is on: every request runs as the anonymous role (set roles.switch: false to run as the connection role)"}, "trusted proxy": {func() []string { - return ValidateRLS(RLS{Auth: Auth{Mode: "none", TrustedProxies: []string{"10.0.0.0/8", "not-an-ip"}}}) - }, `rls.auth.trusted_proxies: "not-an-ip" is not a valid IP or CIDR block`}, + return ValidateIdentity(Auth{Mode: "none", Headers: Headers{TrustedProxies: []string{"10.0.0.0/8", "not-an-ip"}}}, Roles{}, Claims{}) + }, `auth.headers.trusted_proxies: "not-an-ip" is not a valid IP or CIDR block`}, "anonymous role none": {func() []string { - return ValidateRLS(RLS{Enabled: true, AnonymousRole: "none", Auth: Auth{Mode: "none"}}) - }, `rls.anonymous_role: "none" is not a role requests may assume: use letters, digits and underscores, not none, public or a pg_ role`}, + return ValidateIdentity(Auth{Mode: "none"}, Roles{Anonymous: "none"}, Claims{}) + }, `roles.anonymous: "none" is not a role requests may assume: use letters, digits and underscores, not none, public or a pg_ role`}, "default role pg_": {func() []string { - return ValidateRLS(RLS{AnonymousRole: "anon", DefaultRole: "pg_read_all_data", Auth: Auth{Mode: "none"}}) - }, `rls.default_role: "pg_read_all_data" is not a role requests may assume: use letters, digits and underscores, not none, public or a pg_ role`}, + return ValidateIdentity(Auth{Mode: "none"}, Roles{Default: "pg_read_all_data"}, Claims{}) + }, `roles.default: "pg_read_all_data" is not a role requests may assume: use letters, digits and underscores, not none, public or a pg_ role`}, "allowed role none": {func() []string { - return ValidateRLS(RLS{AnonymousRole: "anon", AllowedRoles: []string{"app_user", "NONE"}, Auth: Auth{Mode: "none"}}) - }, `rls.allowed_roles: "NONE" is not a role requests may assume: use letters, digits and underscores, not none, public or a pg_ role`}, + return ValidateIdentity(Auth{Mode: "none"}, Roles{Allowed: []string{"app_user", "NONE"}}, Claims{}) + }, `roles.allowed: "NONE" is not a role requests may assume: use letters, digits and underscores, not none, public or a pg_ role`}, "claims prefix": {func() []string { - return ValidateRLS(RLS{AnonymousRole: "anon", ClaimsPrefix: "plpgsql", Auth: Auth{Mode: "none"}}) - }, `rls.claims_prefix: invalid claims prefix "plpgsql": "plpgsql" is a server or extension settings namespace`}, + return ValidateIdentity(Auth{Mode: "none"}, Roles{}, Claims{Prefix: "plpgsql"}) + }, `claims.prefix: invalid claims prefix "plpgsql": "plpgsql" is a server or extension settings namespace`}, + "claims json setting": {func() []string { + return ValidateIdentity(Auth{Mode: "none"}, Roles{}, Claims{JSONSetting: "claims"}) + }, `claims.json_setting: invalid claims setting "claims": use a dotted name such as "request.jwt.claims"`}, + "claims json under prefix": {func() []string { + return ValidateIdentity(Auth{Mode: "none"}, Roles{}, Claims{Prefix: "jwt.claims", JSONSetting: "JWT.claims.all"}) + }, `claims.json_setting: "JWT.claims.all" lies under claims.prefix "jwt.claims", where a claim of that name would overwrite it`}, "header prefix empty": {func() []string { - return ValidateRLS(RLS{AnonymousRole: "anon", RoleClaim: "role", Auth: Auth{Mode: "headers"}}) - }, `rls.auth.header_prefix: "" must be letters, digits and hyphens ending in a hyphen, e.g. X-Pdbq-Claim-`}, + return ValidateIdentity(Auth{Mode: "headers", Headers: Headers{RoleClaim: "role", TrustedProxies: []string{"10.0.0.1"}}}, Roles{}, Claims{}) + }, `auth.headers.prefix: "" must be letters, digits and hyphens ending in a hyphen, e.g. X-Claim-`}, "header prefix no trailing hyphen": {func() []string { - return ValidateRLS(RLS{AnonymousRole: "anon", RoleClaim: "role", Auth: Auth{Mode: "headers", HeaderPrefix: "X-Pdbq-Claim"}}) - }, `rls.auth.header_prefix: "X-Pdbq-Claim" must be letters, digits and hyphens ending in a hyphen, e.g. X-Pdbq-Claim-`}, + return ValidateIdentity(Auth{Mode: "headers", Headers: Headers{Prefix: "X-Pdbq-Claim", RoleClaim: "role", TrustedProxies: []string{"10.0.0.1"}}}, Roles{}, Claims{}) + }, `auth.headers.prefix: "X-Pdbq-Claim" must be letters, digits and hyphens ending in a hyphen, e.g. X-Claim-`}, "header prefix underscore": {func() []string { - return ValidateRLS(RLS{AnonymousRole: "anon", RoleClaim: "role", Auth: Auth{Mode: "headers", HeaderPrefix: "X_Claim-"}}) - }, `rls.auth.header_prefix: "X_Claim-" must be letters, digits and hyphens ending in a hyphen, e.g. X-Pdbq-Claim-`}, + return ValidateIdentity(Auth{Mode: "headers", Headers: Headers{Prefix: "X_Claim-", RoleClaim: "role", TrustedProxies: []string{"10.0.0.1"}}}, Roles{}, Claims{}) + }, `auth.headers.prefix: "X_Claim-" must be letters, digits and hyphens ending in a hyphen, e.g. X-Claim-`}, "header role claim": {func() []string { - return ValidateRLS(RLS{AnonymousRole: "anon", RoleClaim: "AppRole", Auth: Auth{Mode: "headers", HeaderPrefix: "X-Pdbq-Claim-"}}) - }, `rls.role_claim: "AppRole" cannot be sent as a claim header: use lower-case letters and digits joined by single underscores`}, + return ValidateIdentity(Auth{Mode: "headers", Headers: Headers{Prefix: "X-Pdbq-Claim-", RoleClaim: "AppRole", TrustedProxies: []string{"10.0.0.1"}}}, Roles{}, Claims{}) + }, `auth.headers.role_claim: "AppRole" cannot be sent as a claim header: use lower-case letters and digits joined by single underscores`}, "header claims": {func() []string { - return ValidateRLS(RLS{AnonymousRole: "anon", RoleClaim: "role", Auth: Auth{Mode: "headers", HeaderPrefix: "X-Pdbq-Claim-", HeaderClaims: []string{"user_id", "user-id"}}}) - }, `rls.auth.header_claims: "user-id" cannot be sent as a claim header: use lower-case letters and digits joined by single underscores`}, + return ValidateIdentity(Auth{Mode: "headers", Headers: Headers{Prefix: "X-Pdbq-Claim-", RoleClaim: "role", Claims: []string{"user_id", "user-id"}, TrustedProxies: []string{"10.0.0.1"}}}, Roles{}, Claims{}) + }, `auth.headers.claims: "user-id" cannot be sent as a claim header: use lower-case letters and digits joined by single underscores`}, + "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: "` + strings.Repeat("c", 64) + `" is longer than 63 bytes`}, "isolation": {func() []string { return ValidateTX(TX{Isolation: "chaos"}) }, @@ -329,8 +375,14 @@ func TestValidateRejects(t *testing.T) { `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"}, - "log level": {func() []string { return ValidateLog(Log{Level: "loud"}) }, - `log.level: "loud" invalid`}, + "log level": {func() []string { return ValidateLog(Log{Level: "loud", Format: "text"}) }, + `log.level: "loud" is not 'debug', 'info', 'warn' or 'error'`}, + "log format": {func() []string { return ValidateLog(Log{Level: "info", Format: "jsn"}) }, + `log.format: "jsn" is not 'text' or 'json'`}, + "plugin names": {func() []string { + return ValidatePluginNames([]string{"postgis", "advanced-filters"}, []string{"postgis", "advanced_filters"}) + }, + `plugins.disabled: unknown plugin "advanced-filters", did you mean "advanced_filters"?`}, "metrics path relative": {func() []string { return ValidateMetrics(Metrics{Path: "metrics"}, "") }, `metrics.path: "metrics" must start with / and name a path other than /`}, "metrics path root": {func() []string { return ValidateMetrics(Metrics{Path: "/"}, "") }, @@ -359,29 +411,67 @@ func TestValidateRejects(t *testing.T) { } func TestAuthConfig(t *testing.T) { - rls := RLS{ - Enabled: true, RoleClaim: "role", DefaultRole: "d", AnonymousRole: "anon", AllowedRoles: []string{"x"}, - Auth: Auth{Mode: "headers", HeaderPrefix: "X-Pdbr-Claim-", HeaderClaims: []string{"user_id"}, TrustedProxies: []string{"10.0.0.0/8", "garbage", "192.168.1.1"}}, + a := Auth{ + Mode: "headers", + JWT: JWT{SecretFile: secretFile, JWKSURL: "https://idp/jwks", Issuer: "i", Audience: "a", Leeway: time.Second, RoleClaimPath: "app.role"}, + Headers: Headers{Prefix: "X-Pdbr-Claim-", Claims: []string{"user_id"}, RoleClaim: "app_role", + TrustedProxies: []string{"10.0.0.0/8", "garbage", "192.168.1.1"}}, + } + r := Roles{Switch: false, Default: "d", Anonymous: "anon", Allowed: []string{"x"}} + cfg, err := AuthConfig(a, r) + if err != nil { + t.Fatal(err) } - cfg := AuthConfig(rls) - if !cfg.Enabled || cfg.Mode != "headers" || cfg.HeaderPrefix != "X-Pdbr-Claim-" || cfg.RoleClaim != "role" || - cfg.DefaultRole != "d" || cfg.AnonymousRole != "anon" || len(cfg.AllowedRoles) != 1 || + if cfg.Mode != "headers" || cfg.HeaderPrefix != "X-Pdbr-Claim-" || cfg.HeaderRoleClaim != "app_role" || cfg.RoleClaimPath != "app.role" || + cfg.JWTSecret != "file-secret" || cfg.JWKSURL != "https://idp/jwks" || cfg.JWTIssuer != "i" || cfg.JWTAudience != "a" || cfg.Leeway != time.Second || + cfg.DefaultRole != "d" || cfg.AnonymousRole != "anon" || len(cfg.AllowedRoles) != 1 || !cfg.SkipRoleSwitch || len(cfg.HeaderClaims) != 1 || cfg.HeaderClaims[0] != "user_id" { t.Fatalf("AuthConfig = %+v", cfg) } if len(cfg.TrustedProxies) != 2 || cfg.TrustedProxies[1].Bits() != 32 { t.Fatalf("TrustedProxies = %v (invalid entries dropped, singles /32)", cfg.TrustedProxies) } - if AuthConfig(RLS{}).TrustedProxies != nil { - t.Fatal("no proxies configured must stay nil (trust every peer)") + if _, err := AuthConfig(Auth{JWT: JWT{SecretFile: "/nonexistent"}}, r); err == nil { + t.Fatal("unreadable secret file accepted") + } + if cfg, _ := AuthConfig(Auth{}, Roles{Switch: true}); cfg.SkipRoleSwitch { + t.Fatal("roles.switch on must switch roles") + } +} + +func TestResolveSecret(t *testing.T) { + if s, err := (JWT{Secret: "inline"}).ResolveSecret(); err != nil || s != "inline" { + t.Fatalf("inline = %q, %v", s, err) + } + if s, err := (JWT{SecretFile: secretFile}).ResolveSecret(); err != nil || s != "file-secret" { + t.Fatalf("file = %q, %v", s, err) + } + empty := filepath.Join(t.TempDir(), "empty") + if err := os.WriteFile(empty, []byte("\n"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := (JWT{SecretFile: empty}).ResolveSecret(); err == nil || !strings.HasSuffix(err.Error(), "is empty") { + t.Fatalf("empty file err = %v", err) + } +} + +func TestIdentityWarnings(t *testing.T) { + if w := IdentityWarnings(DefaultAuth("X-C-"), Roles{Switch: true, Allowed: []string{"a"}}); len(w) != 0 { + t.Fatalf("warnings = %q", w) + } + if w := IdentityWarnings(DefaultAuth("X-C-"), Roles{Switch: false}); len(w) != 1 || !strings.HasPrefix(w[0], "roles.switch is off") { + t.Fatalf("warnings = %q", w) + } + if w := IdentityWarnings(DefaultAuth("X-C-"), Roles{Switch: true}); len(w) != 1 || !strings.HasPrefix(w[0], "roles.allowed is empty") { + t.Fatalf("warnings = %q", w) } - if p := AuthConfig(RLS{Auth: Auth{TrustedProxies: []string{"junk"}}}).TrustedProxies; p == nil || len(p) != 0 { - t.Fatalf("all-invalid list must be empty non-nil (trust nobody), got %v", p) + if w := IdentityWarnings(Auth{Mode: "none"}, Roles{Switch: true, Anonymous: "a"}); len(w) != 0 { + t.Fatalf("warnings = %q", w) } } func TestPluginsDisabledSet(t *testing.T) { - set := Plugins{Disabled: []string{"a", "b"}}.DisabledSet() + set := Plugins[struct{}]{Disabled: []string{"a", "b"}}.DisabledSet() if !set["a"] || !set["b"] || set["c"] { t.Fatalf("set = %v", set) } diff --git a/confx/load.go b/confx/load.go index d4f1aac..838e914 100644 --- a/confx/load.go +++ b/confx/load.go @@ -5,8 +5,10 @@ import ( "net/netip" "os" "reflect" + "sort" "strings" + "github.com/go-viper/mapstructure/v2" "github.com/knadh/koanf/parsers/yaml" "github.com/knadh/koanf/providers/env" "github.com/knadh/koanf/providers/file" @@ -15,28 +17,112 @@ import ( flag "github.com/spf13/pflag" ) +// LoadOption customises Load. +type LoadOption func(*loadOpts) + +type loadOpts struct { + moved map[string]string +} + +// WithMoved adds product keys to MovedKeys: old key (or old section, which +// maps every key below it) to the key that replaced it. +func WithMoved(moved map[string]string) LoadOption { + return func(o *loadOpts) { + for k, v := range moved { + o.moved[k] = v + } + } +} + // Load layers configuration into dst (which already holds the defaults): // optional YAML file, then envPrefix-prefixed environment variables, then // flags. Pass only the flags the user actually set (see ChangedFlags) so // unset flags cannot shadow YAML/env values; flag names are koanf paths. -// Validation is the caller's job. -func Load(envPrefix, path string, flags *flag.FlagSet, dst any) error { +// +// Loading is strict: a file key that dst has no field for is an error +// naming the key it moved to (MovedKeys, WithMoved) 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 key), or +// nearly does; 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. +func Load(envPrefix, path string, flags *flag.FlagSet, dst any, opts ...LoadOption) error { + o := loadOpts{moved: map[string]string{}} + for k, v := range MovedKeys { + o.moved[k] = v + } + for _, opt := range opts { + opt(&o) + } + schema := schemaOf(dst) + var errs []string k := koanf.New(".") if path != "" { - if err := k.Load(file.Provider(path), yaml.Parser()); err != nil { + fk := koanf.New(".") + if err := fk.Load(file.Provider(path), yaml.Parser()); err != nil { return fmt.Errorf("config: read %s: %w", path, err) } + for _, key := range fk.Keys() { + if schema.known(key) { + continue + } + msg := "unknown key " + key + if hint := schema.unknownKey(key, o.moved, func(p string) string { return p }); hint != "" { + msg += ": " + hint + } + errs = append(errs, msg) + } + if err := k.Merge(fk); err != nil { + return fmt.Errorf("config: %w", err) + } } - if err := k.Load(env.ProviderWithValue(envPrefix, ".", envValueMapper(envPrefix, slicePaths(dst))), nil); err != nil { + envVars := map[string]string{} + mapper := envValueMapper(envPrefix, slicePaths(dst)) + ek := koanf.New(".") + if err := ek.Load(env.ProviderWithValue(envPrefix, ".", func(key, value string) (string, any) { + path, v := mapper(key, value) + envVars[path] = key + return path, v + }), nil); err != nil { return fmt.Errorf("config: env: %w", err) } + for _, key := range ek.Keys() { + if schema.known(key) { + continue + } + top, _, _ := strings.Cut(key, ".") + if !schema.section(top, o.moved) { + ek.Delete(key) + continue + } + msg := fmt.Sprintf("unknown environment variable %s (%s)", envVars[key], key) + if hint := schema.unknownKey(key, o.moved, func(p string) string { return envName(envPrefix, p) }); hint != "" { + msg += ": " + hint + } + errs = append(errs, msg) + } + if len(errs) > 0 { + sort.Strings(errs) + return InvalidConfig(errs) + } + if err := k.Merge(ek); err != nil { + return fmt.Errorf("config: %w", err) + } if flags != nil { if err := k.Load(posflag.Provider(flags, ".", k), nil); err != nil { return fmt.Errorf("config: flags: %w", err) } } - if err := k.Unmarshal("", dst); err != nil { - return fmt.Errorf("config: unmarshal: %w", err) + err := k.UnmarshalWithConf("", dst, koanf.UnmarshalConf{DecoderConfig: &mapstructure.DecoderConfig{ + DecodeHook: mapstructure.ComposeDecodeHookFunc( + mapstructure.StringToTimeDurationHookFunc(), + mapstructure.TextUnmarshallerHookFunc()), + WeaklyTypedInput: true, + ErrorUnused: true, + }}) + if err != nil { + return fmt.Errorf("config: %w", err) } return nil } diff --git a/confx/sections.go b/confx/sections.go index b33411c..b0b1b19 100644 --- a/confx/sections.go +++ b/confx/sections.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "github.com/suprbdev/pdbcore/auth" "github.com/suprbdev/pdbcore/contract" ) @@ -19,7 +20,7 @@ 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."` - StatementTimeout time.Duration `koanf:"statement_timeout" doc:"Per-statement timeout applied to every request (0 disables)."` + 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."` } // Schema selects what is introspected and how. @@ -35,29 +36,74 @@ type Filters struct { AllowColumns map[string][]string `koanf:"allow_columns" doc:"Per-table extra filterable columns, keyed by schema.table, overriding indexed_only."` } -// RLS is the row-level-security / identity section. -type RLS struct { - Enabled bool `koanf:"enabled" doc:"Run each request as a switched role with claims exposed via set_config (SET LOCAL). Disabling uses the privileged connection directly and logs a loud warning."` - DefaultRole string `koanf:"default_role" doc:"Role assumed for authenticated requests without a role claim."` - AnonymousRole string `koanf:"anonymous_role" doc:"Role assumed for unauthenticated requests."` - RoleClaim string `koanf:"role_claim" doc:"JWT claim (or claim header in headers mode: app_role is App-Role) carrying the database role."` - AllowedRoles []string `koanf:"allowed_roles" doc:"Roles a request may assume via the role claim. Empty allows any role (subject to database grants); default_role and anonymous_role are always allowed."` - ClaimsPrefix string `koanf:"claims_prefix" doc:"set_config namespace for request claims, e.g. pdbq.claims."` - Auth Auth `koanf:"auth"` +// Auth is the credential section: how a request proves who it is. +type Auth struct { + Mode auth.Mode `koanf:"mode" doc:"Credential source: 'jwt' (verify a bearer JWT), 'headers' (claims set by a trusted gateway) or 'none' (no credentials: every request is anonymous)."` + JWT JWT `koanf:"jwt" doc:"JWT verification (jwt mode) and the key minting signs with."` + Headers Headers `koanf:"headers" doc:"Gateway claim headers (headers mode)."` + MintType string `koanf:"mint_type" doc:"Schema-qualified composite type (e.g. public.jwt) minted into a signed JWT: any function returning it yields an HS256 token string built from the composite's fields (an exp field becomes the token expiry). Requires jwt.secret or jwt.secret_file; jwt.issuer/jwt.audience are embedded when set. Empty disables minting."` +} + +// JWT is the auth.jwt section. +type JWT struct { + Secret string `koanf:"secret" doc:"HMAC secret verifying HS256/384/512 tokens (ignored for verification when jwks_url is set) and signing minted tokens."` + SecretFile string `koanf:"secret_file" doc:"File holding the HMAC secret (trailing newlines are stripped), instead of secret."` + JWKSURL string `koanf:"jwks_url" doc:"JWKS endpoint for asymmetric JWT verification (RS256/384/512, ES256/384/512). Takes precedence over secret."` + JWKSCacheTTL time.Duration `koanf:"jwks_cache_ttl" doc:"How long fetched JWKS keys are cached; an unknown kid triggers an early refresh (key rotation) at most once a minute. After the TTL, keys refresh in the background and stay in use for up to one more TTL while the endpoint fails; failed fetches back off from 1s to 1m."` + Issuer string `koanf:"issuer" doc:"Expected iss claim; empty skips the check."` + Audience string `koanf:"audience" doc:"Expected aud claim; empty skips the check."` + Leeway time.Duration `koanf:"leeway" doc:"Clock skew tolerated when checking exp, nbf and iat."` + RoleClaimPath string `koanf:"role_claim_path" doc:"Path of the claim carrying the database role: dot-separated keys with optional array indexes and double-quoted keys, e.g. role, app_metadata.role, realm_access.roles[0] or \"https://example.com/role\". A missing claim falls back to roles.default; a claim that is not a non-empty string is rejected."` +} + +// Headers is the auth.headers section. +type Headers struct { + Prefix string `koanf:"prefix" doc:"Header prefix mapped to claims, e.g. X-Pdbq-Claim-. The rest of the name maps to one claim (User-Id is user_id); requests with a claim header containing an underscore or other punctuation, repeated, or folding onto another claim header are rejected. The gateway must strip every client-supplied header with this prefix, in any letter case."` + Claims []string `koanf:"claims" doc:"Claim names (e.g. user_id) accepted from claim headers; role_claim is always accepted. Requests carrying any other claim header are rejected. Empty accepts any claim."` + RoleClaim string `koanf:"role_claim" doc:"Claim carrying the database role (role is sent as Role). A missing claim falls back to roles.default."` + TrustedProxies []string `koanf:"trusted_proxies" doc:"CIDR blocks (or single IPs) allowed to send claim headers; required in headers mode. Requests from other peers that carry claim headers are rejected."` +} + +// Roles is the database role section: which role a request runs as. +type Roles struct { + Switch bool `koanf:"switch" doc:"Run each request as its resolved role (SET LOCAL ROLE). Disabling runs every request as the connection role, with credentials still verified and claims still set; it logs a loud warning."` + Anonymous string `koanf:"anonymous" doc:"Role of requests without credentials (every request in auth mode none). Empty refuses requests without credentials with 401 (auth modes jwt and headers)."` + Default string `koanf:"default" doc:"Role of authenticated requests without a role claim; empty falls back to anonymous, and a request that resolves to no role is refused."` + Allowed []string `koanf:"allowed" doc:"Roles a request may assume via its role claim. Empty allows any role (subject to database grants); default and anonymous are always allowed."` +} + +// Claims is the section exposing request claims to SQL. +type Claims struct { + Prefix string `koanf:"prefix" doc:"Namespace of the per-claim settings: claim user_id is current_setting('jwt.claims.user_id', true) with the default (PostGraphile's). Empty sets no per-claim settings."` + JSONSetting string `koanf:"json_setting" doc:"Setting that receives every claim as one JSON object ('{}' without credentials), e.g. request.jwt.claims (PostgREST's: current_setting('request.jwt.claims', true)::json->>'sub'). Empty sets none."` +} + +// DefaultClaimsPrefix is the default claims.prefix, PostGraphile's +// namespace, so policies reading current_setting('jwt.claims.') port +// unchanged. +const DefaultClaimsPrefix = "jwt.claims" + +// DefaultAuth is the auth section's default: jwt mode, a one-hour JWKS +// cache, the role in the top-level role claim, and claim headers named +// headerPrefix + claim. +func DefaultAuth(headerPrefix string) Auth { + return Auth{ + Mode: auth.ModeJWT, + JWT: JWT{JWKSCacheTTL: time.Hour, RoleClaimPath: "role"}, + Headers: Headers{Prefix: headerPrefix, RoleClaim: "role"}, + } } -// Auth is the claim source (nested under rls.auth). -type Auth struct { - Mode string `koanf:"mode" doc:"Claim source: 'jwt', 'headers' (behind a trusted gateway), or 'none'."` - JWTSecret string `koanf:"jwt_secret" doc:"HMAC secret for HS256/384/512 verification (jwt mode; ignored when jwks_url is set)."` - JWKSURL string `koanf:"jwks_url" doc:"JWKS endpoint for asymmetric JWT verification (RS256/384/512, ES256/384/512). Takes precedence over jwt_secret."` - JWKSCacheTTL time.Duration `koanf:"jwks_cache_ttl" doc:"How long fetched JWKS keys are cached; an unknown kid triggers an early refresh (key rotation) at most once a minute. After the TTL, keys refresh in the background and stay in use for up to one more TTL while the endpoint fails; failed fetches back off from 1s to 1m."` - JWTIssuer string `koanf:"jwt_issuer" doc:"Expected iss claim; empty skips the check."` - JWTAudience string `koanf:"jwt_audience" doc:"Expected aud claim; empty skips the check."` - HeaderPrefix string `koanf:"header_prefix" doc:"Header prefix mapped to claims in headers mode, e.g. X-Pdbq-Claim-. The rest of the name maps to one claim (User-Id is user_id); requests with a claim header containing an underscore or other punctuation, repeated, or folding onto another claim header are rejected. The gateway must strip every client-supplied header with this prefix, in any letter case."` - HeaderClaims []string `koanf:"header_claims" doc:"Claim names (e.g. user_id) accepted from claim headers in headers mode; role_claim is always accepted. Requests carrying any other claim header are rejected. Empty accepts any claim."` - TrustedProxies []string `koanf:"trusted_proxies" doc:"CIDR blocks (or single IPs) allowed to supply claim headers in headers mode. Requests from other peers that carry claim headers are rejected. Empty trusts every peer and logs a startup warning."` - JWTType string `koanf:"jwt_type" doc:"Schema-qualified composite type (e.g. public.jwt) minted into a signed JWT: any function returning it yields an HS256 token string built from the composite's fields (an exp field becomes the token expiry). Requires jwt_secret; jwt_issuer/jwt_audience are embedded when set. Empty disables minting."` +// DefaultRoles is the roles section's default: role switching on and no +// anonymous access. +func DefaultRoles() Roles { + return Roles{Switch: true} +} + +// DefaultClaims is the claims section's default: per-claim settings under +// DefaultClaimsPrefix and no JSON setting. +func DefaultClaims() Claims { + return Claims{Prefix: DefaultClaimsPrefix} } // TX is the transaction policy shared by both products. pdbq adds @@ -80,14 +126,16 @@ type Errors struct { Detail string `koanf:"detail" doc:"'dev' exposes full PostgreSQL error detail in GraphQL errors; 'prod' sanitizes but passes constraint-violation and bad-input messages through; 'strict' hides every database error message (constraint and column names never leak)."` } -// Plugins disables and configures plugins by name. -type Plugins struct { - Disabled []string `koanf:"disabled" doc:"Plugin names to disable."` - Settings map[string]map[string]any `koanf:"settings" doc:"Per-plugin configuration, keyed by plugin name."` +// Plugins disables and configures plugins by name. S is the product's +// settings struct: one koanf-tagged field per configurable plugin, keyed by +// plugin name, each holding that plugin's typed settings. +type Plugins[S any] struct { + Disabled []string `koanf:"disabled" doc:"Plugin names to disable."` + Settings S `koanf:"settings" doc:"Per-plugin settings, one section per plugin."` } // DisabledSet returns the disabled-plugin set for registry filtering. -func (p Plugins) DisabledSet() map[string]bool { +func (p Plugins[S]) DisabledSet() map[string]bool { out := map[string]bool{} for _, n := range p.Disabled { out[n] = true diff --git a/confx/strict.go b/confx/strict.go new file mode 100644 index 0000000..9ac9fd5 --- /dev/null +++ b/confx/strict.go @@ -0,0 +1,218 @@ +package confx + +import ( + "encoding" + "fmt" + "reflect" + "sort" + "strings" + "time" +) + +// MovedKeys maps configuration keys removed before 1.0 to the key that +// replaced them. Load names the replacement when a file or environment +// variable still uses an old key; products add their own with WithMoved. +var MovedKeys = map[string]string{ + "rls.enabled": "roles.switch", + "rls.anonymous_role": "roles.anonymous", + "rls.default_role": "roles.default", + "rls.allowed_roles": "roles.allowed", + "rls.role_claim": "auth.jwt.role_claim_path", + "rls.claims_prefix": "claims.prefix", + "rls.auth.mode": "auth.mode", + "rls.auth.jwt_secret": "auth.jwt.secret", + "rls.auth.jwks_url": "auth.jwt.jwks_url", + "rls.auth.jwks_cache_ttl": "auth.jwt.jwks_cache_ttl", + "rls.auth.jwt_issuer": "auth.jwt.issuer", + "rls.auth.jwt_audience": "auth.jwt.audience", + "rls.auth.header_prefix": "auth.headers.prefix", + "rls.auth.header_claims": "auth.headers.claims", + "rls.auth.trusted_proxies": "auth.headers.trusted_proxies", + "rls.auth.jwt_type": "auth.mint_type", +} + +type keyKind int + +const ( + // leafKey holds a value. + leafKey keyKind = iota + // sectionKey is a struct whose children are checked. + sectionKey + // openKey is a map or interface accepting any child key. + openKey +) + +// keySchema is the set of koanf paths a config struct accepts. +type keySchema map[string]keyKind + +var ( + durationType = reflect.TypeOf(time.Duration(0)) + textType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() +) + +func schemaOf(dst any) keySchema { + s := keySchema{} + t := reflect.TypeOf(dst) + for t != nil && t.Kind() == reflect.Pointer { + t = t.Elem() + } + if t != nil && t.Kind() == reflect.Struct { + s.collect(t, "") + } + return s +} + +func (s keySchema) collect(t reflect.Type, prefix string) { + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + key := f.Tag.Get("koanf") + if f.Anonymous && f.Type.Kind() == reflect.Struct && (key == "" || strings.HasPrefix(key, ",")) { + s.collect(f.Type, prefix) + continue + } + if key == "" || key == "-" || !f.IsExported() { + continue + } + path := key + if prefix != "" { + path = prefix + "." + key + } + ft := f.Type + switch { + case ft == durationType || reflect.PointerTo(ft).Implements(textType): + s[path] = leafKey + case ft.Kind() == reflect.Struct: + s[path] = sectionKey + s.collect(ft, path) + case ft.Kind() == reflect.Map || ft.Kind() == reflect.Interface: + s[path] = openKey + default: + s[path] = leafKey + } + } +} + +// known reports whether key is accepted: a path of the schema, or a key +// below a map or interface path. +func (s keySchema) known(key string) bool { + if _, ok := s[key]; ok { + return true + } + for i := len(key) - 1; i > 0; i-- { + if key[i] != '.' { + continue + } + switch kind, ok := s[key[:i]]; { + case ok && kind == openKey: + return true + case ok: + return false + } + } + return false +} + +// section reports whether name is a top-level key of the schema or of a +// moved key, or a near miss of one. +func (s keySchema) section(name string, moved map[string]string) bool { + tops := []string{} + for p := range s { + if !strings.Contains(p, ".") { + if p == name { + return true + } + tops = append(tops, p) + } + } + for old := range moved { + if top, _, _ := strings.Cut(old, "."); top == name { + return true + } + } + return len(name) >= 4 && closest(name, tops) != "" +} + +// unknownKey describes an unknown key: where it moved to, or the closest +// known or moved key; name renders a path for the message. +func (s keySchema) unknownKey(key string, moved map[string]string, name func(string) string) string { + if to, ok := movedTo(key, moved); ok { + return fmt.Sprintf("moved to %s", name(to)) + } + cands := make([]string, 0, len(s)+len(moved)) + for p := range s { + cands = append(cands, p) + } + for old := range moved { + cands = append(cands, old) + } + best := closest(key, cands) + if best == "" { + return "" + } + if to, ok := movedTo(best, moved); ok { + return fmt.Sprintf("did you mean %s (formerly %s)?", name(to), best) + } + return fmt.Sprintf("did you mean %s?", name(best)) +} + +// movedTo maps key through moved: an exact entry, or the longest entry +// that is a dotted prefix of key, with the rest of key appended. +func movedTo(key string, moved map[string]string) (string, bool) { + if to, ok := moved[key]; ok { + return to, true + } + best := "" + for old := range moved { + if strings.HasPrefix(key, old+".") && len(old) > len(best) { + best = old + } + } + if best == "" { + return "", false + } + return moved[best] + key[len(best):], true +} + +// closest returns the candidate nearest to s by edit distance, or "" when +// none is within max(2, len(s)/5) edits. Ties go to the lexically smallest. +func closest(s string, cands []string) string { + sorted := append([]string(nil), cands...) + sort.Strings(sorted) + limit := max(2, len(s)/5) + best, bestD := "", limit+1 + for _, c := range sorted { + if d := editDistance(s, c); d < bestD { + best, bestD = c, d + } + } + return best +} + +// editDistance is the Levenshtein distance between a and b, in bytes. +func editDistance(a, b string) int { + prev := make([]int, len(b)+1) + cur := make([]int, len(b)+1) + for j := range prev { + prev[j] = j + } + for i := 1; i <= len(a); i++ { + cur[0] = i + for j := 1; j <= len(b); j++ { + cost := 1 + if a[i-1] == b[j-1] { + cost = 0 + } + cur[j] = min(prev[j]+1, cur[j-1]+1, prev[j-1]+cost) + } + prev, cur = cur, prev + } + return prev[len(b)] +} + +// envName renders a koanf path as the environment variable that sets it: +// the inverse of EnvKeyMapper. +func envName(prefix, path string) string { + s := strings.ReplaceAll(path, "_", "__") + s = strings.ReplaceAll(s, ".", "_") + return prefix + strings.ToUpper(s) +} diff --git a/confx/strict_test.go b/confx/strict_test.go new file mode 100644 index 0000000..d1a28d8 --- /dev/null +++ b/confx/strict_test.go @@ -0,0 +1,169 @@ +package confx + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func writeYAML(t *testing.T, body string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "c.yaml") + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + return path +} + +func TestLoadRejectsUnknownFileKeys(t *testing.T) { + path := writeYAML(t, ` +rls: + enabled: false + enabeld: true + auth: + jwt_secret: s +roles: + anonymus: web_anon +server: + addr: ":1" + adr: ":2" +plugins: + settings: + advanced-filters: + relations: false + advanced_filters: + relation: false +totally_unrelated: 1 +`) + cfg := pdbqDefaults() + err := Load("PDBX_", path, nil, &cfg, WithMoved(map[string]string{"plugins.settings.advanced-filters": "plugins.settings.advanced_filters"})) + if err == nil { + t.Fatal("unknown keys accepted") + } + for _, want := range []string{ + "unknown key rls.enabled: moved to roles.switch", + "unknown key rls.enabeld: did you mean roles.switch (formerly rls.enabled)?", + "unknown key rls.auth.jwt_secret: moved to auth.jwt.secret", + "unknown key roles.anonymus: did you mean roles.anonymous?", + "unknown key server.adr: did you mean server.addr?", + "unknown key plugins.settings.advanced-filters.relations: moved to plugins.settings.advanced_filters.relations", + "unknown key plugins.settings.advanced_filters.relation: did you mean plugins.settings.advanced_filters.relations?", + "unknown key totally_unrelated\n", + } { + if !strings.Contains(err.Error()+"\n", want) { + t.Errorf("error lacks %q:\n%v", want, err) + } + } + if !strings.HasPrefix(err.Error(), "invalid config:\n - ") { + t.Errorf("error shape: %v", err) + } + if cfg.Server.Addr != ":8080" { + t.Errorf("a rejected load must not apply values, addr = %q", cfg.Server.Addr) + } +} + +func TestLoadRejectsUnknownEnvKeysInKnownSections(t *testing.T) { + t.Setenv("PDBX_RLS_ENABLED", "false") + t.Setenv("PDBX_ROLES_ANONYMUS", "web_anon") + t.Setenv("PDBX_DATABSE_URL", "postgres://x") + t.Setenv("PDBX_TEST_DATABASE_URL", "postgres://test") + t.Setenv("PDBX_PRINT_SDL_DIGEST", "1") + cfg := pdbqDefaults() + err := Load("PDBX_", "", nil, &cfg) + if err == nil { + t.Fatal("unknown env keys accepted") + } + for _, want := range []string{ + "unknown environment variable PDBX_RLS_ENABLED (rls.enabled): moved to PDBX_ROLES_SWITCH", + "unknown environment variable PDBX_ROLES_ANONYMUS (roles.anonymus): did you mean PDBX_ROLES_ANONYMOUS?", + "unknown environment variable PDBX_DATABSE_URL (databse.url): did you mean PDBX_DATABASE_URL?", + } { + if !strings.Contains(err.Error(), want) { + t.Errorf("error lacks %q:\n%v", want, err) + } + } + for _, unwanted := range []string{"TEST", "PRINT"} { + if strings.Contains(err.Error(), unwanted) { + t.Errorf("variable outside the config sections reported:\n%v", err) + } + } +} + +func TestLoadIgnoresUnrelatedPrefixedEnv(t *testing.T) { + t.Setenv("PDBX_TEST_DATABASE_URL", "postgres://test") + t.Setenv("PDBX_TEST_PDBQ_DIR", "/x") + cfg := pdbqDefaults() + if err := Load("PDBX_", "", nil, &cfg); err != nil { + t.Fatal(err) + } +} + +func TestLoadDecodesEnvIntoTypedSettings(t *testing.T) { + t.Setenv("PDBX_PLUGINS_SETTINGS_ADVANCED__FILTERS_RELATIONS", "true") + t.Setenv("PDBX_PLUGINS_SETTINGS_ADVANCED__FILTERS_MAX__DEPTH", "4") + t.Setenv("PDBX_ROLES_SWITCH", "false") + t.Setenv("PDBX_AUTH_JWT_LEEWAY", "30s") + t.Setenv("PDBX_ROLES_ALLOWED", "app_user, app_admin") + cfg := pdbqDefaults() + if err := Load("PDBX_", "", nil, &cfg); err != nil { + t.Fatal(err) + } + s := cfg.Plugins.Settings.AdvancedFilters + if !s.Relations || s.MaxDepth != 4 || cfg.Roles.Switch || cfg.Auth.JWT.Leeway != 30*time.Second || + len(cfg.Roles.Allowed) != 2 || cfg.Roles.Allowed[1] != "app_admin" { + t.Fatalf("env decode: settings %+v roles %+v leeway %v", s, cfg.Roles, cfg.Auth.JWT.Leeway) + } + t.Setenv("PDBX_PLUGINS_SETTINGS_ADVANCED__FILTERS_MAX__DEPTH", "deep") + cfg = pdbqDefaults() + if err := Load("PDBX_", "", nil, &cfg); err == nil || !strings.Contains(err.Error(), "max_depth") { + t.Fatalf("bad int accepted: %v", err) + } +} + +func TestLoadRejectsUnknownKeysInListEntries(t *testing.T) { + path := writeYAML(t, "contracts:\n - name: public\n default_policy: exclude\n") + var c struct { + Contracts []Contract `koanf:"contracts"` + } + err := Load("PDBX_", path, nil, &c) + if err == nil || !strings.Contains(err.Error(), "default_policy") { + t.Fatalf("err = %v", err) + } +} + +func TestLoadAcceptsMapKeys(t *testing.T) { + path := writeYAML(t, "filters:\n allow_columns:\n public.users: [email]\n") + cfg := pdbqDefaults() + if err := Load("PDBX_", path, nil, &cfg); err != nil { + t.Fatal(err) + } + if len(cfg.Filters.AllowColumns) == 0 { + t.Fatalf("allow_columns = %v", cfg.Filters.AllowColumns) + } +} + +func TestEnvName(t *testing.T) { + for path, want := range map[string]string{ + "roles.switch": "PDBQ_ROLES_SWITCH", + "server.max_depth": "PDBQ_SERVER_MAX__DEPTH", + "plugins.settings.advanced_filters.relations": "PDBQ_PLUGINS_SETTINGS_ADVANCED__FILTERS_RELATIONS", + } { + got := envName("PDBQ_", path) + if got != want || EnvKeyMapper("PDBQ_")(got) != path { + t.Errorf("envName(%q) = %q, want %q (and back)", path, got, want) + } + } +} + +func TestEditDistance(t *testing.T) { + for _, tc := range []struct { + a, b string + d int + }{{"", "", 0}, {"a", "", 1}, {"kitten", "sitting", 3}, {"enabeld", "enabled", 2}, {"test", "auth", 4}} { + if got := editDistance(tc.a, tc.b); got != tc.d { + t.Errorf("editDistance(%q, %q) = %d, want %d", tc.a, tc.b, got, tc.d) + } + } +} diff --git a/confx/testdata/jwt-secret b/confx/testdata/jwt-secret new file mode 100644 index 0000000..c096931 --- /dev/null +++ b/confx/testdata/jwt-secret @@ -0,0 +1 @@ +file-secret diff --git a/confx/testdata/pdbq.example.yaml b/confx/testdata/pdbq.example.yaml index 18db1bb..3f8ff73 100644 --- a/confx/testdata/pdbq.example.yaml +++ b/confx/testdata/pdbq.example.yaml @@ -5,8 +5,8 @@ database: max_conns: 10 # Timeout for establishing a connection. connect_timeout: "10s" - # Per-statement timeout applied to every request (0 disables). - statement_timeout: "30s" + # 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" server: # Listen address for the HTTP server. @@ -54,40 +54,55 @@ filters: # Per-table extra filterable columns, keyed by schema.table, overriding indexed_only. allow_columns: {} -rls: - # Run each request as a switched role with claims exposed via set_config (SET LOCAL). Disabling uses the privileged connection directly and logs a loud warning. - enabled: true - # Role assumed for authenticated requests without a role claim. - default_role: "" - # Role assumed for unauthenticated requests. - anonymous_role: "anonymous" - # JWT claim (or claim header in headers mode: app_role is App-Role) carrying the database role. - role_claim: "role" - # Roles a request may assume via the role claim. Empty allows any role (subject to database grants); default_role and anonymous_role are always allowed. - allowed_roles: [] - # set_config namespace for request claims, e.g. pdbq.claims. - claims_prefix: "pdbq.claims" - auth: - # Claim source: 'jwt', 'headers' (behind a trusted gateway), or 'none'. - mode: "jwt" - # HMAC secret for HS256/384/512 verification (jwt mode; ignored when jwks_url is set). - jwt_secret: "" - # JWKS endpoint for asymmetric JWT verification (RS256/384/512, ES256/384/512). Takes precedence over jwt_secret. +auth: + # Credential source: 'jwt' (verify a bearer JWT), 'headers' (claims set by a trusted gateway) or 'none' (no credentials: every request is anonymous). + mode: "jwt" + # JWT verification (jwt mode) and the key minting signs with. + jwt: + # HMAC secret verifying HS256/384/512 tokens (ignored for verification when jwks_url is set) and signing minted tokens. + secret: "" + # File holding the HMAC secret (trailing newlines are stripped), instead of secret. + secret_file: "" + # JWKS endpoint for asymmetric JWT verification (RS256/384/512, ES256/384/512). Takes precedence over secret. jwks_url: "" # How long fetched JWKS keys are cached; an unknown kid triggers an early refresh (key rotation) at most once a minute. After the TTL, keys refresh in the background and stay in use for up to one more TTL while the endpoint fails; failed fetches back off from 1s to 1m. jwks_cache_ttl: "1h0m0s" # Expected iss claim; empty skips the check. - jwt_issuer: "" + issuer: "" # Expected aud claim; empty skips the check. - jwt_audience: "" - # Header prefix mapped to claims in headers mode, e.g. X-Pdbq-Claim-. The rest of the name maps to one claim (User-Id is user_id); requests with a claim header containing an underscore or other punctuation, repeated, or folding onto another claim header are rejected. The gateway must strip every client-supplied header with this prefix, in any letter case. - header_prefix: "X-Pdbq-Claim-" - # Claim names (e.g. user_id) accepted from claim headers in headers mode; role_claim is always accepted. Requests carrying any other claim header are rejected. Empty accepts any claim. - header_claims: [] - # CIDR blocks (or single IPs) allowed to supply claim headers in headers mode. Requests from other peers that carry claim headers are rejected. Empty trusts every peer and logs a startup warning. + audience: "" + # Clock skew tolerated when checking exp, nbf and iat. + leeway: "0s" + # Path of the claim carrying the database role: dot-separated keys with optional array indexes and double-quoted keys, e.g. role, app_metadata.role, realm_access.roles[0] or "https://example.com/role". A missing claim falls back to roles.default; a claim that is not a non-empty string is rejected. + role_claim_path: "role" + # Gateway claim headers (headers mode). + headers: + # Header prefix mapped to claims, e.g. X-Pdbq-Claim-. The rest of the name maps to one claim (User-Id is user_id); requests with a claim header containing an underscore or other punctuation, repeated, or folding onto another claim header are rejected. The gateway must strip every client-supplied header with this prefix, in any letter case. + prefix: "X-Pdbq-Claim-" + # Claim names (e.g. user_id) accepted from claim headers; role_claim is always accepted. Requests carrying any other claim header are rejected. Empty accepts any claim. + claims: [] + # Claim carrying the database role (role is sent as Role). A missing claim falls back to roles.default. + role_claim: "role" + # CIDR blocks (or single IPs) allowed to send claim headers; required in headers mode. Requests from other peers that carry claim headers are rejected. trusted_proxies: [] - # Schema-qualified composite type (e.g. public.jwt) minted into a signed JWT: any function returning it yields an HS256 token string built from the composite's fields (an exp field becomes the token expiry). Requires jwt_secret; jwt_issuer/jwt_audience are embedded when set. Empty disables minting. - jwt_type: "" + # Schema-qualified composite type (e.g. public.jwt) minted into a signed JWT: any function returning it yields an HS256 token string built from the composite's fields (an exp field becomes the token expiry). Requires jwt.secret or jwt.secret_file; jwt.issuer/jwt.audience are embedded when set. Empty disables minting. + mint_type: "" + +roles: + # Run each request as its resolved role (SET LOCAL ROLE). Disabling runs every request as the connection role, with credentials still verified and claims still set; it logs a loud warning. + switch: true + # Role of requests without credentials (every request in auth mode none). Empty refuses requests without credentials with 401 (auth modes jwt and headers). + anonymous: "" + # Role of authenticated requests without a role claim; empty falls back to anonymous, and a request that resolves to no role is refused. + default: "" + # Roles a request may assume via its role claim. Empty allows any role (subject to database grants); default and anonymous are always allowed. + allowed: [] + +claims: + # Namespace of the per-claim settings: claim user_id is current_setting('jwt.claims.user_id', true) with the default (PostGraphile's). Empty sets no per-claim settings. + prefix: "jwt.claims" + # Setting that receives every claim as one JSON object ('{}' without credentials), e.g. request.jwt.claims (PostgREST's: current_setting('request.jwt.claims', true)::json->>'sub'). Empty sets none. + json_setting: "" transactions: # Wrap every mutation in a transaction. @@ -114,8 +129,14 @@ errors: plugins: # Plugin names to disable. disabled: [] - # Per-plugin configuration, keyed by plugin name. - settings: {} + # Per-plugin settings, one section per plugin. + settings: + # advanced_filters plugin. + advanced_filters: + # Filter on related rows. + relations: false + # Deepest relation filter. + max_depth: 0 log: # Log level: debug, info, warn, error. diff --git a/confx/validate.go b/confx/validate.go index 974b7dc..ac5d120 100644 --- a/confx/validate.go +++ b/confx/validate.go @@ -3,7 +3,8 @@ package confx import ( "fmt" "net" - "net/netip" + "net/url" + "os" "strings" "github.com/suprbdev/pdbcore/auth" @@ -29,52 +30,99 @@ func ValidateErrors(e Errors) []string { return []string{fmt.Sprintf("errors.detail: %q is not 'dev', 'prod' or 'strict'", e.Detail)} } -// ValidateRLS checks the rls section: auth mode, trusted proxies, JWT -// secret/JWKS presence, jwt_type shape, the headers-mode prefix and claim -// names (auth.ValidHeaderClaim), the anonymous role, the configured role -// names (pgexec.ValidRole) and claims_prefix (pgexec.ValidateClaimsPrefix). -func ValidateRLS(c RLS) []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 +// 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 +// (pgexec.ValidateClaimsPrefix) and JSON setting +// (pgexec.ValidateClaimsSetting), which must not lie under the prefix. +func ValidateIdentity(a Auth, r Roles, c Claims) []string { var errs []string - switch c.Auth.Mode { - case "jwt", "headers", "none": - default: - errs = append(errs, fmt.Sprintf("rls.auth.mode: %q is not 'jwt', 'headers' or 'none'", c.Auth.Mode)) + add := func(format string, args ...any) { errs = append(errs, fmt.Sprintf(format, args...)) } + if _, err := auth.ParseMode(string(a.Mode)); err != nil { + add("auth.mode: %q is not 'jwt', 'headers' or 'none'", a.Mode) } - for _, p := range c.Auth.TrustedProxies { - if _, err := ParseTrustedProxy(p); err != nil { - errs = append(errs, fmt.Sprintf("rls.auth.trusted_proxies: %q is not a valid IP or CIDR block", p)) + j := a.JWT + if j.Secret != "" && j.SecretFile != "" { + add("auth.jwt.secret and auth.jwt.secret_file are mutually exclusive") + } + if j.SecretFile != "" { + if _, err := j.ResolveSecret(); err != nil { + add("auth.jwt.secret_file: %v", err) + } + } + if j.JWKSURL != "" { + if u, err := url.Parse(j.JWKSURL); err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" { + add("auth.jwt.jwks_url: %q is not an http(s) URL", j.JWKSURL) + } + } + if j.Leeway < 0 { + add("auth.jwt.leeway 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)") + } + if err := auth.ValidateClaimPath(j.RoleClaimPath); err != nil { + add("auth.jwt.role_claim_path: %v", err) } } - if c.Auth.Mode == "headers" { - errs = append(errs, validateHeadersMode(c)...) + for _, p := range a.Headers.TrustedProxies { + if _, err := ParseTrustedProxy(p); err != nil { + add("auth.headers.trusted_proxies: %q is not a valid IP or CIDR block", p) + } } - if c.Enabled && c.Auth.Mode == "jwt" && c.Auth.JWTSecret == "" && c.Auth.JWKSURL == "" { - errs = append(errs, "rls.auth.jwt_secret or rls.auth.jwks_url is required when rls.enabled and auth mode is jwt") + if a.Mode == auth.ModeHeaders { + errs = append(errs, validateHeadersMode(a.Headers)...) } - if c.Auth.JWTType != "" && c.Auth.JWTSecret == "" { - errs = append(errs, "rls.auth.jwt_type requires rls.auth.jwt_secret: minting signs with the HMAC secret (JWKS keys are verify-only)") + if a.MintType != "" && j.Secret == "" && j.SecretFile == "" { + add("auth.mint_type requires auth.jwt.secret or auth.jwt.secret_file: minting signs with the HMAC secret (JWKS keys are verify-only)") } - if jt := c.Auth.JWTType; jt != "" && (strings.Count(jt, ".") != 1 || strings.HasPrefix(jt, ".") || strings.HasSuffix(jt, ".")) { - errs = append(errs, fmt.Sprintf("rls.auth.jwt_type: %q must be schema-qualified, e.g. public.jwt", jt)) + if mt := a.MintType; mt != "" && (strings.Count(mt, ".") != 1 || strings.HasPrefix(mt, ".") || strings.HasSuffix(mt, ".")) { + add("auth.mint_type: %q must be schema-qualified, e.g. public.jwt", mt) } - if c.Enabled && c.AnonymousRole == "" { - errs = append(errs, "rls.anonymous_role is required when rls.enabled: an empty role would run unauthenticated requests as the privileged connection role, bypassing RLS") + if a.Mode == auth.ModeNone && r.Switch && r.Anonymous == "" { + add("roles.anonymous is required in auth mode none while roles.switch is on: every request runs as the anonymous role (set roles.switch: false to run as the connection role)") } - roles := []struct{ key, role string }{{"rls.anonymous_role", c.AnonymousRole}, {"rls.default_role", c.DefaultRole}} - for _, r := range c.AllowedRoles { - roles = append(roles, struct{ key, role string }{"rls.allowed_roles", r}) + roles := []struct{ key, role string }{{"roles.anonymous", r.Anonymous}, {"roles.default", r.Default}} + for _, ar := range r.Allowed { + roles = append(roles, struct{ key, role string }{"roles.allowed", ar}) } - for _, r := range roles { - if r.role != "" && !pgexec.ValidRole(r.role) { - errs = append(errs, fmt.Sprintf("%s: %q is not a role requests may assume: use letters, digits and underscores, not none, public or a pg_ role", r.key, r.role)) + for _, kr := range roles { + if kr.role != "" && !pgexec.ValidRole(kr.role) { + add("%s: %q is not a role requests may assume: use letters, digits and underscores, not none, public or a pg_ role", kr.key, kr.role) } } - if err := pgexec.ValidateClaimsPrefix(c.ClaimsPrefix); err != nil { - errs = append(errs, "rls.claims_prefix: "+err.Error()) + if err := pgexec.ValidateClaimsPrefix(c.Prefix); err != nil { + add("claims.prefix: %v", err) + } + if c.JSONSetting != "" { + if err := pgexec.ValidateClaimsSetting(c.JSONSetting); err != nil { + add("claims.json_setting: %v", err) + } else if c.Prefix != "" && strings.HasPrefix(strings.ToLower(c.JSONSetting), strings.ToLower(c.Prefix)+".") { + add("claims.json_setting: %q lies under claims.prefix %q, where a claim of that name would overwrite it", c.JSONSetting, c.Prefix) + } } return errs } +// IdentityWarnings returns the startup warnings for a valid identity +// configuration that is legal but risky: role switching off, and any role +// claim accepted in jwt or headers mode. +func IdentityWarnings(a Auth, r Roles) []string { + var out []string + if !r.Switch { + out = append(out, "roles.switch is off: every request runs as the connection role, so row-level security policies for request roles do not apply") + } + if r.Switch && a.Mode != auth.ModeNone && len(r.Allowed) == 0 { + out = append(out, "roles.allowed is empty: a valid credential may assume any role the connection role can switch to; list the roles requests may use") + } + return out +} + // ValidateTX checks transactions.isolation and transactions.max_retries. func ValidateTX(t TX) []string { var errs []string @@ -218,28 +266,59 @@ func ValidateSchema(s Schema) []string { return nil } -// ValidateLog checks log.level. +// ValidateLog checks log.level and log.format. func ValidateLog(l Log) []string { + var errs []string switch l.Level { case "debug", "info", "warn", "error": - return nil + default: + errs = append(errs, fmt.Sprintf("log.level: %q is not 'debug', 'info', 'warn' or 'error'", l.Level)) } - return []string{fmt.Sprintf("log.level: %q invalid", l.Level)} + switch l.Format { + case "text", "json": + default: + errs = append(errs, fmt.Sprintf("log.format: %q is not 'text' or 'json'", l.Format)) + } + return errs } -func validateHeadersMode(c RLS) []string { +// ValidatePluginNames checks that every plugins.disabled entry names a +// plugin in known, suggesting the closest name for a typo. +func ValidatePluginNames(disabled, known []string) []string { var errs []string - if p := c.Auth.HeaderPrefix; !validHeaderPrefix(p) { - errs = append(errs, fmt.Sprintf("rls.auth.header_prefix: %q must be letters, digits and hyphens ending in a hyphen, e.g. X-Pdbq-Claim-", p)) + set := make(map[string]bool, len(known)) + for _, k := range known { + set[k] = true } - if c.RoleClaim != "" && !auth.ValidHeaderClaim(c.RoleClaim) { - errs = append(errs, fmt.Sprintf("rls.role_claim: %q cannot be sent as a claim header: use lower-case letters and digits joined by single underscores", c.RoleClaim)) + for _, d := range disabled { + if set[d] { + continue + } + msg := fmt.Sprintf("plugins.disabled: unknown plugin %q", d) + if s := closest(d, known); s != "" { + msg += fmt.Sprintf(", did you mean %q?", s) + } + errs = append(errs, msg) } - for _, claim := range c.Auth.HeaderClaims { + return errs +} + +func validateHeadersMode(h Headers) []string { + var errs []string + if !validHeaderPrefix(h.Prefix) { + errs = append(errs, fmt.Sprintf("auth.headers.prefix: %q must be letters, digits and hyphens ending in a hyphen, e.g. X-Claim-", h.Prefix)) + } + if !auth.ValidHeaderClaim(h.RoleClaim) { + errs = append(errs, fmt.Sprintf("auth.headers.role_claim: %q cannot be sent as a claim header: use lower-case letters and digits joined by single underscores", h.RoleClaim)) + } + for _, claim := range h.Claims { if !auth.ValidHeaderClaim(claim) { - errs = append(errs, fmt.Sprintf("rls.auth.header_claims: %q cannot be sent as a claim header: use lower-case letters and digits joined by single underscores", claim)) + errs = append(errs, fmt.Sprintf("auth.headers.claims: %q cannot be sent as a claim header: use lower-case letters and digits joined by single underscores", claim)) } } + if len(h.TrustedProxies) == 0 { + errs = append(errs, "auth.headers.trusted_proxies is required in auth mode headers: list the gateway addresses allowed to send claim headers") + } return errs } @@ -269,33 +348,54 @@ func ValidChannelName(s string) bool { return s != "" } -// AuthConfig converts the rls section into an auth.Config. Invalid -// trusted_proxies entries are dropped (ValidateRLS rejects them; skipping -// here only shrinks the trusted set, never widens it); nil when none were -// configured, which auth treats as "trust every peer". -func AuthConfig(c RLS) auth.Config { +// ResolveSecret returns the HMAC secret: Secret, or the contents of +// SecretFile with trailing newlines stripped. A secret file that cannot be +// read or is empty is an error. +func (j JWT) ResolveSecret() (string, error) { + if j.SecretFile == "" { + return j.Secret, nil + } + b, err := os.ReadFile(j.SecretFile) + if err != nil { + return "", err + } + s := strings.TrimRight(string(b), "\r\n") + if s == "" { + return "", fmt.Errorf("%s is empty", j.SecretFile) + } + return s, nil +} + +// AuthConfig converts the auth and roles sections into an auth.Config, +// reading the secret file. Invalid trusted_proxies entries are dropped +// (ValidateIdentity rejects them; skipping here only shrinks the trusted +// set, never widens it). +func AuthConfig(a Auth, r Roles) (auth.Config, error) { + secret, err := a.JWT.ResolveSecret() + if err != nil { + return auth.Config{}, fmt.Errorf("auth.jwt.secret_file: %w", err) + } cfg := auth.Config{ - Enabled: c.Enabled, - Mode: c.Auth.Mode, - JWTSecret: c.Auth.JWTSecret, - JWKSURL: c.Auth.JWKSURL, - JWKSCacheTTL: c.Auth.JWKSCacheTTL, - JWTIssuer: c.Auth.JWTIssuer, - JWTAudience: c.Auth.JWTAudience, - HeaderPrefix: c.Auth.HeaderPrefix, - HeaderClaims: c.Auth.HeaderClaims, - RoleClaim: c.RoleClaim, - DefaultRole: c.DefaultRole, - AnonymousRole: c.AnonymousRole, - AllowedRoles: c.AllowedRoles, - } - if len(c.Auth.TrustedProxies) > 0 { - cfg.TrustedProxies = make([]netip.Prefix, 0, len(c.Auth.TrustedProxies)) - for _, p := range c.Auth.TrustedProxies { - if pfx, err := ParseTrustedProxy(p); err == nil { - cfg.TrustedProxies = append(cfg.TrustedProxies, pfx) - } + Mode: a.Mode, + JWTSecret: secret, + JWKSURL: a.JWT.JWKSURL, + JWKSCacheTTL: a.JWT.JWKSCacheTTL, + JWTIssuer: a.JWT.Issuer, + JWTAudience: a.JWT.Audience, + Leeway: a.JWT.Leeway, + RoleClaimPath: a.JWT.RoleClaimPath, + HeaderPrefix: a.Headers.Prefix, + HeaderClaims: a.Headers.Claims, + HeaderRoleClaim: a.Headers.RoleClaim, + DefaultRole: r.Default, + AnonymousRole: r.Anonymous, + AllowedRoles: r.Allowed, + SkipRoleSwitch: !r.Switch, + } + for _, p := range a.Headers.TrustedProxies { + if pfx, err := ParseTrustedProxy(p); err == nil { + cfg.TrustedProxies = append(cfg.TrustedProxies, pfx) } } - return cfg + return cfg, nil } diff --git a/docs/upgrading.md b/docs/upgrading.md index 062db82..0434269 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -45,3 +45,71 @@ releases (format 9) are refused: regenerate them with `pdbq schema dump` or `*introspect.UnsupportedServerError` on older servers, and so does every connection `pgexec.Connect`'s pool opens to one. `RangeType.Multirange` is always set by introspection. + +### Identity configuration, strict config, typed plugin settings + +The products' `rls` section is replaced by three shared `confx` sections, +and configuration loading is strict. Both products use the same keys: + +```yaml +auth: + mode: jwt # jwt | headers | none + jwt: {secret, secret_file, jwks_url, jwks_cache_ttl, issuer, audience, leeway, role_claim_path} + headers: {prefix, claims, role_claim, trusted_proxies} + mint_type: "" +roles: {switch: true, anonymous: "", default: "", allowed: []} +claims: {prefix: jwt.claims, json_setting: ""} +``` + +| 0.x key | 1.0 key | Notes | +|---|---|---| +| `rls.enabled: true` | `roles.switch: true` | default | +| `rls.enabled: false` | `roles.switch: false` | credentials are still verified; for no authentication at all also set `auth.mode: none` | +| `rls.anonymous_role` (default `anonymous`) | `roles.anonymous` (default empty) | empty answers requests without credentials with 401 and `WWW-Authenticate`; set it to keep anonymous access | +| `rls.default_role` | `roles.default` | | +| `rls.allowed_roles` | `roles.allowed` | | +| `rls.role_claim` | `auth.jwt.role_claim_path` / `auth.headers.role_claim` | jwt takes a path such as `app_metadata.role` | +| `rls.claims_prefix` (default `pdbq.claims`) | `claims.prefix` (default `jwt.claims`) | set `claims.prefix: pdbq.claims` to keep existing policies, or update them | +| — | `claims.json_setting` | e.g. `request.jwt.claims` for PostgREST/Supabase policies | +| `rls.auth.mode` | `auth.mode` | unknown modes are errors in `auth.New` too | +| `rls.auth.jwt_secret` | `auth.jwt.secret` | or `auth.jwt.secret_file` | +| `rls.auth.jwks_url` | `auth.jwt.jwks_url` | | +| `rls.auth.jwks_cache_ttl` | `auth.jwt.jwks_cache_ttl` | | +| `rls.auth.jwt_issuer` | `auth.jwt.issuer` | | +| `rls.auth.jwt_audience` | `auth.jwt.audience` | | +| — | `auth.jwt.leeway` | default `0s` | +| `rls.auth.header_prefix` | `auth.headers.prefix` | | +| `rls.auth.header_claims` | `auth.headers.claims` | | +| `rls.auth.trusted_proxies` | `auth.headers.trusted_proxies` | required in headers mode (empty no longer trusts every peer) | +| `rls.auth.jwt_type` | `auth.mint_type` | | +| `log.format: ` | `log.format: text` or `json` | other values are rejected | + +Go API changes: + +- **`auth`**: `New` returns `(*Authenticator, error)` and rejects an unknown + mode, a jwt mode without a secret or JWKS URL and a headers mode without + trusted proxies. `Config.Mode` is the typed `auth.Mode`; `Config.Enabled` + is gone (use `SkipRoleSwitch` to run as the connection role, with + credentials still verified); `Config.RoleClaim` is split into + `RoleClaimPath` (jwt) and `HeaderRoleClaim` (headers). An empty + `AnonymousRole` refuses requests without credentials with + `ErrAuthRequired`, a credential resolving to no role is + `ErrRoleNotAllowed`, and a role claim that is not a non-empty string is + `ErrInvalidToken`. `Challenge(err)` gives the `WWW-Authenticate` value. + The `Bearer` scheme is case-insensitive. +- **`pgexec`**: `DefaultClaimsPrefix` is gone (`confx.DefaultClaimsPrefix` is + `jwt.claims`); an empty `Identity.ClaimsPrefix` sets no per-claim settings. + `Identity.ClaimsJSONSetting` sets every claim as one JSON object. SQLSTATE + class 21 classifies as `UserInput`. +- **`confx`**: `RLS` and the flat `Auth` fields are replaced by `Auth`, + `JWT`, `Headers`, `Roles` and `Claims`; `ValidateRLS` by + `ValidateIdentity(Auth, Roles, Claims)`; `AuthConfig(RLS)` by + `AuthConfig(Auth, Roles) (auth.Config, error)`. `Plugins` is generic, + `Plugins[S]`, holding the product's typed settings struct. `Load` rejects + unknown keys (file keys, and environment variables whose first segment + names a section) with the key they moved to or the closest valid one; + products add their own renames with `WithMoved`. +- **`httpx`**: `CORS`, `Preflight` and `CORSWithPreflight` take a + `CORSPolicy{Origins, AllowMethods, ExposeHeaders}`; CORS and gzip add to + `Vary` instead of replacing it. +- The test fixture's policies read `jwt.claims.user_id`. diff --git a/go.mod b/go.mod index 6296241..276eca5 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/suprbdev/pdbcore go 1.26.0 require ( + github.com/go-viper/mapstructure/v2 v2.4.0 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/jackc/pgx/v5 v5.10.0 github.com/knadh/koanf/parsers/yaml v1.1.0 @@ -18,7 +19,6 @@ require ( github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect - github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect diff --git a/httpx/cors.go b/httpx/cors.go index 888c463..be5ab53 100644 --- a/httpx/cors.go +++ b/httpx/cors.go @@ -4,7 +4,24 @@ // products. package httpx -import "net/http" +import ( + "net/http" + "strings" +) + +// CORSPolicy is the cross-origin policy of a set of routes. +type CORSPolicy struct { + // Origins is the allowlist: exact origins, or "*" to allow any. An + // allowed origin is echoed in Access-Control-Allow-Origin. + Origins []string + // AllowMethods is the literal Access-Control-Allow-Methods value of + // preflight responses, e.g. "POST, GET, OPTIONS". + AllowMethods string + // ExposeHeaders lists the response headers, beyond the CORS-safelisted + // ones, that browsers let scripts read (Access-Control-Expose-Headers), + // e.g. Content-Range or ETag. + ExposeHeaders []string +} // OriginAllowed reports whether origin matches the allowlist: exact match, // or "*" to allow any. @@ -17,34 +34,63 @@ func OriginAllowed(origins []string, origin string) bool { return false } -// CORS sets Access-Control-Allow-Origin on responses whose Origin header -// matches an allowed origin (exact match, or "*" to allow any). Preflight -// requests are not answered here — mount Preflight on the paths that need -// it (products differ in method sets), or wrap with CORSWithPreflight. -func CORS(origins []string, next http.Handler) http.Handler { +// AddVary adds names to the Vary header of h, keeping the values already +// there and skipping names it already lists (compared case-insensitively), +// so middlewares that each vary on a request header compose in any order. +func AddVary(h http.Header, names ...string) { + for _, name := range names { + if !varies(h, name) { + h.Add("Vary", name) + } + } +} + +func varies(h http.Header, name string) bool { + for _, v := range h.Values("Vary") { + for _, tok := range strings.Split(v, ",") { + if tok = strings.TrimSpace(tok); tok == "*" || strings.EqualFold(tok, name) { + return true + } + } + } + return false +} + +// CORS adds the cross-origin headers of p to responses: Vary: Origin on +// every response (the headers depend on it), and for a request whose Origin +// is allowed, Access-Control-Allow-Origin echoing it and +// Access-Control-Expose-Headers listing p.ExposeHeaders. Preflight requests +// are not answered here: mount Preflight on the paths that need it, or wrap +// with CORSWithPreflight. +func CORS(p CORSPolicy, next http.Handler) http.Handler { + expose := strings.Join(p.ExposeHeaders, ", ") return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if origin := r.Header.Get("Origin"); origin != "" && OriginAllowed(origins, origin) { - w.Header().Set("Access-Control-Allow-Origin", origin) - w.Header().Set("Vary", "Origin") + h := w.Header() + AddVary(h, "Origin") + if origin := r.Header.Get("Origin"); origin != "" && OriginAllowed(p.Origins, origin) { + h.Set("Access-Control-Allow-Origin", origin) + if expose != "" { + h.Set("Access-Control-Expose-Headers", expose) + } } next.ServeHTTP(w, r) }) } // Preflight answers CORS preflight (OPTIONS) requests: 204 with the allow -// headers for an allowed origin, a bare 204 otherwise. allowMethods is the -// literal Access-Control-Allow-Methods value (e.g. "POST, GET, OPTIONS"). -func Preflight(origins []string, allowMethods string) http.HandlerFunc { +// headers for an allowed origin, a bare 204 otherwise. The allowed request +// headers echo Access-Control-Request-Headers. +func Preflight(p CORSPolicy) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + h := w.Header() + AddVary(h, "Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers") origin := r.Header.Get("Origin") - if origin == "" || !OriginAllowed(origins, origin) { + if origin == "" || !OriginAllowed(p.Origins, origin) { w.WriteHeader(http.StatusNoContent) return } - h := w.Header() h.Set("Access-Control-Allow-Origin", origin) - h.Set("Vary", "Origin") - h.Set("Access-Control-Allow-Methods", allowMethods) + h.Set("Access-Control-Allow-Methods", p.AllowMethods) if reqHeaders := r.Header.Get("Access-Control-Request-Headers"); reqHeaders != "" { h.Set("Access-Control-Allow-Headers", reqHeaders) } @@ -56,9 +102,9 @@ func Preflight(origins []string, allowMethods string) http.HandlerFunc { // CORSWithPreflight combines CORS with a catch-all preflight: OPTIONS // requests carrying Access-Control-Request-Method are answered by Preflight // on every path; everything else flows through CORS to next. -func CORSWithPreflight(origins []string, allowMethods string, next http.Handler) http.Handler { - preflight := Preflight(origins, allowMethods) - cors := CORS(origins, next) +func CORSWithPreflight(p CORSPolicy, next http.Handler) http.Handler { + preflight := Preflight(p) + cors := CORS(p, next) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" { preflight(w, r) diff --git a/httpx/gzip.go b/httpx/gzip.go index afa5b33..6e8c161 100644 --- a/httpx/gzip.go +++ b/httpx/gzip.go @@ -28,7 +28,7 @@ func Gzip(next http.Handler) http.Handler { return } w.Header().Set("Content-Encoding", "gzip") - w.Header().Add("Vary", "Accept-Encoding") + AddVary(w.Header(), "Accept-Encoding") gz := gzipPool.Get().(*gzip.Writer) gz.Reset(w) defer func() { diff --git a/httpx/httpx_test.go b/httpx/httpx_test.go index b3e575c..4972e86 100644 --- a/httpx/httpx_test.go +++ b/httpx/httpx_test.go @@ -36,7 +36,7 @@ func TestHealthz(t *testing.T) { } func TestCORSAllowedOrigin(t *testing.T) { - h := CORS([]string{"https://example.com"}, health()) + h := CORS(CORSPolicy{Origins: []string{"https://example.com"}}, health()) rec := do(h, "GET", "/healthz", map[string]string{"Origin": "https://example.com"}) if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "https://example.com" { t.Fatalf("Access-Control-Allow-Origin = %q, want https://example.com", got) @@ -47,15 +47,18 @@ func TestCORSAllowedOrigin(t *testing.T) { } func TestCORSDisallowedOrigin(t *testing.T) { - h := CORS([]string{"https://example.com"}, health()) + h := CORS(CORSPolicy{Origins: []string{"https://example.com"}}, health()) rec := do(h, "GET", "/healthz", map[string]string{"Origin": "https://evil.com"}) if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "" { t.Fatalf("Access-Control-Allow-Origin = %q, want empty for disallowed origin", got) } + if got := rec.Header().Get("Vary"); got != "Origin" { + t.Fatalf("Vary = %q, want Origin on every response", got) + } } func TestCORSWildcard(t *testing.T) { - h := CORS([]string{"*"}, health()) + h := CORS(CORSPolicy{Origins: []string{"*"}}, health()) rec := do(h, "GET", "/healthz", map[string]string{"Origin": "https://anything.example"}) if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "https://anything.example" { t.Fatalf("Access-Control-Allow-Origin = %q, want echoed origin for wildcard config", got) @@ -63,7 +66,7 @@ func TestCORSWildcard(t *testing.T) { } func TestCORSNoOriginHeader(t *testing.T) { - h := CORS([]string{"*"}, health()) + h := CORS(CORSPolicy{Origins: []string{"*"}}, health()) rec := do(h, "GET", "/healthz", nil) if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "" { t.Fatalf("Access-Control-Allow-Origin = %q, want empty without Origin", got) @@ -72,7 +75,7 @@ func TestCORSNoOriginHeader(t *testing.T) { func TestPreflight(t *testing.T) { mux := http.NewServeMux() - mux.Handle("OPTIONS /graphql", Preflight([]string{"https://example.com"}, "POST, GET, OPTIONS")) + mux.Handle("OPTIONS /graphql", Preflight(CORSPolicy{Origins: []string{"https://example.com"}, AllowMethods: "POST, GET, OPTIONS"})) rec := do(mux, "OPTIONS", "/graphql", map[string]string{ "Origin": "https://example.com", "Access-Control-Request-Method": "POST", @@ -95,8 +98,54 @@ func TestPreflight(t *testing.T) { } } +func TestCORSExposeHeaders(t *testing.T) { + p := CORSPolicy{Origins: []string{"https://example.com"}, ExposeHeaders: []string{"Content-Range", "ETag", "Location"}} + rec := do(CORS(p, health()), "GET", "/healthz", map[string]string{"Origin": "https://example.com"}) + if got := rec.Header().Get("Access-Control-Expose-Headers"); got != "Content-Range, ETag, Location" { + t.Fatalf("Access-Control-Expose-Headers = %q", got) + } + rec = do(CORS(p, health()), "GET", "/healthz", map[string]string{"Origin": "https://evil.com"}) + if got := rec.Header().Get("Access-Control-Expose-Headers"); got != "" { + t.Fatalf("Access-Control-Expose-Headers = %q for a disallowed origin", got) + } + rec = do(CORS(CORSPolicy{Origins: []string{"*"}}, health()), "GET", "/healthz", map[string]string{"Origin": "https://a.example"}) + if _, ok := rec.Header()["Access-Control-Expose-Headers"]; ok { + t.Fatal("Access-Control-Expose-Headers set without ExposeHeaders") + } +} + +func TestCORSAndGzipKeepBothVary(t *testing.T) { + p := CORSPolicy{Origins: []string{"*"}} + hdr := map[string]string{"Origin": "https://a.example", "Accept-Encoding": "gzip"} + for name, h := range map[string]http.Handler{ + "cors outside": CORS(p, Gzip(health())), + "gzip outside": Gzip(CORS(p, health())), + } { + rec := do(h, "GET", "/healthz", hdr) + got := rec.Header().Values("Vary") + if len(got) != 2 || !varies(rec.Header(), "Origin") || !varies(rec.Header(), "Accept-Encoding") { + t.Errorf("%s: Vary = %q, want Origin and Accept-Encoding once each", name, got) + } + } +} + +func TestAddVary(t *testing.T) { + h := http.Header{} + h.Set("Vary", "accept-encoding, Cookie") + AddVary(h, "Accept-Encoding", "Origin", "origin") + if got := h.Values("Vary"); len(got) != 2 || got[0] != "accept-encoding, Cookie" || got[1] != "Origin" { + t.Fatalf("Vary = %q", got) + } + h = http.Header{} + h.Set("Vary", "*") + AddVary(h, "Origin") + if got := h.Values("Vary"); len(got) != 1 { + t.Fatalf("Vary = %q, want * alone", got) + } +} + func TestPreflightDisallowedOrigin(t *testing.T) { - h := Preflight([]string{"https://example.com"}, "POST, GET, OPTIONS") + h := Preflight(CORSPolicy{Origins: []string{"https://example.com"}, AllowMethods: "POST, GET, OPTIONS"}) rec := do(h, "OPTIONS", "/graphql", map[string]string{"Origin": "https://evil.com"}) if rec.Code != http.StatusNoContent { t.Fatalf("status = %d, want 204", rec.Code) @@ -107,7 +156,7 @@ func TestPreflightDisallowedOrigin(t *testing.T) { } func TestCORSWithPreflight(t *testing.T) { - h := CORSWithPreflight([]string{"*"}, "GET, POST, OPTIONS", health()) + h := CORSWithPreflight(CORSPolicy{Origins: []string{"*"}, AllowMethods: "GET, POST, OPTIONS"}, health()) rec := do(h, "OPTIONS", "/anything", map[string]string{ "Origin": "https://a.example", "Access-Control-Request-Method": "POST", }) @@ -154,8 +203,8 @@ func TestGzipSkippedWithoutAcceptEncoding(t *testing.T) { func TestGzipSkipsCORSPreflight(t *testing.T) { mux := http.NewServeMux() - mux.Handle("OPTIONS /graphql", Preflight([]string{"*"}, "POST, GET, OPTIONS")) - h := Gzip(CORS([]string{"*"}, mux)) + mux.Handle("OPTIONS /graphql", Preflight(CORSPolicy{Origins: []string{"*"}, AllowMethods: "POST, GET, OPTIONS"})) + h := Gzip(CORS(CORSPolicy{Origins: []string{"*"}}, mux)) rec := do(h, "OPTIONS", "/graphql", map[string]string{"Origin": "https://example.com", "Accept-Encoding": "gzip"}) if rec.Code != http.StatusNoContent { t.Fatalf("preflight status = %d, want 204", rec.Code) diff --git a/pgexec/batch_e2e_test.go b/pgexec/batch_e2e_test.go index 587cf8b..7bf0a09 100644 --- a/pgexec/batch_e2e_test.go +++ b/pgexec/batch_e2e_test.go @@ -73,7 +73,7 @@ type sessionState struct { } const stateSQL = `SELECT pg_backend_pid(), current_user, session_user, current_setting('role'), - coalesce(current_setting('pdbq.claims.user_id', true), ''), current_setting('is_superuser')` + coalesce(current_setting('jwt.claims.user_id', true), ''), current_setting('is_superuser')` func scanState(row pgx.Row) (sessionState, error) { var s sessionState @@ -106,15 +106,15 @@ func TestQueryTxRLSMatrix(t *testing.T) { want int }{ {pgexec.Identity{Role: "anonymous"}, 3}, - {pgexec.Identity{Role: "app_user", Claims: map[string]any{"user_id": "1", "n": 5}}, 4}, - {pgexec.Identity{Role: "app_user", Claims: map[string]any{"user_id": "2"}}, 3}, + {pgexec.Identity{Role: "app_user", ClaimsPrefix: "jwt.claims", Claims: map[string]any{"user_id": "1", "n": 5}}, 4}, + {pgexec.Identity{Role: "app_user", ClaimsPrefix: "jwt.claims", Claims: map[string]any{"user_id": "2"}}, 3}, } { var in sessionState var n int var nClaim string err := pgexec.QueryTx(ctx, pool, tm.opts, tc.id, pgexec.Stmt{SQL: stateSQL, Scan: func(r pgx.Row) (err error) { in, err = scanState(r); return err }}, - pgexec.Stmt{SQL: "SELECT count(*), coalesce(current_setting('pdbq.claims.n', true), '') FROM posts", + pgexec.Stmt{SQL: "SELECT count(*), coalesce(current_setting('jwt.claims.n', true), '') FROM posts", Scan: func(r pgx.Row) error { return r.Scan(&n, &nClaim) }}, ) if err != nil { @@ -144,7 +144,7 @@ func TestQueryTxRLSMatrix(t *testing.T) { func TestQueryTxRoleMatchesSetLocalRole(t *testing.T) { pool := onePool(t, "") ctx := context.Background() - id := pgexec.Identity{Role: "app_user", Claims: map[string]any{"user_id": "9"}} + id := pgexec.Identity{Role: "app_user", ClaimsPrefix: "jwt.claims", Claims: map[string]any{"user_id": "9"}} var viaTx, viaBatch sessionState err := pgexec.RunTx(ctx, pool, pgexec.TxOptions{RLS: true}, id, func(q pgexec.Querier) (err error) { viaTx, err = scanState(q.QueryRow(ctx, stateSQL)) @@ -165,7 +165,7 @@ func TestQueryTxRoleMatchesSetLocalRole(t *testing.T) { } func TestQueryTxNoLeakAfterFailure(t *testing.T) { - id := pgexec.Identity{Role: "app_user", Claims: map[string]any{"user_id": "1"}} + id := pgexec.Identity{Role: "app_user", ClaimsPrefix: "jwt.claims", Claims: map[string]any{"user_id": "1"}} boom := errors.New("scan veto") for _, mode := range execModes { for _, tm := range txModes { @@ -214,7 +214,7 @@ func TestQueryTxNoLeakAfterFailure(t *testing.T) { func TestQueryTxAtomic(t *testing.T) { pool := testPool(t) ctx := context.Background() - id := pgexec.Identity{Role: "app_user", Claims: map[string]any{"user_id": "1"}} + id := pgexec.Identity{Role: "app_user", ClaimsPrefix: "jwt.claims", Claims: map[string]any{"user_id": "1"}} prefix := fmt.Sprintf("qtx-%d-", time.Now().UnixNano()) t.Cleanup(func() { _, _ = pool.Exec(context.Background(), "DELETE FROM users WHERE email LIKE $1", prefix+"%") }) count := func(email string) int { @@ -319,12 +319,12 @@ func TestQueryTxRetryProbe(t *testing.T) { } } } - id := pgexec.Identity{Role: "app_user", Claims: map[string]any{"user_id": "1"}} + id := pgexec.Identity{Role: "app_user", ClaimsPrefix: "jwt.claims", Claims: map[string]any{"user_id": "1"}} probe := func(retries int) (scans int, uid string, err error) { opts := tm.opts opts.MaxRetries, opts.Log = retries, quietLog err = pgexec.QueryTx(ctx, pool, opts, id, pgexec.Stmt{ - SQL: "SELECT retry_probe(), current_setting('pdbq.claims.user_id')", + SQL: "SELECT retry_probe(), current_setting('jwt.claims.user_id')", Scan: func(r pgx.Row) error { scans++ var v int @@ -373,11 +373,11 @@ func TestQueryTxRejectsOpenTransaction(t *testing.T) { func TestRunTxClaimsOneStatement(t *testing.T) { pool := onePool(t, "") ctx := context.Background() - id := pgexec.Identity{Role: "app_user", Claims: map[string]any{"user_id": "3", "roles": []string{"a", "b"}, "exp": 17}} + id := pgexec.Identity{Role: "app_user", ClaimsPrefix: "jwt.claims", Claims: map[string]any{"user_id": "3", "roles": []string{"a", "b"}, "exp": 17}} err := pgexec.RunTx(ctx, pool, pgexec.TxOptions{RLS: true}, id, func(q pgexec.Querier) error { var uid, roles, exp string - if err := q.QueryRow(ctx, `SELECT current_setting('pdbq.claims.user_id'), current_setting('pdbq.claims.roles'), - current_setting('pdbq.claims.exp')`).Scan(&uid, &roles, &exp); err != nil { + if err := q.QueryRow(ctx, `SELECT current_setting('jwt.claims.user_id'), current_setting('jwt.claims.roles'), + current_setting('jwt.claims.exp')`).Scan(&uid, &roles, &exp); err != nil { return err } if uid != "3" || roles != `["a","b"]` || exp != "17" { @@ -481,7 +481,7 @@ func (o *errObserver) ObserveQuery(_ context.Context, ev pgexec.QueryEvent) { func TestQueryTxRequestedRollbackIsNotAnError(t *testing.T) { pool := testPool(t) ctx := context.Background() - id := pgexec.Identity{Role: "app_user", Claims: map[string]any{"user_id": "1"}} + id := pgexec.Identity{Role: "app_user", ClaimsPrefix: "jwt.claims", Claims: map[string]any{"user_id": "1"}} email := fmt.Sprintf("qtx-rb-%d@example.com", time.Now().UnixNano()) t.Cleanup(func() { _, _ = pool.Exec(context.Background(), "DELETE FROM users WHERE email = $1", email) }) opts := pgexec.TxOptions{RLS: true, ScanBeforeCommit: true} diff --git a/pgexec/batch_test.go b/pgexec/batch_test.go index fed5f4e..743bf11 100644 --- a/pgexec/batch_test.go +++ b/pgexec/batch_test.go @@ -29,7 +29,7 @@ func TestBatchPlanShapes(t *testing.T) { }{ {"implicit, no rls", TxOptions{}, anon, []string{"SELECT 1", "SELECT 2"}}, {"implicit, role", TxOptions{RLS: true}, anon, []string{identitySQL, "SELECT 1", "SELECT 2"}}, - {"implicit, claims only", TxOptions{RLS: true}, Identity{Claims: map[string]any{"sub": "1"}}, []string{claimsSQL, "SELECT 1", "SELECT 2"}}, + {"implicit, claims only", TxOptions{RLS: true}, Identity{ClaimsPrefix: "jwt.claims", Claims: map[string]any{"sub": "1"}}, []string{claimsSQL, "SELECT 1", "SELECT 2"}}, {"implicit, empty identity", TxOptions{RLS: true}, Identity{}, []string{"SELECT 1", "SELECT 2"}}, {"explicit", TxOptions{RLS: true, Isolation: pgx.Serializable}, anon, []string{"BEGIN ISOLATION LEVEL SERIALIZABLE", identitySQL, "SELECT 1", "SELECT 2", "COMMIT"}}, diff --git a/pgexec/bench_e2e_test.go b/pgexec/bench_e2e_test.go index 69c32bf..12610c2 100644 --- a/pgexec/bench_e2e_test.go +++ b/pgexec/bench_e2e_test.go @@ -11,15 +11,15 @@ import ( "github.com/suprbdev/pdbcore/pgexec" ) -const benchSQL = `SELECT jsonb_build_object('id', t.id, 'email', t.email, 'uid', current_setting('pdbq.claims.user_id', true)) FROM users AS t WHERE t.id = $1` +const benchSQL = `SELECT jsonb_build_object('id', t.id, 'email', t.email, 'uid', current_setting('jwt.claims.user_id', true)) FROM users AS t WHERE t.id = $1` var benchIdentities = []struct { name string id pgexec.Identity }{ {"anonymous", pgexec.Identity{Role: "anonymous"}}, - {"role+2claims", pgexec.Identity{Role: "app_user", Claims: map[string]any{"user_id": "1", "role": "app_user"}}}, - {"role+7claims", pgexec.Identity{Role: "app_user", Claims: map[string]any{ + {"role+2claims", pgexec.Identity{Role: "app_user", ClaimsPrefix: "jwt.claims", Claims: map[string]any{"user_id": "1", "role": "app_user"}}}, + {"role+7claims", pgexec.Identity{Role: "app_user", ClaimsPrefix: "jwt.claims", Claims: map[string]any{ "user_id": "1", "role": "app_user", "sub": "1", "iss": "https://issuer.example", "aud": "pdb", "exp": 1900000000, "iat": 1800000000, }}}, } diff --git a/pgexec/classify.go b/pgexec/classify.go index 680cbc6..9a7bea6 100644 --- a/pgexec/classify.go +++ b/pgexec/classify.go @@ -16,7 +16,10 @@ type Class int const ( // OK: err was nil. OK Class = iota - // UserInput: 22* data exceptions, 23502/23514, and 42* other than 42501. + // UserInput: 21* cardinality violations (a row targeted twice by one + // INSERT ... ON CONFLICT DO UPDATE, a scalar subquery returning + // several rows), 22* data exceptions, 23502/23514, and 42* other + // than 42501. UserInput // Permission: 42501 insufficient privilege. Permission @@ -55,7 +58,7 @@ func (c Class) String() string { type Detail int const ( - // Prod passes 22*/23* PG messages, and the messages of malformed + // Prod passes 21*/22*/23* PG messages, and the messages of malformed // full-text/ltree operands, through and hides the rest. Prod Detail = iota // Dev exposes full PG messages (and non-PG error text). @@ -194,7 +197,7 @@ func classOf(code string) Class { return Resource } switch prefix(code) { - case "22", "42": + case "21", "22", "42": return UserInput case "53", "08": return Resource @@ -225,7 +228,7 @@ func SanitizeMessage(pgErr *pgconn.PgError, strict bool) string { return "constraint violation" } return pgErr.Message - case "22": // data exceptions (bad input format) + case "21", "22": // cardinality violations and data exceptions (bad input) if strict { return "invalid input value" } diff --git a/pgexec/classify_test.go b/pgexec/classify_test.go index 978843f..5aa9ea9 100644 --- a/pgexec/classify_test.go +++ b/pgexec/classify_test.go @@ -17,7 +17,7 @@ func TestClassifyClasses(t *testing.T) { code string want Class }{ - {"22P02", UserInput}, {"22001", UserInput}, + {"21000", UserInput}, {"22P02", UserInput}, {"22001", UserInput}, {"23502", UserInput}, {"23514", UserInput}, {"23505", Conflict}, {"23503", Conflict}, {"23001", Conflict}, {"23P01", Conflict}, {"23000", Internal}, @@ -41,6 +41,7 @@ func TestClassifyMessagePolicy(t *testing.T) { perm := pgErr("42501", `permission denied for table users`) undef := pgErr("42703", `column "secret" does not exist`) raise := pgErr("P0001", "nope") + card := pgErr("21000", "ON CONFLICT DO UPDATE command cannot affect row a second time") cases := []struct { name string @@ -57,6 +58,8 @@ func TestClassifyMessagePolicy(t *testing.T) { {"permission strict", perm, Strict, "permission denied"}, {"permission dev", perm, Dev, perm.Message}, {"undefined column prod", undef, Prod, "invalid operation"}, + {"cardinality prod passes through", card, Prod, card.Message}, + {"cardinality strict hidden", card, Strict, "invalid input value"}, {"raise prod", raise, Prod, "database error"}, {"raise strict", raise, Strict, "database error"}, {"raise dev", raise, Dev, "nope"}, diff --git a/pgexec/e2e_test.go b/pgexec/e2e_test.go index 60b9f05..778321a 100644 --- a/pgexec/e2e_test.go +++ b/pgexec/e2e_test.go @@ -49,7 +49,7 @@ func TestRunTxRLSMatrix(t *testing.T) { var n int err := pgexec.RunTx(ctx, pool, pgexec.TxOptions{RLS: true}, id, func(q pgexec.Querier) error { var role, uid string - if err := q.QueryRow(ctx, "SELECT current_user, coalesce(current_setting('pdbq.claims.user_id', true), '')").Scan(&role, &uid); err != nil { + if err := q.QueryRow(ctx, "SELECT current_user, coalesce(current_setting('jwt.claims.user_id', true), '')").Scan(&role, &uid); err != nil { return err } if role != id.Role { @@ -70,10 +70,10 @@ func TestRunTxRLSMatrix(t *testing.T) { if n := count(pgexec.Identity{Role: "anonymous"}); n != 3 { t.Fatalf("anonymous sees %d posts, want 3", n) } - if n := count(pgexec.Identity{Role: "app_user", Claims: map[string]any{"user_id": "1"}}); n != 4 { + if n := count(pgexec.Identity{Role: "app_user", ClaimsPrefix: "jwt.claims", Claims: map[string]any{"user_id": "1"}}); n != 4 { t.Fatalf("app_user#1 sees %d posts, want 4", n) } - if n := count(pgexec.Identity{Role: "app_user", Claims: map[string]any{"user_id": "2"}}); n != 3 { + if n := count(pgexec.Identity{Role: "app_user", ClaimsPrefix: "jwt.claims", Claims: map[string]any{"user_id": "2"}}); n != 3 { t.Fatalf("app_user#2 sees %d posts, want 3", n) } // SET LOCAL: identity must not leak to the pooled connection. @@ -86,6 +86,55 @@ func TestRunTxRLSMatrix(t *testing.T) { } } +func TestClaimsJSONSettingVisibleToPolicies(t *testing.T) { + pool := testPool(t) + ctx := context.Background() + admin, err := pool.Acquire(ctx) + if err != nil { + t.Fatal(err) + } + defer admin.Release() + for _, stmt := range []string{ + `CREATE TABLE IF NOT EXISTS json_claims_probe (owner text NOT NULL)`, + `TRUNCATE json_claims_probe`, + `INSERT INTO json_claims_probe VALUES ('u1'), ('u2'), ('u2')`, + `ALTER TABLE json_claims_probe ENABLE ROW LEVEL SECURITY`, + `DROP POLICY IF EXISTS own ON json_claims_probe`, + `CREATE POLICY own ON json_claims_probe FOR SELECT TO app_user + USING (owner = current_setting('request.jwt.claims', true)::json->>'sub')`, + `GRANT SELECT ON json_claims_probe TO app_user`, + } { + if _, err := admin.Exec(ctx, stmt); err != nil { + t.Fatalf("%s: %v", stmt, err) + } + } + t.Cleanup(func() { _, _ = pool.Exec(context.Background(), `DROP TABLE IF EXISTS json_claims_probe`) }) + count := func(id pgexec.Identity) (n int, doc string) { + err := pgexec.RunTx(ctx, pool, pgexec.TxOptions{RLS: true}, id, func(q pgexec.Querier) error { + return q.QueryRow(ctx, `SELECT (SELECT count(*) FROM json_claims_probe), current_setting('request.jwt.claims', true)`).Scan(&n, &doc) + }) + if err != nil { + t.Fatal(err) + } + return n, doc + } + id := pgexec.Identity{Role: "app_user", ClaimsJSONSetting: "request.jwt.claims", Claims: map[string]any{"sub": "u2", "role": "app_user"}} + if n, doc := count(id); n != 2 || doc != `{"role":"app_user","sub":"u2"}` { + t.Fatalf("u2 sees %d rows with claims %s, want 2", n, doc) + } + id.Claims = nil + if n, doc := count(id); n != 0 || doc != "{}" { + t.Fatalf("no claims: %d rows with claims %q, want 0 and {}", n, doc) + } + var batched int + err = pgexec.QueryTx(ctx, pool, pgexec.TxOptions{RLS: true}, + pgexec.Identity{Role: "app_user", ClaimsJSONSetting: "request.jwt.claims", Claims: map[string]any{"sub": "u1"}}, + pgexec.Stmt{SQL: `SELECT count(*) FROM json_claims_probe`, Scan: func(r pgx.Row) error { return r.Scan(&batched) }}) + if err != nil || batched != 1 { + t.Fatalf("QueryTx: %d rows, err %v, want 1", batched, err) + } +} + func TestRunTxRollbackOnError(t *testing.T) { pool := testPool(t) ctx := context.Background() diff --git a/pgexec/ident.go b/pgexec/ident.go index dc45c72..911cc78 100644 --- a/pgexec/ident.go +++ b/pgexec/ident.go @@ -36,8 +36,8 @@ var reservedClaimsNamespaces = map[string]bool{ "cron": true, "anon": true, "pgrst": true, "bdr": true, "pgroonga": true, } -// ValidateClaimsPrefix checks an Identity.ClaimsPrefix ("" means -// DefaultClaimsPrefix): dot-separated components, each a letter or +// ValidateClaimsPrefix checks an Identity.ClaimsPrefix ("" sets no +// per-claim settings): dot-separated components, each a letter or // underscore followed by letters, digits and underscores, and a first // component that is not a real setting namespace (plpgsql, auto_explain, // postgis, anything starting with pg_, ...). Claims are written to @@ -47,15 +47,29 @@ func ValidateClaimsPrefix(prefix string) error { if prefix == "" { return nil } - parts := strings.Split(prefix, ".") + return validateSettingName("claims prefix", prefix, "jwt.claims") +} + +// ValidateClaimsSetting checks an Identity.ClaimsJSONSetting: the rules of +// ValidateClaimsPrefix, plus at least two components, since PostgreSQL only +// accepts custom settings whose name contains a dot. +func ValidateClaimsSetting(name string) error { + if !strings.Contains(name, ".") { + return fmt.Errorf("invalid claims setting %q: use a dotted name such as %q", name, "request.jwt.claims") + } + return validateSettingName("claims setting", name, "request.jwt.claims") +} + +func validateSettingName(what, name, example string) error { + parts := strings.Split(name, ".") for _, p := range parts { if p == "" || !simpleIdent(p) || (p[0] >= '0' && p[0] <= '9') { - return fmt.Errorf("invalid claims prefix %q: use dot-separated identifiers such as %q", prefix, DefaultClaimsPrefix) + return fmt.Errorf("invalid %s %q: use dot-separated identifiers such as %q", what, name, example) } } first := strings.ToLower(parts[0]) if strings.HasPrefix(first, "pg_") || reservedClaimsNamespaces[first] { - return fmt.Errorf("invalid claims prefix %q: %q is a server or extension settings namespace", prefix, parts[0]) + return fmt.Errorf("invalid %s %q: %q is a server or extension settings namespace", what, name, parts[0]) } return nil } diff --git a/pgexec/ident_test.go b/pgexec/ident_test.go index dbe0c1b..13f3f0a 100644 --- a/pgexec/ident_test.go +++ b/pgexec/ident_test.go @@ -63,3 +63,16 @@ func TestValidateClaimsPrefix(t *testing.T) { } } } + +func TestValidateClaimsSetting(t *testing.T) { + for _, s := range []string{"request.jwt.claims", "app.claims", "_x.y1"} { + if err := ValidateClaimsSetting(s); err != nil { + t.Errorf("ValidateClaimsSetting(%q) = %v, want nil", s, err) + } + } + for _, s := range []string{"", "claims", ".claims", "a..b", "1a.b", "plpgsql.x", "pg_trgm.x", "pgrst.claims", "a.b;"} { + if err := ValidateClaimsSetting(s); err == nil { + t.Errorf("ValidateClaimsSetting(%q) = nil, want an error", s) + } + } +} diff --git a/pgexec/tx.go b/pgexec/tx.go index 08414db..3e68db1 100644 --- a/pgexec/tx.go +++ b/pgexec/tx.go @@ -27,22 +27,24 @@ type TxBeginner interface { BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error) } -// DefaultClaimsPrefix is the set_config namespace used when -// Identity.ClaimsPrefix is empty (kept as pdbq's so existing RLS policies -// work with either product). -const DefaultClaimsPrefix = "pdbq.claims" - // Identity is the request identity applied inside a transaction. type Identity struct { // Role is the database role to SET LOCAL ROLE to ("" = no switch). Role string - // Claims are exposed as set_config(ClaimsPrefix.key, value, true). - // String values are set verbatim; anything else is JSON-encoded. Keys - // failing ValidClaimKey are skipped. + // Claims are exposed as set_config(ClaimsPrefix.key, value, true) + // and, as one JSON object, as set_config(ClaimsJSONSetting, json, + // true). String values are set verbatim; anything else is + // JSON-encoded. Keys failing ValidClaimKey are skipped by the + // per-claim settings. Claims map[string]any - // ClaimsPrefix defaults to DefaultClaimsPrefix and must pass - // ValidateClaimsPrefix. + // ClaimsPrefix is the namespace of the per-claim settings; it must + // pass ValidateClaimsPrefix. Empty sets no per-claim settings. ClaimsPrefix string + // ClaimsJSONSetting names the setting that receives every claim as + // one JSON object ("{}" when there are none), e.g. + // request.jwt.claims; it must pass ValidateClaimsSetting. Empty sets + // no JSON setting. + ClaimsJSONSetting string } // TxOptions controls RunTx and QueryTx. @@ -147,45 +149,60 @@ const claimsSQL = `SELECT count(set_config(c.k, c.v, true)) FROM unnest($1::text // role passed as a bind parameter instead of a quoted identifier. const identitySQL = `SELECT set_config('role', $1, true), (SELECT count(set_config(c.k, c.v, true)) FROM unnest($2::text[], $3::text[]) AS c(k, v))` -// claimSettings returns the set_config names (ClaimsPrefix + "." + key) and -// values for id.Claims, sorted by name. String values are used verbatim and -// anything else is JSON-encoded; keys failing [ValidClaimKey] and values -// that cannot be encoded are skipped. A prefix failing -// [ValidateClaimsPrefix] is an error. +// claimSettings returns the set_config names and values for id: one +// ClaimsPrefix + "." + key setting per claim, sorted by name, then the +// ClaimsJSONSetting holding every claim as a JSON object. String values are +// used verbatim and anything else is JSON-encoded; keys failing +// [ValidClaimKey] and values that cannot be encoded are skipped. A prefix +// failing [ValidateClaimsPrefix], a JSON setting failing +// [ValidateClaimsSetting] and claims that cannot be encoded as one JSON +// object are errors. func claimSettings(id Identity) (names, values []string, err error) { if err := ValidateClaimsPrefix(id.ClaimsPrefix); err != nil { return nil, nil, err } - if len(id.Claims) == 0 { - return nil, nil, nil - } - prefix := id.ClaimsPrefix - if prefix == "" { - prefix = DefaultClaimsPrefix + if id.ClaimsJSONSetting != "" { + if err := ValidateClaimsSetting(id.ClaimsJSONSetting); err != nil { + return nil, nil, err + } } - keys := make([]string, 0, len(id.Claims)) - for k := range id.Claims { - if ValidClaimKey(k) { - keys = append(keys, k) + if id.ClaimsPrefix != "" && len(id.Claims) > 0 { + keys := make([]string, 0, len(id.Claims)) + for k := range id.Claims { + if ValidClaimKey(k) { + keys = append(keys, k) + } + } + sort.Strings(keys) + names = make([]string, 0, len(keys)+1) + values = make([]string, 0, len(keys)+1) + for _, k := range keys { + var val string + switch tv := id.Claims[k].(type) { + case string: + val = tv + default: + b, err := json.Marshal(tv) + if err != nil { + continue + } + val = string(b) + } + names = append(names, id.ClaimsPrefix+"."+k) + values = append(values, val) } } - sort.Strings(keys) - names = make([]string, 0, len(keys)) - values = make([]string, 0, len(keys)) - for _, k := range keys { - var val string - switch tv := id.Claims[k].(type) { - case string: - val = tv - default: - b, err := json.Marshal(tv) + if id.ClaimsJSONSetting != "" { + doc := "{}" + if len(id.Claims) > 0 { + b, err := json.Marshal(id.Claims) if err != nil { - continue + return nil, nil, fmt.Errorf("encode claims: %w", err) } - val = string(b) + doc = string(b) } - names = append(names, prefix+"."+k) - values = append(values, val) + names = append(names, id.ClaimsJSONSetting) + values = append(values, doc) } return names, values, nil } diff --git a/pgexec/tx_test.go b/pgexec/tx_test.go index 21bbb58..bee9bc0 100644 --- a/pgexec/tx_test.go +++ b/pgexec/tx_test.go @@ -89,8 +89,9 @@ func serFail() error { func TestRunTxAppliesIdentityThenCommits(t *testing.T) { db := &fakeDB{} id := Identity{ - Role: "app_user", - Claims: map[string]any{"user_id": "7", "roles": []string{"a"}, "bad-key": "x"}, + Role: "app_user", + ClaimsPrefix: "jwt.claims", + Claims: map[string]any{"user_id": "7", "roles": []string{"a"}, "bad-key": "x"}, } calls := 0 err := RunTx(context.Background(), db, TxOptions{Isolation: pgx.Serializable, RLS: true}, id, func(q Querier) error { @@ -110,7 +111,7 @@ func TestRunTxAppliesIdentityThenCommits(t *testing.T) { if tx.stmts[0] != `SET LOCAL ROLE "app_user"` { t.Fatalf("first stmt = %q", tx.stmts[0]) } - want := claimsSQL + ` [{pdbq.claims.roles,pdbq.claims.user_id}, {["a"],7}]` + want := claimsSQL + ` [{jwt.claims.roles,jwt.claims.user_id}, {["a"],7}]` if len(tx.stmts) != 2 || tx.stmts[1] != want { t.Fatalf("stmts = %q, want role then one claims statement %q", tx.stmts, want) } @@ -118,7 +119,7 @@ func TestRunTxAppliesIdentityThenCommits(t *testing.T) { func TestApplyIdentityNoClaimsNoStatement(t *testing.T) { tx := &fakeTx{} - if err := ApplyIdentity(context.Background(), tx, Identity{Claims: map[string]any{"bad-key": "x"}}); err != nil { + if err := ApplyIdentity(context.Background(), tx, Identity{ClaimsPrefix: "jwt.claims", Claims: map[string]any{"bad-key": "x"}}); err != nil { t.Fatal(err) } if len(tx.stmts) != 0 { @@ -324,3 +325,48 @@ func TestParseIsolation(t *testing.T) { } } } + +func TestApplyIdentityClaimsJSONSetting(t *testing.T) { + cases := []struct { + name string + id Identity + want string + }{ + {"json only", Identity{ClaimsJSONSetting: "request.jwt.claims", Claims: map[string]any{"sub": "u1", "n": 2}}, + claimsSQL + ` [{request.jwt.claims}, {{"n":2,"sub":"u1"}}]`}, + {"prefix and json", Identity{ClaimsPrefix: "jwt.claims", ClaimsJSONSetting: "request.jwt.claims", Claims: map[string]any{"bad-key": "x", "sub": "u1"}}, + claimsSQL + ` [{jwt.claims.sub,request.jwt.claims}, {u1,{"bad-key":"x","sub":"u1"}}]`}, + {"anonymous gets an empty object", Identity{ClaimsPrefix: "jwt.claims", ClaimsJSONSetting: "request.jwt.claims"}, + claimsSQL + ` [{request.jwt.claims}, {{}}]`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + tx := &fakeTx{} + if err := ApplyIdentity(context.Background(), tx, tc.id); err != nil { + t.Fatal(err) + } + if len(tx.stmts) != 1 || tx.stmts[0] != tc.want { + t.Fatalf("stmts = %q, want [%q]", tx.stmts, tc.want) + } + }) + } +} + +func TestApplyIdentityNoPrefixSetsNoClaims(t *testing.T) { + tx := &fakeTx{} + if err := ApplyIdentity(context.Background(), tx, Identity{Claims: map[string]any{"sub": "u1"}}); err != nil { + t.Fatal(err) + } + if len(tx.stmts) != 0 { + t.Fatalf("stmts = %q, want none", tx.stmts) + } +} + +func TestApplyIdentityRejectsBadClaimsSetting(t *testing.T) { + for _, name := range []string{"claims", "plpgsql.claims", "pg_x.y", "a..b"} { + err := ApplyIdentity(context.Background(), &fakeTx{}, Identity{ClaimsJSONSetting: name}) + if err == nil || !strings.HasPrefix(err.Error(), "invalid claims setting") { + t.Errorf("%q: err = %v", name, err) + } + } +} diff --git a/testutil/fixture.sql b/testutil/fixture.sql index 8b7af7c..97b0257 100644 --- a/testutil/fixture.sql +++ b/testutil/fixture.sql @@ -271,7 +271,7 @@ BEGIN END $$; -- Roles for the RLS demo. The anonymous role only sees published posts; --- app_user additionally sees their own rows (claim pdbq.claims.user_id). +-- app_user additionally sees their own rows (claim jwt.claims.user_id). DO $$ BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'anonymous') THEN CREATE ROLE anonymous NOLOGIN; @@ -293,10 +293,10 @@ GRANT USAGE ON SEQUENCE retry_probe_seq TO anonymous, app_user; ALTER TABLE posts ENABLE ROW LEVEL SECURITY; CREATE POLICY posts_public ON posts FOR SELECT - USING (published OR author_id = NULLIF(current_setting('pdbq.claims.user_id', true), '')::integer); + USING (published OR author_id = NULLIF(current_setting('jwt.claims.user_id', true), '')::integer); CREATE POLICY posts_own_writes ON posts FOR ALL TO app_user - USING (author_id = NULLIF(current_setting('pdbq.claims.user_id', true), '')::integer) - WITH CHECK (author_id = NULLIF(current_setting('pdbq.claims.user_id', true), '')::integer); + USING (author_id = NULLIF(current_setting('jwt.claims.user_id', true), '')::integer) + WITH CHECK (author_id = NULLIF(current_setting('jwt.claims.user_id', true), '')::integer); -- Seed data. INSERT INTO users (email, full_name, mood, settings, tags, address, prev_addresses, moods) VALUES