Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,19 @@ becomes the release notes of the next tag.

## [Unreleased]

### Fixed

- A request body over `limits.max_body_bytes` is answered `413 body_too_large`
whether or not it is valid JSON (it was `400 invalid_request` for a body
that fails to parse); a GET query string over the limit gets the same
answer.
- `pdbq plugins list` reports the effective state: `simple_names` shows
`disabled` until `plugins.settings.simple_names.enabled` is `true`.
- A removed or moved 0.x flag (`--rls.enabled`, `--server.max_cost`,
kebab-case plugin flags) names its replacement or the reason it was removed,
as the config keys and environment variables do, instead of a bare
`unknown flag`.

### Documentation

- Fix the quickstart's Secure setup (the query is `allTodos`, the `anonymous`
Expand Down
4 changes: 2 additions & 2 deletions cmd/pdbq/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ func rootCmd() *cobra.Command {
SilenceUsage: true,
SilenceErrors: true,
}
root.SetFlagErrorFunc(func(_ *cobra.Command, err error) error { return config.ExplainFlagError(err) })
root.PersistentFlags().String("config", "", "path to config file (default: ./pdbq.yaml if present)")
root.AddCommand(serveCmd(), queryCmd(), schemaCmd(), configCmd(), pluginsCmd())
return root
Expand Down Expand Up @@ -491,10 +492,9 @@ func pluginsCmd() *cobra.Command {
return err
}
app := pdbq.New(cfg)
disabled := cfg.DisabledPlugins()
for _, p := range app.Plugins() {
status := "enabled"
if disabled[p.Name()] {
if !cfg.PluginEnabled(p.Name()) {
status = "disabled"
}
fmt.Printf("%-20s priority=%-4d %-8s hooks: %s\n",
Expand Down
20 changes: 20 additions & 0 deletions cmd/pdbq/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"bytes"
"errors"
"io"
"path/filepath"
"strings"
"testing"
Expand Down Expand Up @@ -135,3 +136,22 @@ func TestParseClaims(t *testing.T) {
t.Errorf("empty: %v, %v", got, err)
}
}

func TestOldFlagsNameTheirReplacement(t *testing.T) {
for args, want := range map[string]string{
"serve --rls.enabled=false": "unknown flag: --rls.enabled: moved to --roles.switch",
"serve --server.max_cost=5": "unknown flag: --server.max_cost: moved to --limits.max_cost",
"serve --plugins.settings.advanced-filters.enabled=1": "moved to --plugins.settings.advanced_filters.enabled",
"plugins list --server.subscriptions": "moved to --subscriptions.enabled",
"serve --transactions.mutations": "removed: mutations always run in a transaction",
} {
cmd := rootCmd()
cmd.SetArgs(strings.Fields(args))
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
err := cmd.Execute()
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("%s: err = %v, want %q", args, err, want)
}
}
}
6 changes: 5 additions & 1 deletion docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,14 @@ Run `pdbq completion <shell> --help` for per-shell install notes.
```console
$ pdbq plugins list
smart_comments priority=50 enabled hooks: catalog, inflection, schema
simple_names priority=100 enabled hooks: catalog, inflection
simple_names priority=100 disabled hooks: catalog, inflection
advanced_filters priority=150 enabled hooks: schema
postgis priority=160 enabled hooks: schema
contrib priority=170 enabled hooks: schema
aggregates priority=180 enabled hooks: schema
nested_mutations priority=200 enabled hooks: schema, compile
```

The status is the effective state: `disabled` for a plugin named in
`plugins.disabled`, and for `simple_names` until
`plugins.settings.simple_names.enabled` is `true`.
2 changes: 1 addition & 1 deletion docs/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ WebSocket close codes, not GraphQL errors (`4400`, `4401`, `4403`, `4406`,
| `method_not_allowed` | 405 + `Allow` | a mutation or subscription over `GET` / `HEAD`; a method no route of that path serves |
| `unsupported_media_type` | 415 | `POST` without `Content-Type: application/json` |
| `not_acceptable` | 406 | `Accept: multipart/mixed` naming only a `deferSpec` / `incrementalSpec` pdbq does not serve |
| `body_too_large` | 413 | request body larger than `limits.max_body_bytes` |
| `body_too_large` | 413 | request body larger than `limits.max_body_bytes` (checked before the body is parsed, so a non-JSON body gets it too), or a GET query string longer than it |
| `persisted_query_not_found` | 200 | a hash-only request whose hash is not registered; message `PersistedQueryNotFound`, so Apollo clients resend with the query |
| `persisted_query_not_supported` | 200 for a hash-only request; 400 for a registration | a hash-only request while persisted queries are off (message `PersistedQueryNotSupported`, so Apollo clients stop sending hashes); a query sent with its hash to register it while `persisted_queries.apq` is off |
| `persisted_query_required` | 400 | `persisted_queries.only` and the request has no `persistedQuery` extension |
Expand Down
5 changes: 3 additions & 2 deletions docs/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,8 @@ variables `PDBQ_SERVER_MAX__COST ... moved to PDBQ_LIMITS_MAX__COST`).
`subscriptions`, `live`, `incremental` and `server.document_cache`; see
the table below and [Configuration](configuration.md). Flags follow the
keys (`--limits.max_cost`, `--subscriptions.enabled`, …); an old flag is
only rejected as `unknown flag` without a suggestion, so use the table.
rejected like an old key and names its replacement
(`unknown flag: --server.max_cost: moved to --limits.max_cost`).
- **`server.introspection: true` replaces `server.disable_introspection`
and `server.expose_schema`.** The polarity is inverted
(`disable_introspection: true` is `introspection: false`), and the SDL at
Expand Down Expand Up @@ -397,7 +398,7 @@ messages are unchanged except where the table says so.
| `server.request_timeout` elapsed: `503`, `{"errors":[{"message":"request timeout"}]}` without a JSON content type | `504`, `Content-Type: application/json`, `{"errors":[{"message":"request timeout","extensions":{"code":"timeout"}}]}` |
| role claim outside `roles.allowed` or never assumable: `401` | `403`, code `role_not_allowed` (same `WWW-Authenticate: Bearer error="insufficient_scope"`) |
| missing / invalid credentials: `401` without a code | `401`, code `auth_required` / `invalid_token` |
| body above `limits.max_body_bytes`: `400 malformed request body` | `413`, code `body_too_large` |
| body above `limits.max_body_bytes`: `400 malformed request body` | `413`, code `body_too_large`, also for a body that is not JSON |
| APQ miss: code `PERSISTED_QUERY_NOT_FOUND` | code `persisted_query_not_found` (message `PersistedQueryNotFound` kept) |
| hash-only request with persisted queries off: `400 missing query` | `200`, message `PersistedQueryNotSupported`, code `persisted_query_not_supported` |
| `persisted_queries.only` without a hash; registration with `apq` off | same `400`s, codes `persisted_query_required` / `persisted_query_not_supported` |
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,5 @@ require (
require (
github.com/coder/websocket v1.8.15
github.com/prometheus/client_golang v1.25.0
github.com/suprbdev/pdbcore v0.19.0
github.com/suprbdev/pdbcore v0.19.1
)
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/suprbdev/pdbcore v0.19.0 h1:0j+vkzyt1bKcREPh6OUT9vX69dzL5QMzAAJvd1Ck+KM=
github.com/suprbdev/pdbcore v0.19.0/go.mod h1:loM9g7/i1GhIY4CRmHeAiMucJ57nxTgxN0YNHc7tW7w=
github.com/suprbdev/pdbcore v0.19.1 h1:vTl8odNVm2Gi5nU+hsDr4rvY22cozzz0cKLPRp758dg=
github.com/suprbdev/pdbcore v0.19.1/go.mod h1:loM9g7/i1GhIY4CRmHeAiMucJ57nxTgxN0YNHc7tW7w=
github.com/vektah/gqlparser/v2 v2.5.36 h1:CN9mKVHgMkc+XftdOWIhb4HEL8wKSYkFAqhf8booa7s=
github.com/vektah/gqlparser/v2 v2.5.36/go.mod h1:cAJ9qwVgPaUkWv6Gn8vn0mqOE0Ui5Pn56wNy5396XWo=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
Expand Down
19 changes: 19 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (

"github.com/suprbdev/pdbcore/auth"
"github.com/suprbdev/pdbcore/confx"
"github.com/suprbdev/pdbcore/confx/cliflags"
pgcontrib "github.com/suprbdev/pdbcore/contrib"
"github.com/suprbdev/pdbq/internal/live"
"github.com/suprbdev/pdbq/internal/plugins/advancedfilters"
Expand Down Expand Up @@ -362,6 +363,14 @@ var RemovedKeys = map[string]string{
"plugins.settings.nested_mutations.force_transactions": "nested mutations always run in a transaction",
}

// ExplainFlagError adds the moved-to or removed hint to the error of an
// unknown flag that names an old config key (--rls.enabled), as loading the
// key from a file or PDBQ_* variable does.
func ExplainFlagError(err error) error {
cfg := DefaultConfig()
return cliflags.Explain(err, &cfg, confx.WithMoved(MovedKeys), confx.WithRemoved(RemovedKeys))
}

// Load builds the effective config: defaults, then optional YAML file, then
// PDBQ_* env vars, then flags (highest precedence: koanf path to value,
// see confx.WithFlags), and validates it. Pass only the flags the user set
Expand Down Expand Up @@ -501,6 +510,16 @@ var reservedPaths = map[string]bool{"/graphql": true, "/healthz": true, "/readyz
// DisabledPlugins returns the disabled-plugin set for registry filtering.
func (c *Config) DisabledPlugins() map[string]bool { return c.Plugins.DisabledSet() }

// PluginEnabled reports whether the named plugin takes part in the schema:
// it is not listed in plugins.disabled and, for simple_names, which is inert
// until plugins.settings.simple_names.enabled is set, that setting is on.
func (c *Config) PluginEnabled(name string) bool {
if c.DisabledPlugins()[name] {
return false
}
return name != simplenames.Name || c.Plugins.Settings.SimpleNames.Enabled
}

func validateIncremental(in Incremental, maxConns int32) []string {
var errs []string
if in.MaxDeferred < 1 {
Expand Down
15 changes: 15 additions & 0 deletions internal/config/load_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,21 @@ func TestPluginsDisabledNames(t *testing.T) {
}
}

func TestPluginEnabledReflectsSettings(t *testing.T) {
cfg := DefaultConfig()
if cfg.PluginEnabled("simple_names") || !cfg.PluginEnabled("advanced_filters") {
t.Errorf("defaults: simple_names %v, advanced_filters %v", cfg.PluginEnabled("simple_names"), cfg.PluginEnabled("advanced_filters"))
}
cfg.Plugins.Settings.SimpleNames.Enabled = true
if !cfg.PluginEnabled("simple_names") {
t.Error("simple_names enabled by its setting reads disabled")
}
cfg.Plugins.Disabled = []string{"simple_names", "postgis"}
if cfg.PluginEnabled("simple_names") || cfg.PluginEnabled("postgis") {
t.Error("plugins.disabled ignored")
}
}

func TestLogFormatValidated(t *testing.T) {
wantLoadError(t, writeConfig(t, "auth:\n jwt:\n secret: s\nlog:\n format: logfmt\n"), `log.format: "logfmt" is not 'text' or 'json'`)
}
Expand Down
3 changes: 3 additions & 0 deletions internal/server/codes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ func TestHTTPErrorCodes(t *testing.T) {
}{
{"malformed body", plain, jsonRequest(`{`), http.StatusBadRequest, errcode.InvalidRequest, ""},
{"too large", plain, jsonRequest(`{"query":"` + strings.Repeat(" ", 300) + `"}`), http.StatusRequestEntityTooLarge, errcode.BodyTooLarge, ""},
{"too large not JSON", plain, jsonRequest(strings.Repeat("x", 300)), http.StatusRequestEntityTooLarge, errcode.BodyTooLarge, ""},
{"too large malformed JSON", plain, jsonRequest(`{` + strings.Repeat(" ", 300)), http.StatusRequestEntityTooLarge, errcode.BodyTooLarge, ""},
{"too large query string", plain, httptest.NewRequest("GET", "/graphql?query="+strings.Repeat("a", 300), nil), http.StatusRequestEntityTooLarge, errcode.BodyTooLarge, ""},
{"missing query", plain, jsonRequest(`{}`), http.StatusBadRequest, errcode.InvalidRequest, "missing query"},
{"media type", plain, httptest.NewRequest("POST", "/graphql", strings.NewReader(`{}`)), http.StatusUnsupportedMediaType, errcode.UnsupportedMediaType, ""},
{"malformed variables", plain, httptest.NewRequest("GET", "/graphql?query=%7B__typename%7D&variables=%7B", nil), http.StatusBadRequest, errcode.InvalidRequest, ""},
Expand Down
13 changes: 12 additions & 1 deletion internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
package server

import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"mime"
"net/http"
Expand Down Expand Up @@ -332,6 +334,10 @@ func (s *Server) handleGraphQL(w http.ResponseWriter, r *http.Request) {
var req gqlHTTPRequest
switch r.Method {
case http.MethodGet, http.MethodHead:
if limit := s.cfg.Limits.MaxBodyBytes; int64(len(r.URL.RawQuery)) > limit {
writeError(w, http.StatusRequestEntityTooLarge, errcode.BodyTooLarge, fmt.Sprintf("request query string exceeds %d bytes", limit))
return
}
req.Query = r.URL.Query().Get("query")
req.OperationName = r.URL.Query().Get("operationName")
if vars := r.URL.Query().Get("variables"); vars != "" {
Expand All @@ -349,14 +355,19 @@ func (s *Server) handleGraphQL(w http.ResponseWriter, r *http.Request) {
return
}
body := http.MaxBytesReader(w, r.Body, s.cfg.Limits.MaxBodyBytes)
if err := json.NewDecoder(body).Decode(&req); err != nil {
raw, err := io.ReadAll(body)
if err != nil {
if mbe := (*http.MaxBytesError)(nil); errors.As(err, &mbe) {
writeError(w, http.StatusRequestEntityTooLarge, errcode.BodyTooLarge, fmt.Sprintf("request body exceeds %d bytes", mbe.Limit))
return
}
writeError(w, http.StatusBadRequest, errcode.InvalidRequest, "malformed request body")
return
}
if err := json.NewDecoder(bytes.NewReader(raw)).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, errcode.InvalidRequest, "malformed request body")
return
}
}
if handled := s.resolvePersisted(w, &req); handled {
return
Expand Down
1 change: 1 addition & 0 deletions test/errors_e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ func TestErrorCodesE2E(t *testing.T) {
{"unsupported_media_type", plain, rawRequest(http.MethodPost, "/graphql", "text/plain", gqlQuery(`{ __typename }`)), 415, "unsupported_media_type", ""},
{"not_acceptable", plain, rawPost(gqlQuery(`{ __typename }`), "Accept", "multipart/mixed;deferSpec=1999"), 406, "not_acceptable", ""},
{"body_too_large", plain, rawPost(gqlQuery(`{ __typename }` + strings.Repeat(" ", 5000))), 413, "body_too_large", ""},
{"body_too_large not JSON", plain, rawPost(strings.Repeat("x", 5000)), 413, "body_too_large", ""},
{"persisted_query_not_supported", plain, rawPost(hashOnly), 200, "persisted_query_not_supported", "PersistedQueryNotSupported"},
{"persisted_query_not_found", apq, rawPost(hashOnly), 200, "persisted_query_not_found", "PersistedQueryNotFound"},
{"persisted_query_required", locked, post200(`{ __typename }`), 400, "persisted_query_required", ""},
Expand Down
Loading