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
22 changes: 15 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ GraphQL); the shared half lives in
[pdbcore](docs/pdbcore.md).

```console
$ pdbr serve --database.url postgres://localhost/mydb
$ pdbr serve --database.url postgres://localhost/mydb --auth.mode none --roles.switch=false
time=... msg=introspected tables=12 enums=3 functions=2 took=38ms
time=... msg=listening addr=:8080 base_path=/api openapi=true
$ curl 'localhost:8080/api/users?select=id,email,posts(title)&mood=eq.happy&limit=2'
Expand All @@ -32,9 +32,11 @@ $ curl 'localhost:8080/api/users?select=id,email,posts(title)&mood=eq.happy&limi
`limit`/`offset`, keyset `after=`/`before=` cursors, `count=true`,
`distinct=`, `/by/{cols}/{vals}` unique lookups, `/rpc/{fn}`.
- **RLS-aware by default** — each request runs with `SET LOCAL ROLE` and
claims exposed via `set_config('pdbq.claims.*', ...)` from a verified JWT or
trusted gateway headers. The claims prefix is deliberately shared with pdbq
so existing policies work unchanged.
claims exposed via `set_config('jwt.claims.*', ...)` (and optionally as
one JSON object such as PostgREST's `request.jwt.claims`) from a verified
JWT or trusted gateway headers; requests without credentials are refused
unless an anonymous role is configured. The claim settings are shared
with pdbq and PostGraphile so existing policies work unchanged.
- **Filters with an indexed-only policy** — only indexed columns are
filterable/orderable out of the box (`filters.indexed_only: false` opens it
up), with per-type operator sets and `@filterable` smart-comment opt-in.
Expand All @@ -51,8 +53,8 @@ $ curl 'localhost:8080/api/users?select=id,email,posts(title)&mood=eq.happy&limi
- **Watch mode** — a DDL event trigger (or poll fallback) re-introspects and
atomically swaps the API during development.
- **Plugins** — five small hook interfaces (catalog, inflection, API,
compile, request) with four built-ins: `smart-comments`, `advanced-filters`,
`postgis`, `nested-mutations`.
compile, request) with four built-ins: `smart_comments`, `advanced_filters`,
`postgis`, `nested_mutations`.
- **Schema contracts** — per-audience APIs (`public`, `partner`,
`internal`) selected by `@contract` / `@behavior ±contract:<name>` smart
comments, each under its own base path with its own OpenAPI document, see
Expand Down Expand Up @@ -95,10 +97,15 @@ $ curl localhost:8080/api/openapi.json | jq .paths | head
Or against your own database:

```console
$ pdbr config init # writes a starter pdbr.yaml
$ pdbr config init # writes a starter pdbr.yaml: no auth, connection role
$ pdbr serve
```

The starter (and the first example above) run without authentication as the
connection role; configure `auth` and `roles` before production
([docs/rls.md](docs/rls.md)). The defaults verify JWTs and refuse requests
without credentials.

See [docs/quickstart.md](docs/quickstart.md) for the full tour.

## Documentation
Expand All @@ -116,6 +123,7 @@ See [docs/quickstart.md](docs/quickstart.md) for the full tour.
| [docs/errors.md](docs/errors.md) | Problem Details format, `code` catalogue, status mapping |
| [docs/openapi.md](docs/openapi.md) | What the generated OpenAPI 3.1 document contains |
| [docs/configuration.md](docs/configuration.md) | Config layering; full reference in `examples/pdbr.example.yaml` |
| [docs/upgrading.md](docs/upgrading.md) | Breaking changes and config migration between releases |
| [docs/cli.md](docs/cli.md) | All subcommands, scripting patterns |
| [docs/rls.md](docs/rls.md) | Roles, JWT/header claims, policies |
| [docs/smart-comments.md](docs/smart-comments.md) | `@omit`/`@name`/`@foreignKey`/… tags with REST semantics |
Expand Down
69 changes: 38 additions & 31 deletions cmd/pdbr/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"syscall"

"github.com/spf13/cobra"
"github.com/spf13/pflag"

"github.com/suprbdev/pdbcore/cache"
"github.com/suprbdev/pdbcore/confx"
Expand Down Expand Up @@ -63,7 +64,9 @@ func configFlags(cmd *cobra.Command) {
fs.StringSlice("schema.schemas", nil, "PostgreSQL schemas to expose")
fs.String("schema.cache_path", "", "boot from schema cache file")
fs.Bool("schema.expose_partitions", false, "expose table partitions as resources of their own")
fs.Bool("rls.enabled", true, "enable RLS role switching")
fs.String("auth.mode", "", "credential source: jwt|headers|none")
fs.Bool("roles.switch", true, "run each request as its resolved role (SET LOCAL ROLE)")
fs.String("roles.anonymous", "", "role of requests without credentials (empty answers them 401)")
fs.Bool("watch.enabled", false, "watch for DDL changes (dev)")
fs.Bool("filters.indexed_only", true, "only indexed columns filterable")
fs.String("errors.detail", "", "error verbosity: dev|prod|strict")
Expand All @@ -72,6 +75,7 @@ func configFlags(cmd *cobra.Command) {
fs.String("metrics.path", "", "URL path of the metrics endpoint (default /metrics)")
fs.String("metrics.addr", "", "separate listen address for the metrics endpoint, e.g. :9090")
registerEnumCompletion(cmd, "server.tx_end", "commit", "commit-allow-override", "rollback", "rollback-allow-override")
registerEnumCompletion(cmd, "auth.mode", "jwt", "headers", "none")
registerEnumCompletion(cmd, "errors.detail", "dev", "prod", "strict")
registerEnumCompletion(cmd, "log.level", "debug", "info", "warn", "error")
}
Expand All @@ -89,18 +93,40 @@ func loadConfig(cmd *cobra.Command) (config.Config, error) {
}

// loadConfigRaw loads defaults < file < env < flags without validating, for
// commands that adjust the config before validation (pdbr request forces
// rls.auth.mode=none, so a missing jwt_secret must not stop it).
// commands that adjust the config before validation.
func loadConfigRaw(cmd *cobra.Command) (config.Config, error) {
path, _ := cmd.Flags().GetString("config")
if path == "" {
path = confx.Discover("pdbr.yaml", "pdbr.yml")
}
cfg := config.DefaultConfig()
if err := confx.Load(config.EnvPrefix, path, confx.ChangedFlags(cmd.Flags(), "config"), &cfg); err != nil {
return config.LoadUnvalidated(path, changedConfigFlags(cmd))
}

// changedConfigFlags returns the config flags set on cmd's command line:
// the flags named after a config path (configFlags), leaving out --config
// and command options such as --cache or --print-sql, which strict loading
// would reject as unknown keys.
func changedConfigFlags(cmd *cobra.Command) *pflag.FlagSet {
var local []string
cmd.Flags().VisitAll(func(f *pflag.Flag) {
if !strings.Contains(f.Name, ".") {
local = append(local, f.Name)
}
})
return confx.ChangedFlags(cmd.Flags(), local...)
}

// loadConnectionConfig loads the config of a command that serves no HTTP
// clients (request, schema dump/check, plugins list): it runs as the
// connection role without credentials (config.UseConnectionIdentity) and is
// then validated, so it works on a default config without a JWT secret.
func loadConnectionConfig(cmd *cobra.Command) (config.Config, error) {
cfg, err := loadConfigRaw(cmd)
if err != nil {
return cfg, err
}
return cfg, nil
cfg.UseConnectionIdentity()
return cfg, cfg.Validate()
}

func newApp(cfg config.Config) *pdbr.App {
Expand Down Expand Up @@ -152,15 +178,10 @@ func requestCmd() *cobra.Command {
Short: "Run a one-off request through the real handler (body to stdout, status to stderr)",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := loadConfigRaw(cmd)
cfg, err := loadConnectionConfig(cmd)
if err != nil {
return err
}
// One-off CLI requests run without HTTP auth: no role switch.
cfg.RLS.Auth.Mode = "none"
if err := cfg.Validate(); err != nil {
return err
}
if accept != "" {
headers = append(headers, "Accept: "+accept)
}
Expand All @@ -187,7 +208,7 @@ func schemaCmd() *cobra.Command {
Use: "dump",
Short: "Introspect the database and write a schema cache file",
RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := loadConfig(cmd)
cfg, err := loadConnectionConfig(cmd)
if err != nil {
return err
}
Expand All @@ -214,7 +235,7 @@ func schemaCmd() *cobra.Command {
Use: "check",
Short: "Compare the live database schema against a cache file (exit 1 on drift)",
RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := loadConfig(cmd)
cfg, err := loadConnectionConfig(cmd)
if err != nil {
return err
}
Expand Down Expand Up @@ -320,19 +341,7 @@ func configCmd() *cobra.Command {
if _, err := os.Stat(path); err == nil {
return fmt.Errorf("%s already exists", path)
}
starter := `# pdbr configuration. Run "pdbr config example" for the full annotated reference.
database:
# Fill in real credentials, or delete the url and set PDBR_DATABASE_URL.
url: "postgres://USER:PASSWORD@HOST:5432/DB"
server:
addr: ":8080"
base_path: "/api"
schema:
schemas: ["public"]
rls:
enabled: false # enable + configure auth before production use
`
if err := os.WriteFile(path, []byte(starter), 0o644); err != nil {
if err := os.WriteFile(path, []byte(config.Starter), 0o644); err != nil {
return err
}
fmt.Println("wrote", path)
Expand Down Expand Up @@ -371,11 +380,9 @@ func pluginsCmd() *cobra.Command {
Use: "list",
Short: "List registered plugins and the hooks they implement",
RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := loadConfig(cmd)
cfg, err := loadConnectionConfig(cmd)
if err != nil {
// plugins list should work without a valid DB config
cfg = config.DefaultConfig()
cfg.RLS.Enabled = false
return err
}
app := newApp(cfg)
disabled := cfg.DisabledPlugins()
Expand Down
27 changes: 25 additions & 2 deletions cmd/pdbr/request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,7 @@ func TestPrintSQLMatchesGolden(t *testing.T) {
cfg := config.DefaultConfig()
cfg.Database.URL = "postgres://nobody@127.0.0.1:1/none"
cfg.Schema.CachePath = cachePath
cfg.RLS.Enabled = false
cfg.RLS.Auth.Mode = "none"
cfg.UseConnectionIdentity()
if err := cfg.Validate(); err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -135,3 +134,27 @@ func TestFlagValueCompletion(t *testing.T) {
t.Errorf("completion zsh: %v %q", err, out.String()[:min(len(out.String()), 40)])
}
}

// TestCommandsRunOnDefaultConfig: pdbr request and pdbr plugins list need
// no JWT secret (they run as the connection role without credentials), and
// command options such as --print-sql are not taken for config keys.
func TestCommandsRunOnDefaultConfig(t *testing.T) {
t.Chdir(t.TempDir())
cachePath := filepath.Join(t.TempDir(), "schema.cache")
if err := cache.Save(cachePath, testutil.FixtureCatalog(), cache.Writer{Product: "pdbr", Version: "test"}); err != nil {
t.Fatal(err)
}
out, err := runCLI(t, "request", "GET", "/users?select=id", "--print-sql", "--schema.cache_path", cachePath, "--log.level", "error")
if err != nil || !strings.Contains(out, "-- request: GET /api/users?select=id") {
t.Fatalf("request --print-sql on defaults: %v\n%s", err, out)
}
if _, err := runCLI(t, "plugins", "list"); err != nil {
t.Fatalf("plugins list on defaults: %v", err)
}
if _, err := runCLI(t, "config", "validate"); err == nil || !strings.Contains(err.Error(), "auth.jwt.secret") {
t.Fatalf("config validate on defaults = %v, want the missing secret", err)
}
if _, err := runCLI(t, "request", "GET", "/users", "--rls.enabled=false"); err == nil || !strings.Contains(err.Error(), "unknown flag: --rls.enabled") {
t.Fatalf("removed flag: %v", err)
}
}
4 changes: 2 additions & 2 deletions cmd/pdbr/schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func TestSchemaCheckRejectsBadCacheBeforeConnecting(t *testing.T) {
dir := t.TempDir()
// database.url points nowhere: every case below must fail on the cache
// file, never by trying to reach the database.
base := []string{"schema", "check", "--database.url", "postgres://nobody:x@127.0.0.1:1/none", "--rls.enabled=false"}
base := []string{"schema", "check", "--database.url", "postgres://nobody:x@127.0.0.1:1/none"}

_, err := runCLI(t, append(base, "--cache", filepath.Join(dir, "missing.cache"))...)
if err == nil || !strings.Contains(err.Error(), "cache: open") {
Expand Down Expand Up @@ -108,7 +108,7 @@ func TestSchemaDumpCheckLive(t *testing.T) {
t.Cleanup(dropProbe)

path := filepath.Join(t.TempDir(), "schema.cache")
flags := []string{"--database.url", dbURL, "--rls.enabled=false"}
flags := []string{"--database.url", dbURL, "--auth.mode=none", "--roles.switch=false"}
out, err := runCLI(t, append([]string{"schema", "dump", "-o", path}, flags...)...)
if err != nil || !strings.HasPrefix(out, "wrote "+path) {
t.Fatalf("dump: %v %q", err, out)
Expand Down
3 changes: 2 additions & 1 deletion compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ services:
environment:
PDBR_DATABASE_URL: postgres://pdbr:pdbr@db:5432/pdbr
PDBR_WATCH_ENABLED: "true"
PDBR_RLS_ENABLED: "false" # dev stack; see docs/rls.md for production
PDBR_AUTH_MODE: none # dev stack; see docs/rls.md for production
PDBR_ROLES_SWITCH: "false"
PDBR_ERRORS_DETAIL: dev
PDBR_LOG_LEVEL: debug
4 changes: 2 additions & 2 deletions contracts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func contractCatalog(t *testing.T) *introspect.Catalog {

func contractConfig() config.Config {
cfg := config.DefaultConfig()
cfg.RLS.Enabled = false
cfg.UseConnectionIdentity()
cfg.Contracts = []confx.Contract{{Name: "internal"}, {Name: "public"}, {Name: "partner", Default: "exclude", Path: "/partners"}}
return cfg
}
Expand Down Expand Up @@ -138,7 +138,7 @@ func TestContractFullAPIUnchanged(t *testing.T) {
ctx := context.Background()
quiet := WithLogger(slog.New(slog.NewTextHandler(io.Discard, nil)))
plain := config.DefaultConfig()
plain.RLS.Enabled = false
plain.UseConnectionIdentity()
want, err := New(plain, quiet).BuildAPI(ctx, contractCatalog(t))
if err != nil {
t.Fatal(err)
Expand Down
8 changes: 4 additions & 4 deletions db/init/01-schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down
10 changes: 5 additions & 5 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ POST /api/rpc/search_posts {"q": "hello"}
<table>` → array with full `select=` (embeds included), filters, `order=`,
`limit`/`offset`, `count=true` and CSV — offset paging only, no cursors;
`SETOF <scalar>` → array of values. A function returning the
`rls.auth.jwt_type` composite returns a minted HS256 JWT string.
`auth.mint_type` composite returns a minted HS256 JWT string.
- Not exposed: functions without EXECUTE privilege, extension-owned, unnamed
args, `OUT`/`INOUT`/`VARIADIC`, trigger/internal returns. Overloads →
keep-first + warning. `schema.functions: false` removes RPC and computed
Expand All @@ -438,16 +438,16 @@ POST /api/rpc/search_posts {"q": "hello"}
- `select=` applies to mutation responses (compiled against the `__mut` CTE,
embeds work; `RETURNING` lists only referenced columns).
- Nested writes on `POST` and single-row `PATCH` (plugin
`nested-mutations`): forward key → `{"create": {…}}` or `{"connect":
`nested_mutations`): forward key → `{"create": {…}}` or `{"connect":
{<key cols>}}` (exactly one on `POST`; the key is the referenced columns,
the primary key or one unique constraint — `{"email": "…"}` connects a
user), on `PATCH` also `{"disconnect": true}`, `{"update": {…}}`,
`{"delete": true}`; backward key → lists under `create` and `connect`,
on `PATCH` also `update` (`[{"where": {…}, "data": {…}}]`), `delete`,
`disconnect`; depth ≤ 3 (`plugins.settings.nested-mutations.max_depth`);
`disconnect`; depth ≤ 3 (`plugins.settings.nested_mutations.max_depth`);
FK columns become optional when nested input is provided; a nested
lookup that matches nothing is `404` and rolls the request back
([mutations.md](mutations.md#nested-mutations-plugin-nested-mutations)).
([mutations.md](mutations.md#nested-mutations-plugin-nested_mutations)).

## Content negotiation

Expand Down Expand Up @@ -567,7 +567,7 @@ Cursor and `Link` details: [pagination.md](pagination.md).
| request cost | `server.max_cost` (100000) | `400 cost_exceeded` |
| body size | `server.max_body_bytes` (1 MiB) | `413` |
| request time | `server.request_timeout` (30s) | `504` |
| statement time | `database.statement_timeout` (30s) | `504` |
| statement time | `database.statement_timeout` (25s) | `504` |

Errors are RFC 9457 problem documents (`application/problem+json`) with a
stable `code` extension:
Expand Down
Loading
Loading