From 95b052fa653a621161362ea3cc9afa9f5b413abc Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 24 Nov 2026 07:30:40 -0600 Subject: [PATCH] id-pg: Postgres-over-HTTP (PostgREST) query translator with allowlist (#13760) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New crate pkgs/id/crates/id-pg implementing section 3 of the #5805 design: the data-shaped query object, the owner collection allowlist, and the pure translator to a PostgREST request — or a refusal by the section 3.2 stable feature name, always before any network call. Keyset pagination is generated as the lexicographic or-group over the effective ordering (declared keys plus the unique-key tiebreak), so the pagination key is total by construction. Tests (design section 10): property tests over the query object (allowlist conformance, total pagination key, determinism) and model tests over the section 3.2 refusal table, including byte-identical bodies for undeclared vs withheld columns (section 6.2). cargo test -p id-pg: 22 passed. Book (book-live-update): ID book crate counts re-derived from Cargo.toml (19 crates / 20 members / 17 default packages) in the layout, crates, architecture, and shape chapters; id-pg roster entries added, plus the missing id-client and id-tui-shell rows from their own Cargo.toml descriptions. Refs #13760 --- pkgs/id/Cargo.lock | 8 + pkgs/id/Cargo.toml | 2 + pkgs/id/book/concepts/architecture.md | 2 +- pkgs/id/book/development/layout.md | 9 +- pkgs/id/book/getting-started/shape.md | 16 +- pkgs/id/book/library/crates.md | 12 +- pkgs/id/crates/id-pg/Cargo.toml | 96 ++++ pkgs/id/crates/id-pg/src/allowlist.rs | 84 ++++ pkgs/id/crates/id-pg/src/lib.rs | 63 +++ pkgs/id/crates/id-pg/src/query.rs | 252 ++++++++++ pkgs/id/crates/id-pg/src/refusal.rs | 142 ++++++ pkgs/id/crates/id-pg/src/translate.rs | 431 ++++++++++++++++++ pkgs/id/crates/id-pg/src/value.rs | 73 +++ .../id-pg/tests/property.proptest-regressions | 7 + pkgs/id/crates/id-pg/tests/property.rs | 319 +++++++++++++ pkgs/id/crates/id-pg/tests/refusal_table.rs | 306 +++++++++++++ 16 files changed, 1807 insertions(+), 15 deletions(-) create mode 100644 pkgs/id/crates/id-pg/Cargo.toml create mode 100644 pkgs/id/crates/id-pg/src/allowlist.rs create mode 100644 pkgs/id/crates/id-pg/src/lib.rs create mode 100644 pkgs/id/crates/id-pg/src/query.rs create mode 100644 pkgs/id/crates/id-pg/src/refusal.rs create mode 100644 pkgs/id/crates/id-pg/src/translate.rs create mode 100644 pkgs/id/crates/id-pg/src/value.rs create mode 100644 pkgs/id/crates/id-pg/tests/property.proptest-regressions create mode 100644 pkgs/id/crates/id-pg/tests/property.rs create mode 100644 pkgs/id/crates/id-pg/tests/refusal_table.rs diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index 7da15b5441..8e63cb117b 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -5164,6 +5164,14 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "id-pg" +version = "0.1.0" +dependencies = [ + "proptest", + "serde", +] + [[package]] name = "id-render" version = "0.1.0" diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index 83751be658..a6fd623680 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -35,6 +35,7 @@ members = [ "crates/id-cli", "crates/id-import-notion", "crates/id-client", + "crates/id-pg", ] # The vendored crates stay OUT of the workspace: as path dependencies inside # this directory Cargo would otherwise treat them as members, and a member's @@ -58,6 +59,7 @@ default-members = [ "crates/id-render", "crates/id-cli", "crates/id-import-notion", + "crates/id-pg", "crates/id-client", ] diff --git a/pkgs/id/book/concepts/architecture.md b/pkgs/id/book/concepts/architecture.md index 69b0c6bf0d..236aad24f1 100644 --- a/pkgs/id/book/concepts/architecture.md +++ b/pkgs/id/book/concepts/architecture.md @@ -4,7 +4,7 @@ Source: this chapter rests on the library survey (`survey/library.md`, the crate ## One workspace, one public surface -The system lives in `pkgs/id/` in the `developing-today/code` repository. The root `Cargo.toml` is two things at once: the package `id` at version `0.1.0` (edition 2024, rust-version 1.96) and the workspace root. The workspace has 17 members: the root package plus 16 crates under `pkgs/id/crates/`. Default members are 15: the root plus 14 crates. `id-native-shell` and `id-hw-shell` are members but not default members, so a plain `cargo build` in `pkgs/id/` never acquires the Bevy desktop dependencies or the hardware-shell code. +The system lives in `pkgs/id/` in the `developing-today/code` repository. The root `Cargo.toml` is two things at once: the package `id` at version `0.1.0` (edition 2024, rust-version 1.96) and the workspace root. The workspace has 20 members: the root package plus 19 crates under `pkgs/id/crates/`. Default members are 17: the root plus 16 crates. `id-native-shell`, `id-hw-shell`, and `id-tui-shell` are members but not default members, so a plain `cargo build` in `pkgs/id/` never acquires the Bevy desktop dependencies or the shell code. Library consumers use one public surface: the root crate, imported as `id::`. The split crates are internal. A consumer who names a split crate directly uses an internal path, with two recorded exceptions: `id-config`, `id-currency-registry`, `id-render` and `id-import-notion` are not exposed at `id::` at all, so a consumer who wants them names those crates directly (library survey §2). diff --git a/pkgs/id/book/development/layout.md b/pkgs/id/book/development/layout.md index f6ed425873..e4413dda16 100644 --- a/pkgs/id/book/development/layout.md +++ b/pkgs/id/book/development/layout.md @@ -18,9 +18,9 @@ ID lives in the `developing-today/code` monorepo, in the directory `pkgs/id/`. T There is no `src/bin/` directory and no `[[bin]]` section in any workspace `Cargo.toml`. The two binaries exist by Cargo's implicit `src/main.rs` rule: `id` from the root package, and `id-native-shell` from `crates/id-native-shell/src/main.rs`. -## The 16 crates +## The 19 crates -`crates/` holds the 16 sub-crates. The workspace has 17 members in total: the root plus these 16. `default-members` lists 15 packages — the root plus 14 crates. `id-native-shell` and `id-hw-shell` are members but not default members, so a plain `cargo build` in `pkgs/id/` never builds the desktop shell or the hardware shell. +`crates/` holds the 19 sub-crates. The workspace has 20 members in total: the root plus these 19. `default-members` lists 17 packages — the root plus 16 crates. `id-native-shell`, `id-hw-shell`, and `id-tui-shell` are members but not default members, so a plain `cargo build` in `pkgs/id/` never builds the shell crates. | Crate | Role in one line | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | @@ -38,10 +38,13 @@ There is no `src/bin/` directory and no `[[bin]]` section in any workspace `Carg | `id-currency-registry` | Currency control-plane registry: the ledger allocator, the account factory and the Postgres schema and migrations. | | `id-render` | Rendering pipeline compiler core: parse and vocabulary validation of semantic markup. No dependents. | | `id-import-notion` | Notion importer manifest and inventory primitives. No dependents. | +| `id-client` | Client-only Rust facade for the id native Android client v1 (slice 1 of #7938, #13403). | +| `id-pg` | Postgres-over-HTTP adapter (#5805): the PostgREST query translator and collection allowlist (design §3), slice #13760. No dependents yet. | | `id-native-shell` | The Bevy native reference shell. Not a default member. | | `id-hw-shell` | The ESP32-class hardware shell spike: one file, `src/lib.rs`, frame builders only, no binary. Not a default member. | +| `id-tui-shell` | The terminal (TUI) shell: the text-native world-session client on the F13.1 shell contract (#12818). Not a default member. | -Dependency direction runs downward to `id-core`. Nothing in the split family depends on the facade in production code; the two shells depend on the facade, and `id-store` dev-depends on it for tests. The full per-crate surface is [The crates](../library/crates.md). +Dependency direction runs downward to `id-core`. Nothing in the split family depends on the facade in production code; the two original shells depend on the facade, and `id-store` dev-depends on it for tests. The full per-crate surface is [The crates](../library/crates.md). Two directories sit outside the workspace: `vendor/p2panda-sync` and `vendor/p2panda-encryption` are listed in the workspace `exclude` array and are consumed as path dependencies only. diff --git a/pkgs/id/book/getting-started/shape.md b/pkgs/id/book/getting-started/shape.md index b8d8002b7b..c5548ca72c 100644 --- a/pkgs/id/book/getting-started/shape.md +++ b/pkgs/id/book/getting-started/shape.md @@ -4,14 +4,14 @@ This chapter is the whole system on one page: the crates, the surfaces, how a file moves, how a world runs, and where data lives. Every other part of this book expands one section of this page. -## The workspace: a facade plus 16 crates - -`pkgs/id/` is a Rust workspace of 17 packages: the root package `id` -version `0.1.0` (the facade) and 16 crates under `pkgs/id/crates/`. -Default members are 15 packages: the root plus 14 crates. The two shell -crates, `id-native-shell` and `id-hw-shell`, are workspace members but -not default members, so a plain `cargo build` in `pkgs/id/` never -acquires the Bevy desktop or hardware-shell dependencies. Two vendored +## The workspace: a facade plus 19 crates + +`pkgs/id/` is a Rust workspace of 20 packages: the root package `id` +version `0.1.0` (the facade) and 19 crates under `pkgs/id/crates/`. +Default members are 17 packages: the root plus 16 crates. The three +shell crates, `id-native-shell`, `id-hw-shell`, and `id-tui-shell`, are +workspace members but not default members, so a plain `cargo build` in +`pkgs/id/` never acquires the Bevy desktop or shell dependencies. Two vendored crates, `vendor/p2panda-sync` and `vendor/p2panda-encryption`, are excluded from the workspace. diff --git a/pkgs/id/book/library/crates.md b/pkgs/id/book/library/crates.md index cf2b92398d..12c1b7436c 100644 --- a/pkgs/id/book/library/crates.md +++ b/pkgs/id/book/library/crates.md @@ -2,9 +2,9 @@ Source: primary sources are [pkgs/id/Cargo.toml](https://github.com/developing-today/code/blob/main/pkgs/id/Cargo.toml), [pkgs/id/src/lib.rs](https://github.com/developing-today/code/blob/main/pkgs/id/src/lib.rs), and the per-crate manifests and `lib.rs` files under [pkgs/id/crates/](https://github.com/developing-today/code/blob/main/pkgs/id/crates/). This chapter is complete without following those links; they record provenance only. -The `id` code lives in one Cargo workspace rooted at `pkgs/id/`. The workspace has 17 members: the root package `id` plus 16 crates under `pkgs/id/crates/`. Default members are 15: the root plus 14 crates. `id-native-shell` and `id-hw-shell` are workspace members but not default members, so a plain `cargo build` in `pkgs/id/` never acquires the Bevy desktop dependencies or the hardware-shell code. The 16 sub-crates declare 228 `pub mod` items in total across their `lib.rs` files; the root adds 26 modules of its own code plus about 90 re-exported modules (see [The id facade crate](facade.md)). +The `id` code lives in one Cargo workspace rooted at `pkgs/id/`. The workspace has 20 members: the root package `id` plus 19 crates under `pkgs/id/crates/`. Default members are 17: the root plus 16 crates. `id-native-shell`, `id-hw-shell`, and `id-tui-shell` are workspace members but not default members, so a plain `cargo build` in `pkgs/id/` never acquires the Bevy desktop dependencies or the shell code. The 19 sub-crates declare 247 `pub mod` items in total across their `lib.rs` files; the root adds 26 modules of its own code plus about 90 re-exported modules (see [The id facade crate](facade.md)). -The workspace is the product of a numbered split of one original crate, recorded in the crate doc headers as umbrella issue #3447: Phase 1 extracted `id-core` (#3447), step 1 extracted `id-caps` (#4403), steps 2a and 2b extracted `id-store` and `id-events` (#4405), step 3 extracted `id-sync` (#4406), step 4 extracted `id-groups` (#4407), step 5 extracted `id-worlds` (#4408), steps 6b and 6c extracted `id-directory` and `id-web` (#4409), and step 7b extracted `id-cli` (#4411). Four crates are not split products: `id-config` (slice 9111-01, #10178), `id-currency-registry` (F1 and F2 of #2062, #2317 and #2318), `id-render` (#7918, decision records #5849 and #5855), and `id-import-notion` (slice 1, #8419). The two shells are separate consumers, covered in [Guest apps and shells as consumers](guests-and-shells.md). +The workspace is the product of a numbered split of one original crate, recorded in the crate doc headers as umbrella issue #3447: Phase 1 extracted `id-core` (#3447), step 1 extracted `id-caps` (#4403), steps 2a and 2b extracted `id-store` and `id-events` (#4405), step 3 extracted `id-sync` (#4406), step 4 extracted `id-groups` (#4407), step 5 extracted `id-worlds` (#4408), steps 6b and 6c extracted `id-directory` and `id-web` (#4409), and step 7b extracted `id-cli` (#4411). Four crates are not split products: `id-config` (slice 9111-01, #10178), `id-currency-registry` (F1 and F2 of #2062, #2317 and #2318), `id-render` (#7918, decision records #5849 and #5855), and `id-import-notion` (slice 1, #8419); `id-client` (#13403), `id-tui-shell` (#12818), and `id-pg` (#13760) are likewise purpose-built rather than split products. The three shells are separate consumers, covered in [Guest apps and shells as consumers](guests-and-shells.md). ## Dependency direction @@ -20,7 +20,7 @@ Production `[dependencies]` edges only; dev-dependencies are named where they ma - `id-currency-registry` depends on nothing and its only production dependent is the facade. - `id-render` and `id-import-notion` depend on nothing and have no dependents, but both are default members and both carry maintained integration test suites. ARCHITECTURE.md calls them candidates for removal or for documenting as unused; no code, manifest, or test marks either crate deprecated or slated for removal (disagreement LIB-11). -## The seventeen members +## The twenty members **`id` (root, the facade).** Purpose: the published library surface and the `id` binary; the root `Cargo.toml` description, "A peer-to-peer file sharing CLI built with Iroh", predates the worlds, directory, and currency surface (disagreement LIB-13). Public modules: 26 modules of its own code in `pkgs/id/src/`, plus about 90 modules re-exported from sub-crates at `id::` paths. Key types and functions: `Cli`, `Command`, the `cmd_*` command functions, `open_store`, `StoreType`, `load_or_create_keypair`, and the constants `KEY_FILE`, `CLIENT_KEY_FILE`, `SERVE_LOCK`, `STORE_PATH`, and `META_ALPN`. Features: `default = ["sandbox", "world"]`, plus `sandbox`, `world`, `ssh`, `web`, `dht`, and `currency-poc-tb`. Dependents: `id-native-shell` and `id-hw-shell` in production; `id-store` dev-depends on it for tests. Full treatment: [The id facade crate](facade.md). @@ -56,6 +56,12 @@ Production `[dependencies]` edges only; dev-dependencies are named where they ma **`id-hw-shell` — 0 public modules.** Purpose: the ESP32-class hardware shell spike (more-shells v1 slice 3, #10929): the presence, journal-head, and confirm/act subset of the F13.1 shell contract. The whole crate is one `src/lib.rs` of 996 lines. Key types and functions: `CONTRACT_NAME = "shell"`, `CONTRACT_VERSION = 1`, `capability_statement()`, `HwShell`, `PresentedChoice`, `SelectableField`, and `HwError`. Features: none. Production dependency: the facade with `features = ["world"]`. Dependents: none; not a default member. Full treatment: [Guest apps and shells as consumers](guests-and-shells.md). +**`id-tui-shell` — 0 public modules.** Purpose: the terminal (TUI) shell for id (more-shells v2 slice 2, #12818): the text-native world-session client on the F13.1 shell contract. The whole crate is one `src/lib.rs` with no `pub mod` declarations; its surface is defined at the crate root. Dependents: none; it is a workspace member but not a default member. Full treatment: [Guest apps and shells as consumers](guests-and-shells.md). + +**`id-client` — 1 public module.** Purpose: the client-only Rust facade for the id native Android client v1 (slice 1 of #7938, child #13403). Public modules: `session`. Dependents: none in the workspace; it is a default member. + +**`id-pg` — 0 public modules.** Purpose: the Postgres-over-HTTP adapter's query translator and collection allowlist (design #5805, §3; slice #13760): it validates the data-shaped query object against the owner's allowlist and either produces the PostgREST request or refuses the query by the design's stable feature names, before any network call. The surface is re-exported at the crate root: `Translator` and `effective_ordering`; the query object (`Query`, `Target`, `SelectItem`, `FilterExpr`, `FilterLeaf`, `FilterOp`, `OrderKey`, `Pagination`, `CountPref`, `Method`, `Direction`); the allowlist (`CollectionAllowlist`, `ColumnDecl`, `DEFAULT_MAX_LIMIT`); the output (`PostgrestRequest`); and the refusal vocabulary (`Refusal`, `RefusalCode`, `Feature`). Features: none. Dependents: none yet; the sibling adapter slices — typed mapping (#13761), error mapping (#13762), and the read paths (#13763) — build on it. + ## Embedding examples from real call sites The shipped binary is itself a facade consumer: `pkgs/id/src/main.rs:10-13` imports `id::{Cli, Command, PeekOptions, PeersOptions, SearchOptions, ServeOptions, cmd_find, cmd_get_multi, cmd_gethash, cmd_id, cmd_list, cmd_migrate_tags, cmd_peek, cmd_peers, cmd_put_hash, cmd_put_multi, cmd_search, cmd_serve, cmd_show, cmd_tag, run_repl}`, and `pkgs/id/src/main.rs:202` calls `id::cli::normalize_args(std::env::args_os())`. diff --git a/pkgs/id/crates/id-pg/Cargo.toml b/pkgs/id/crates/id-pg/Cargo.toml new file mode 100644 index 0000000000..79027d5e9f --- /dev/null +++ b/pkgs/id/crates/id-pg/Cargo.toml @@ -0,0 +1,96 @@ +[package] +name = "id-pg" +version = "0.1.0" +edition = "2024" +rust-version = "1.96" +description = "Postgres-over-HTTP (PostgREST) query translator and collection allowlist for the id foreign data-store adapters (#5805; translator slice #13760)" +license = "MIT OR Apache-2.0" + +# Slice #13760 of the Postgres-over-HTTP adapter design (#5805, +# doc/2026-11-23T20-55-00Z_design_id5805_postgres_http_adapter): the pure +# query translator. It accepts the data-shaped query object, validates it +# against the owner's collection allowlist (design section 3), and either +# produces the PostgREST request to send or refuses the query by stable +# feature name (section 3.2) before any network call. Transport, typed +# mapping (section 5.1), and the grantee error collapse (section 6) are the +# sibling slices #13763, #13761, and #13762; this crate is the allowlist +# layer those slices build on (design section 4, layer 1). + +[dependencies] +serde = { version = "1", features = ["derive"] } + +[dev-dependencies] +proptest = "1.12" + +[lints.rust] +unsafe_code = "warn" +rust_2018_idioms = { level = "warn", priority = -1 } +rust_2024_compatibility = { level = "warn", priority = -1 } +missing_debug_implementations = "warn" +missing_docs = "warn" +trivial_casts = "warn" +trivial_numeric_casts = "warn" +unused_lifetimes = "warn" +unused_qualifications = "warn" + +[lints.clippy] +all = { level = "warn", priority = -1 } +pedantic = { level = "warn", priority = -1 } +nursery = { level = "warn", priority = -1 } +cargo = { level = "warn", priority = -1 } +unwrap_used = "deny" +expect_used = "deny" +panic = "deny" +unimplemented = "deny" +todo = "deny" +dbg_macro = "deny" +print_stdout = "allow" +print_stderr = "allow" +clone_on_ref_ptr = "warn" +create_dir = "warn" +deref_by_slicing = "warn" +empty_structs_with_brackets = "warn" +filetype_is_file = "warn" +float_cmp_const = "warn" +fn_to_numeric_cast_any = "warn" +format_push_string = "warn" +get_unwrap = "warn" +if_then_some_else_none = "warn" +lossy_float_literal = "warn" +map_err_ignore = "warn" +mem_forget = "warn" +mixed_read_write_in_expression = "warn" +mutex_atomic = "warn" +rc_buffer = "warn" +rc_mutex = "warn" +redundant_type_annotations = "warn" +rest_pat_in_fully_bound_structs = "warn" +same_name_method = "warn" +self_named_module_files = "warn" +str_to_string = "warn" +string_add = "warn" +suspicious_xor_used_as_pow = "warn" +try_err = "warn" +undocumented_unsafe_blocks = "warn" +unnecessary_safety_comment = "warn" +unnecessary_safety_doc = "warn" +unnecessary_self_imports = "warn" +unneeded_field_pattern = "warn" +verbose_file_reads = "warn" +module_name_repetitions = "allow" +must_use_candidate = "allow" +missing_errors_doc = "allow" +missing_panics_doc = "allow" +redundant_pub_crate = "allow" +significant_drop_tightening = "allow" +option_if_let_else = "allow" +multiple_crate_versions = "allow" +cargo_common_metadata = "allow" +too_many_lines = "allow" +too_many_arguments = "allow" +fn_params_excessive_bools = "allow" +struct_excessive_bools = "allow" +cognitive_complexity = "allow" +future_not_send = "allow" +assert_is_empty = "allow" +chunks_exact_to_as_chunks = "allow" diff --git a/pkgs/id/crates/id-pg/src/allowlist.rs b/pkgs/id/crates/id-pg/src/allowlist.rs new file mode 100644 index 0000000000..c1f2da9d51 --- /dev/null +++ b/pkgs/id/crates/id-pg/src/allowlist.rs @@ -0,0 +1,84 @@ +//! The owner's collection allowlist (design §3.1, §4 layer 1). +//! +//! A collection is the grantable unit: the adapter exposes exactly the +//! collections listed here, with exactly the columns declared here. +//! A column that exists in the source but is not declared is *withheld* +//! — and, by the §6 collapse rule, indistinguishable from a column +//! that does not exist at all: both are `field_unsupported`. +//! +//! Registration and owner configuration (#13758) will construct these +//! values after checking them against the live endpoint; until then +//! they are built directly in the shapes the design specifies. + +use serde::{Deserialize, Serialize}; + +/// The per-collection row cap applied when the owner declares none +/// (design §3.1: "default 500 rows"). +pub const DEFAULT_MAX_LIMIT: u32 = 500; + +/// One declared column of a collection. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ColumnDecl { + /// The column name as PostgREST addresses it. + pub name: String, + /// Whether queries may filter on this column. + pub filterable: bool, + /// Whether queries may order by this column. + pub orderable: bool, +} + +/// The allowlist for one collection (one table or view). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CollectionAllowlist { + /// The exposed schema the endpoint was registered with. Sent as + /// the request's `Accept-Profile`; a request naming any other + /// schema is refused by construction, since only this value is + /// ever emitted. + pub schema: String, + /// The relation name (table or view) within `schema`. + pub relation: String, + /// The declared columns, in declaration order. Projection `*` and + /// an empty projection both expand to this list, in this order — + /// never to whatever the source currently has. + pub columns: Vec, + /// The declared unique key: column names, all of which must be + /// declared columns. Appended to every ordering as the final + /// tiebreak so the ordering is total and keyset pagination is + /// stable. + pub unique_key: Vec, + /// The declared per-collection row cap. `None` applies + /// [`DEFAULT_MAX_LIMIT`]. + pub max_limit: Option, +} + +impl CollectionAllowlist { + /// The row cap in force for this collection. + pub fn effective_max_limit(&self) -> u32 { + self.max_limit.unwrap_or(DEFAULT_MAX_LIMIT) + } + + /// Look up a declared column by name. + pub fn column(&self, name: &str) -> Option<&ColumnDecl> { + self.columns.iter().find(|c| c.name == name) + } + + /// Whether `name` is a declared column at all. + pub fn is_declared(&self, name: &str) -> bool { + self.column(name).is_some() + } + + /// Whether `name` may be filtered on (declared and filterable). + pub fn is_filterable(&self, name: &str) -> bool { + self.column(name).is_some_and(|c| c.filterable) + } + + /// Whether `name` may be ordered by (declared and orderable). + pub fn is_orderable(&self, name: &str) -> bool { + self.column(name).is_some_and(|c| c.orderable) + } + + /// The declared column names, in declaration order. + pub fn declared_column_names(&self) -> Vec<&str> { + self.columns.iter().map(|c| c.name.as_str()).collect() + } +} diff --git a/pkgs/id/crates/id-pg/src/lib.rs b/pkgs/id/crates/id-pg/src/lib.rs new file mode 100644 index 0000000000..adbdcca523 --- /dev/null +++ b/pkgs/id/crates/id-pg/src/lib.rs @@ -0,0 +1,63 @@ +//! Postgres-over-HTTP query translator with allowlist (design #5805, §3). +//! +//! The adapter speaks exactly one interface: a PostgREST-compatible REST +//! surface over one exposed schema. This crate is the pure translation +//! layer. It takes the data-shaped query object ([`Query`]) plus the +//! owner's collection allowlists ([`CollectionAllowlist`]) and either +//! produces the [`PostgrestRequest`] to send or refuses the query with a +//! stable feature name from the design's §3.2 refusal table — always +//! before any network call (design §9, invariant 1). +//! +//! Scope boundaries, per the design's implementation slices (§11): +//! +//! - This crate is §3 (query translation) and the §10 property/model +//! tests over it. Slice #13760. +//! - Typed mapping of response values (§5.1) is #13761; the error +//! mapping and grantee collapse of *source* errors (§6) is #13762; +//! the live/materialized read paths and the HTTP transport are +//! #13763. Registration and owner config (§4) are #13758 — until that +//! lands, allowlists are constructed directly in the shapes the +//! design specifies. +//! - The translator only ever produces a `GET` request for one +//! collection. It has no way to express a write (design §9, +//! invariant 10). +//! +//! Refusal precedence, when a query violates several rules at once, is +//! fixed and deterministic so the refusal table is model-testable: +//! +//! 1. Non-`GET` method → `write_unsupported`. +//! 2. Non-collection target → `rpc_unsupported` / +//! `discovery_unsupported` / `sql_unsupported`. +//! 3. Count preference → `count_unsupported`. +//! 4. Offset/page pagination → `offset_unsupported`. +//! 5. Non-conjunctive filter tree → `boolean_unsupported`. +//! 6. Embed in the projection → `join_unsupported`. +//! 7. Relation not in the owner's allowlist → `not_available`. +//! 8. Undeclared / non-filterable / non-orderable column → +//! `field_unsupported`. +//! 9. Text-pattern operator → `text_pattern_unsupported`. +//! 10. Limit above the collection cap → `limit_exceeded`. +//! +//! Malformed-value edges the design does not name are refused as +//! `field_unsupported` rather than serialized into a request the source +//! would reject or misread: a comparison against `null` (null tests go +//! through `is.null`), an empty `in` list, a non-finite float, a keyset +//! cursor whose arity does not match the effective ordering, and a +//! `null` inside a keyset cursor (ordering keys are the declared unique +//! key and declared orderable columns; a null there has no total-order +//! position to page from). + +mod allowlist; +mod query; +mod refusal; +mod translate; +mod value; + +pub use allowlist::{CollectionAllowlist, ColumnDecl, DEFAULT_MAX_LIMIT}; +pub use query::{ + CountPref, Direction, FilterExpr, FilterLeaf, FilterOp, Method, OrderKey, Pagination, Query, + SelectItem, Target, +}; +pub use refusal::{Feature, Refusal, RefusalCode}; +pub use translate::{PostgrestRequest, Translator, effective_ordering}; +pub use value::Value; diff --git a/pkgs/id/crates/id-pg/src/query.rs b/pkgs/id/crates/id-pg/src/query.rs new file mode 100644 index 0000000000..0e18b15bf7 --- /dev/null +++ b/pkgs/id/crates/id-pg/src/query.rs @@ -0,0 +1,252 @@ +//! The data-shaped query object (design §3, #5816 shape). +//! +//! The object deliberately can *express* shapes the adapter refuses — +//! writes, RPC targets, boolean trees, embeds, offset pagination, count +//! preferences — so that refusing them by name is a decision of the +//! translator, exercised by the §10 model tests, rather than something +//! the type system hides. + +use serde::{Deserialize, Serialize}; + +use crate::value::Value; + +/// The HTTP method the query asks for. Only `Get` is translatable; +/// every other method is a write and is refused (design §3.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Method { + /// `GET` — the only read method. + Get, + /// `POST`. + Post, + /// `PATCH`. + Patch, + /// `PUT`. + Put, + /// `DELETE`. + Delete, +} + +/// What the query addresses. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum Target { + /// One relation (table or view) by its bare name within the + /// endpoint's exposed schema. + Collection(String), + /// A PostgREST `/rpc/` function call. Refused: + /// `rpc_unsupported`. + Rpc(String), + /// The PostgREST root (`GET /`), i.e. schema/OpenAPI discovery. + /// Refused: `discovery_unsupported`. + Root, + /// A raw-SQL `/query` endpoint. Refused: `sql_unsupported`. + Sql, +} + +/// One element of the requested projection. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum SelectItem { + /// A single declared column by name. + Column(String), + /// `*` — the adapter never forwards a star; it expands to the + /// collection's declared column list (design §3.1). + All, + /// A PostgREST embed, `relation(...)` — a join. Refused: + /// `join_unsupported`. + Embed { + /// The embedded relation's name. + relation: String, + /// The embedded projection. + items: Vec, + }, +} + +/// The closed filter operator set, plus the operators the design +/// refuses by name (kept in the vocabulary so the refusal is a +/// translator decision). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum FilterOp { + /// `eq`. + Eq, + /// `neq`. + Neq, + /// `lt`. + Lt, + /// `lte`. + Lte, + /// `gt`. + Gt, + /// `gte`. + Gte, + /// `in` — the leaf value must be a non-empty [`Value::List`]. + In, + /// `is.null` — the leaf value is ignored. + IsNull, + /// `like`. Refused: `text_pattern_unsupported`. + Like, + /// `ilike`. Refused: `text_pattern_unsupported`. + ILike, + /// `match`. Refused: `text_pattern_unsupported`. + Match, + /// `fts`. Refused: `text_pattern_unsupported`. + Fts, + /// `plfts`. Refused: `text_pattern_unsupported`. + PlFts, + /// `wfts`. Refused: `text_pattern_unsupported`. + Wfts, +} + +impl FilterOp { + /// Whether the design refuses this operator as a text pattern + /// (§3.2: `like`, `ilike`, `match`, and the full-text family). + pub(crate) fn is_text_pattern(self) -> bool { + matches!( + self, + FilterOp::Like + | FilterOp::ILike + | FilterOp::Match + | FilterOp::Fts + | FilterOp::PlFts + | FilterOp::Wfts + ) + } + + /// The PostgREST operator token for a supported operator. + pub(crate) fn postgrest_token(self) -> Option<&'static str> { + match self { + FilterOp::Eq => Some("eq"), + FilterOp::Neq => Some("neq"), + FilterOp::Lt => Some("lt"), + FilterOp::Lte => Some("lte"), + FilterOp::Gt => Some("gt"), + FilterOp::Gte => Some("gte"), + FilterOp::In => Some("in"), + FilterOp::IsNull => Some("is"), + _ => None, + } + } +} + +/// One filter predicate: a column, an operator, and a literal value. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FilterLeaf { + /// The column the predicate filters on. + pub column: String, + /// The operator. + pub op: FilterOp, + /// The literal value (a list for `in`; ignored for `is.null`). + pub value: Value, +} + +/// The filter expression tree. Only a flat conjunction of leaves is +/// translatable; `Or` and `Not` are refused as `boolean_unsupported`. +/// Nested `And` nodes are still a conjunction and are flattened. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum FilterExpr { + /// A conjunction of sub-expressions (leaves or further `And`s). + And(Vec), + /// A disjunction. Refused: `boolean_unsupported`. + Or(Vec), + /// A negation. Refused: `boolean_unsupported`. + Not(Box), + /// A single predicate. + Leaf(FilterLeaf), +} + +/// Sort direction for one ordering key. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Direction { + /// Ascending (`asc`). + Asc, + /// Descending (`desc`). + Desc, +} + +/// One ordering key: a declared orderable column and a direction. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct OrderKey { + /// The column to order by. + pub column: String, + /// The direction. + pub direction: Direction, +} + +/// How the query pages through the result. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum Pagination { + /// No cursor: the first page. + None, + /// Keyset pagination: the cursor is the last row's ordering-key + /// tuple, aligned with the *effective* ordering (the query's + /// ordering keys with the collection's unique key appended as the + /// final tiebreak). + Keyset { + /// The cursor tuple, one value per effective ordering key. + cursor: Vec, + }, + /// Offset pagination. Refused: `offset_unsupported`. + Offset { + /// The offset. + offset: u32, + }, + /// Page-number pagination. Refused: `offset_unsupported`. + Page { + /// The page number. + page: u32, + }, +} + +/// A count preference (the PostgREST `Prefer: count=...` family). +/// Any preference is refused: `count_unsupported` — a count discloses +/// the size of a withheld set. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum CountPref { + /// No count requested. + None, + /// `count=exact`. + Exact, + /// `count=planned`. + Planned, + /// `count=estimated`. + Estimated, +} + +/// A query against one collection, in the #5816 data shape. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Query { + /// The HTTP method. + pub method: Method, + /// What the query addresses. + pub target: Target, + /// The requested projection. An empty list means all declared + /// columns, exactly as [`SelectItem::All`] does. + pub select: Vec, + /// The filter expression, if any. + pub filter: Option, + /// The requested ordering keys (may be empty; the unique key + /// tiebreak is appended by the translator). + pub order: Vec, + /// The pagination mode. + pub pagination: Pagination, + /// The requested row limit. `None` means the collection cap. + pub limit: Option, + /// The count preference. + pub count: CountPref, +} + +impl Query { + /// A plain read of one collection: `GET`, no projection, filter, + /// ordering, pagination, limit, or count preference. Builders of + /// real queries start here and set the fields they need. + pub fn read(relation: &str) -> Self { + Query { + method: Method::Get, + target: Target::Collection(relation.to_string()), + select: Vec::new(), + filter: None, + order: Vec::new(), + pagination: Pagination::None, + limit: None, + count: CountPref::None, + } + } +} diff --git a/pkgs/id/crates/id-pg/src/refusal.rs b/pkgs/id/crates/id-pg/src/refusal.rs new file mode 100644 index 0000000000..42e34b2c36 --- /dev/null +++ b/pkgs/id/crates/id-pg/src/refusal.rs @@ -0,0 +1,142 @@ +//! Refusals: stable codes and feature names (design §3.2, §6). +//! +//! A refusal's grantee-visible body depends only on its code and +//! feature name — never on a column name, a value, or on whether a +//! column was withheld or simply absent. That is what makes an +//! undeclared column and a withheld column produce byte-identical +//! error bodies (§6.2), which the §10 model tests assert. + +use std::fmt; + +use serde::{Deserialize, Serialize}; + +/// The stable error code (design §6.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum RefusalCode { + /// The query shape is outside the §3.1 supported set. Shown as it + /// is: it depends only on the query text. + QueryShapeRefused, + /// The requested limit exceeds the collection's declared cap. + /// Refused, never clamped (§3.2, §6.2). + LimitExceeded, + /// The collapsed outcome for anything that depends on the data or + /// the grant: unknown relation, unlisted relation (§6.2). + NotAvailable, +} + +impl RefusalCode { + /// The stable wire name of the code. + pub fn name(self) -> &'static str { + match self { + RefusalCode::QueryShapeRefused => "query_shape_refused", + RefusalCode::LimitExceeded => "limit_exceeded", + RefusalCode::NotAvailable => "not_available", + } + } +} + +/// A refused query shape, named by its stable feature name (§3.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Feature { + /// Joins and PostgREST embeds. + JoinUnsupported, + /// OR, NOT, or nested boolean trees. + BooleanUnsupported, + /// `like`, `ilike`, `match`, and the full-text operators. + TextPatternUnsupported, + /// Offset or page-number pagination. + OffsetUnsupported, + /// Exact or planned counts. + CountUnsupported, + /// RPC (`/rpc/*`). + RpcUnsupported, + /// Writes (`POST`, `PATCH`, `PUT`, `DELETE`, upsert). + WriteUnsupported, + /// Schema or OpenAPI discovery (`GET /`). + DiscoveryUnsupported, + /// Ordering, filtering, or projecting on an undeclared column — + /// the same name for a withheld column (§6.1). + FieldUnsupported, + /// Raw SQL, or any `/query` endpoint. + SqlUnsupported, + /// A limit above the declared cap. + LimitExceeded, +} + +impl Feature { + /// The stable feature name as it appears in the error (§3.2). + pub fn name(self) -> &'static str { + match self { + Feature::JoinUnsupported => "join_unsupported", + Feature::BooleanUnsupported => "boolean_unsupported", + Feature::TextPatternUnsupported => "text_pattern_unsupported", + Feature::OffsetUnsupported => "offset_unsupported", + Feature::CountUnsupported => "count_unsupported", + Feature::RpcUnsupported => "rpc_unsupported", + Feature::WriteUnsupported => "write_unsupported", + Feature::DiscoveryUnsupported => "discovery_unsupported", + Feature::FieldUnsupported => "field_unsupported", + Feature::SqlUnsupported => "sql_unsupported", + Feature::LimitExceeded => "limit_exceeded", + } + } +} + +/// A query refused before any network call. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Refusal { + /// The stable error code. + pub code: RefusalCode, + /// The refused feature, when the code carries one. `not_available` + /// carries none: naming a feature would distinguish outcomes the + /// collapse rule merges. + pub feature: Option, +} + +impl Refusal { + /// A `query_shape_refused` refusal naming `feature`. + pub fn shape(feature: Feature) -> Self { + Refusal { + code: RefusalCode::QueryShapeRefused, + feature: Some(feature), + } + } + + /// The `limit_exceeded` refusal (§3.2, §6.2). + pub fn limit_exceeded() -> Self { + Refusal { + code: RefusalCode::LimitExceeded, + feature: Some(Feature::LimitExceeded), + } + } + + /// The collapsed `not_available` refusal. + pub fn not_available() -> Self { + Refusal { + code: RefusalCode::NotAvailable, + feature: None, + } + } + + /// The stable grantee-visible error body. It is a function of the + /// code and feature name only, so two refusals with the same code + /// and feature are byte-identical no matter what the query named. + pub fn body(&self) -> String { + match self.feature { + Some(feature) => format!( + "{{\"code\":\"{}\",\"feature\":\"{}\"}}", + self.code.name(), + feature.name() + ), + None => format!("{{\"code\":\"{}\"}}", self.code.name()), + } + } +} + +impl fmt::Display for Refusal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.body()) + } +} + +impl std::error::Error for Refusal {} diff --git a/pkgs/id/crates/id-pg/src/translate.rs b/pkgs/id/crates/id-pg/src/translate.rs new file mode 100644 index 0000000000..904d8046f9 --- /dev/null +++ b/pkgs/id/crates/id-pg/src/translate.rs @@ -0,0 +1,431 @@ +//! The translator: query object + allowlist → PostgREST request, or a +//! refusal by name (design §3). +//! +//! The check order implements the precedence documented in the crate +//! root: method, target, count, pagination kind, boolean structure, +//! embeds, relation, fields, operators, values, cursor, limit. + +use crate::allowlist::CollectionAllowlist; +use crate::query::{ + CountPref, Direction, FilterExpr, FilterLeaf, FilterOp, Method, OrderKey, Pagination, Query, + SelectItem, Target, +}; +use crate::refusal::{Feature, Refusal}; +use crate::value::Value; + +/// A PostgREST request, as data. The transport (#13763) turns this +/// into an actual HTTP call; nothing here performs I/O. +/// +/// The request is always a `GET` against one relation in the +/// endpoint's one exposed schema. There is no field for a body, a +/// write method, or a `Prefer` header, so a write or a count cannot +/// be expressed in the output any more than in the rules. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PostgrestRequest { + /// The HTTP method: always `"GET"`. + pub method: &'static str, + /// The request path: `/` followed by the relation name. + pub path: String, + /// The value for the `Accept-Profile` header: the collection's + /// one exposed schema (design §2, schema pinning). + pub accept_profile: String, + /// The query parameters, in emission order: `select`, one + /// parameter per filter leaf, the keyset `or` parameter when + /// paging, `order`, and `limit`. + pub params: Vec<(String, String)>, +} + +/// The query translator, holding the owner's collection allowlists. +#[derive(Debug, Clone)] +pub struct Translator { + collections: Vec, +} + +impl Translator { + /// Build a translator over the owner's allowlist of collections. + /// The adapter exposes exactly these collections; a query naming + /// any other relation is `not_available`. + pub fn new(collections: Vec) -> Self { + Translator { collections } + } + + /// Translate one query. Every §3.2 refusal is returned before any + /// request exists; a successful result is the whole request. + pub fn translate(&self, query: &Query) -> Result { + // 1. Method: anything but GET is a write. + if query.method != Method::Get { + return Err(Refusal::shape(Feature::WriteUnsupported)); + } + // 2. Target: only a collection read is a v1 shape. + let relation = match &query.target { + Target::Collection(name) => name, + Target::Rpc(_) => return Err(Refusal::shape(Feature::RpcUnsupported)), + Target::Root => return Err(Refusal::shape(Feature::DiscoveryUnsupported)), + Target::Sql => return Err(Refusal::shape(Feature::SqlUnsupported)), + }; + // 3. Counts disclose the size of a withheld set. + if query.count != CountPref::None { + return Err(Refusal::shape(Feature::CountUnsupported)); + } + // 4. Pagination kind: keyset only. + match &query.pagination { + Pagination::Offset { .. } | Pagination::Page { .. } => { + return Err(Refusal::shape(Feature::OffsetUnsupported)); + } + Pagination::None | Pagination::Keyset { .. } => {} + } + // 5. Filter structure: a flat conjunction of leaves. + let mut leaves: Vec<&FilterLeaf> = Vec::new(); + if let Some(filter) = &query.filter { + flatten_filter(filter, &mut leaves)?; + } + // 6. Embeds are joins, wherever they nest in the projection. + if select_contains_embed(&query.select) { + return Err(Refusal::shape(Feature::JoinUnsupported)); + } + // 7. The relation must be one the owner listed. Unknown and + // unlisted collapse to the same outcome. + let collection = self + .collections + .iter() + .find(|c| &c.relation == relation) + .ok_or_else(Refusal::not_available)?; + // 8. Fields: projection, filter, and order columns must be + // declared for the use they are put to. An undeclared column + // and a withheld column are the same refusal (§6.1). + let projection = resolve_projection(collection, &query.select)?; + for leaf in &leaves { + if !collection.is_filterable(&leaf.column) { + return Err(Refusal::shape(Feature::FieldUnsupported)); + } + } + for key in &query.order { + if !collection.is_orderable(&key.column) { + return Err(Refusal::shape(Feature::FieldUnsupported)); + } + } + // 9. Operators: the text-pattern family is refused by name. + for leaf in &leaves { + if leaf.op.is_text_pattern() { + return Err(Refusal::shape(Feature::TextPatternUnsupported)); + } + } + // 10. Values and rendering of the filter parameters. + let mut params: Vec<(String, String)> = vec![("select".to_string(), projection.join(","))]; + for leaf in &leaves { + params.push((leaf.column.clone(), render_leaf_value(leaf)?)); + } + // 11. Ordering and the keyset cursor over the effective + // ordering (total by construction: see `effective_ordering`). + let ordering = effective_ordering(collection, &query.order); + if let Pagination::Keyset { cursor } = &query.pagination { + params.push(("or".to_string(), keyset_or(&ordering, cursor)?)); + } + params.push(("order".to_string(), render_order(&ordering))); + // 12. Limit: above the cap is refused, never clamped. + let cap = collection.effective_max_limit(); + if let Some(limit) = query.limit { + if limit > cap { + return Err(Refusal::limit_exceeded()); + } + } + params.push(("limit".to_string(), query.limit.unwrap_or(cap).to_string())); + Ok(PostgrestRequest { + method: "GET", + path: format!("/{relation}"), + accept_profile: collection.schema.clone(), + params, + }) + } +} + +/// The effective ordering for a query: the query's ordering keys +/// (deduplicated by column, first occurrence wins) with the +/// collection's declared unique key appended, ascending, as the final +/// tiebreak. The result is always total — it ends with the unique key +/// — which is what makes keyset pagination stable (design §3.1). +pub fn effective_ordering(collection: &CollectionAllowlist, order: &[OrderKey]) -> Vec { + let mut effective: Vec = Vec::new(); + for key in order { + if !effective.iter().any(|k| k.column == key.column) { + effective.push(key.clone()); + } + } + for column in &collection.unique_key { + if !effective.iter().any(|k| &k.column == column) { + effective.push(OrderKey { + column: column.clone(), + direction: Direction::Asc, + }); + } + } + effective +} + +/// Flatten a filter expression into its leaves. Only conjunctions +/// flatten; `Or` and `Not` are `boolean_unsupported` wherever they +/// appear in the tree. +fn flatten_filter<'a>(expr: &'a FilterExpr, out: &mut Vec<&'a FilterLeaf>) -> Result<(), Refusal> { + match expr { + FilterExpr::Leaf(leaf) => { + out.push(leaf); + Ok(()) + } + FilterExpr::And(parts) => { + for part in parts { + flatten_filter(part, out)?; + } + Ok(()) + } + FilterExpr::Or(_) | FilterExpr::Not(_) => Err(Refusal::shape(Feature::BooleanUnsupported)), + } +} + +/// Whether any element of the projection is an embed. Embeds nest +/// only inside embeds, so an embed at any depth means a top-level +/// embed exists. +fn select_contains_embed(items: &[SelectItem]) -> bool { + items + .iter() + .any(|item| matches!(item, SelectItem::Embed { .. })) +} + +/// The collection's declared columns as owned strings, in +/// declaration order. +fn declared_columns(collection: &CollectionAllowlist) -> Vec { + collection + .declared_column_names() + .into_iter() + .map(str::to_string) + .collect() +} + +/// Resolve the projection to the declared column list to send. +/// +/// An empty projection, or one containing `All`, expands to the +/// collection's declared columns in declaration order — the star is +/// never forwarded, so a column added to the source later is not +/// exposed by accident. An explicit list keeps the query's order, +/// deduplicated; every name must be declared. +fn resolve_projection( + collection: &CollectionAllowlist, + select: &[SelectItem], +) -> Result, Refusal> { + if select.is_empty() || select.iter().any(|item| matches!(item, SelectItem::All)) { + return Ok(declared_columns(collection)); + } + let mut columns: Vec = Vec::new(); + for item in select { + match item { + SelectItem::Column(name) => { + if !collection.is_declared(name) { + return Err(Refusal::shape(Feature::FieldUnsupported)); + } + if !columns.contains(name) { + columns.push(name.clone()); + } + } + // Embeds were refused before this point; a stray one is + // still a join, never a column. + SelectItem::Embed { .. } => { + return Err(Refusal::shape(Feature::JoinUnsupported)); + } + // Handled by the early return above; expand again rather + // than assume. + SelectItem::All => return Ok(declared_columns(collection)), + } + } + Ok(columns) +} + +/// Render one filter leaf's value as a PostgREST parameter value: +/// `op.value`, `in.(...)`, or `is.null`. +fn render_leaf_value(leaf: &FilterLeaf) -> Result { + match leaf.op { + FilterOp::IsNull => Ok("is.null".to_string()), + FilterOp::In => { + let Value::List(elements) = &leaf.value else { + return Err(Refusal::shape(Feature::FieldUnsupported)); + }; + if elements.is_empty() { + return Err(Refusal::shape(Feature::FieldUnsupported)); + } + let mut rendered = Vec::with_capacity(elements.len()); + for element in elements { + rendered.push(element.quoted_literal()?); + } + Ok(format!("in.({})", rendered.join(","))) + } + op => { + let token = op + .postgrest_token() + .ok_or_else(|| Refusal::shape(Feature::TextPatternUnsupported))?; + Ok(format!("{token}.{}", leaf.value.literal()?)) + } + } +} + +/// Render the `order` parameter value over the effective ordering. +fn render_order(ordering: &[OrderKey]) -> String { + ordering + .iter() + .map(|key| { + let direction = match key.direction { + Direction::Asc => "asc", + Direction::Desc => "desc", + }; + format!("{}.{direction}", key.column) + }) + .collect::>() + .join(",") +} + +/// Build the keyset cursor condition as a PostgREST `or=(...)` +/// parameter value: the lexicographic "strictly after the cursor +/// tuple" condition over the effective ordering. +/// +/// This `or` group is generated by the adapter from the declared +/// ordering and the cursor alone; it is not a user boolean expression +/// (those are `boolean_unsupported`). For ordering keys +/// `k0..kn` with cursor values `v0..vn`, the terms are +/// `k0 v0`, `and(k0.eq.v0, k1 v1)`, … where `` is +/// `gt` for ascending keys and `lt` for descending ones. +fn keyset_or(ordering: &[OrderKey], cursor: &[Value]) -> Result { + if cursor.len() != ordering.len() { + return Err(Refusal::shape(Feature::FieldUnsupported)); + } + let mut terms: Vec = Vec::with_capacity(ordering.len()); + for j in 0..ordering.len() { + let mut parts: Vec = Vec::with_capacity(j + 1); + for (i, key) in ordering.iter().enumerate().take(j) { + parts.push(format!("{}.eq.{}", key.column, cursor[i].quoted_literal()?)); + } + let cmp = match ordering[j].direction { + Direction::Asc => "gt", + Direction::Desc => "lt", + }; + parts.push(format!( + "{}.{cmp}.{}", + ordering[j].column, + cursor[j].quoted_literal()? + )); + if parts.len() == 1 { + terms.push(parts.remove(0)); + } else { + terms.push(format!("and({})", parts.join(","))); + } + } + Ok(format!("({})", terms.join(","))) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use crate::allowlist::ColumnDecl; + use crate::query::FilterExpr; + + fn collection() -> CollectionAllowlist { + CollectionAllowlist { + schema: "public".to_string(), + relation: "items".to_string(), + columns: vec![ + ColumnDecl { + name: "id".to_string(), + filterable: true, + orderable: true, + }, + ColumnDecl { + name: "title".to_string(), + filterable: true, + orderable: true, + }, + ColumnDecl { + name: "body".to_string(), + filterable: false, + orderable: false, + }, + ], + unique_key: vec!["id".to_string()], + max_limit: Some(50), + } + } + + fn translator() -> Translator { + Translator::new(vec![collection()]) + } + + fn param<'a>(request: &'a PostgrestRequest, key: &str) -> Option<&'a str> { + request + .params + .iter() + .find(|(k, _)| k == key) + .map(|(_, v)| v.as_str()) + } + + #[test] + fn plain_read_expands_to_declared_columns_and_defaults() { + let request = translator().translate(&Query::read("items")).unwrap(); + assert_eq!(request.method, "GET"); + assert_eq!(request.path, "/items"); + assert_eq!(request.accept_profile, "public"); + assert_eq!(param(&request, "select"), Some("id,title,body")); + assert_eq!(param(&request, "order"), Some("id.asc")); + assert_eq!(param(&request, "limit"), Some("50")); + } + + #[test] + fn tiebreak_appended_after_declared_ordering() { + let mut query = Query::read("items"); + query.order = vec![OrderKey { + column: "title".to_string(), + direction: Direction::Desc, + }]; + let request = translator().translate(&query).unwrap(); + assert_eq!(param(&request, "order"), Some("title.desc,id.asc")); + } + + #[test] + fn keyset_cursor_renders_lexicographic_or() { + let mut query = Query::read("items"); + query.order = vec![OrderKey { + column: "title".to_string(), + direction: Direction::Desc, + }]; + query.pagination = Pagination::Keyset { + cursor: vec![Value::Text("m".to_string()), Value::Int(42)], + }; + let request = translator().translate(&query).unwrap(); + assert_eq!( + param(&request, "or"), + Some("(title.lt.m,and(title.eq.m,id.gt.42))") + ); + } + + #[test] + fn in_list_quotes_text_with_commas() { + let mut query = Query::read("items"); + query.filter = Some(FilterExpr::Leaf(FilterLeaf { + column: "title".to_string(), + op: FilterOp::In, + value: Value::List(vec![ + Value::Text("a,b".to_string()), + Value::Text("plain".to_string()), + ]), + })); + let request = translator().translate(&query).unwrap(); + assert_eq!(param(&request, "title"), Some("in.(\"a,b\",plain)")); + } + + #[test] + fn is_null_renders_without_value() { + let mut query = Query::read("items"); + query.filter = Some(FilterExpr::Leaf(FilterLeaf { + column: "title".to_string(), + op: FilterOp::IsNull, + value: Value::Null, + })); + let request = translator().translate(&query).unwrap(); + assert_eq!(param(&request, "title"), Some("is.null")); + } +} diff --git a/pkgs/id/crates/id-pg/src/value.rs b/pkgs/id/crates/id-pg/src/value.rs new file mode 100644 index 0000000000..e24a7aaee4 --- /dev/null +++ b/pkgs/id/crates/id-pg/src/value.rs @@ -0,0 +1,73 @@ +//! Typed literal values carried by the query object. + +use serde::{Deserialize, Serialize}; + +use crate::refusal::{Feature, Refusal}; + +/// A literal value in a filter leaf or a keyset cursor. +/// +/// Values are data, never PostgREST text: the translator serializes them +/// at translation time (design §3.1). Integers are carried as `i64` and +/// serialized from the integer itself, never through `f64`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum Value { + /// SQL `NULL`. Only expressible through the `is.null` operator; a + /// comparison against `Null` is refused (see crate docs). + Null, + /// A boolean literal. + Bool(bool), + /// A 64-bit integer literal. + Int(i64), + /// A 64-bit float literal. Non-finite values are refused at + /// translation time. + Float(f64), + /// A text literal. + Text(String), + /// A list of literals; only valid as the value of an `in` filter. + List(Vec), +} + +impl Value { + /// Serialize a scalar literal to its PostgREST filter text. + /// + /// `Null` and `List` have no scalar literal form and are refused as + /// `field_unsupported`; a non-finite float is refused the same way + /// (it has no Postgres literal the adapter may send). + pub(crate) fn literal(&self) -> Result { + match self { + Value::Bool(b) => Ok(b.to_string()), + Value::Int(i) => Ok(i.to_string()), + Value::Float(f) => { + if f.is_finite() { + Ok(f.to_string()) + } else { + Err(Refusal::shape(Feature::FieldUnsupported)) + } + } + Value::Text(s) => Ok(s.clone()), + Value::Null | Value::List(_) => Err(Refusal::shape(Feature::FieldUnsupported)), + } + } + + /// Quote a serialized literal for use inside a PostgREST list + /// context — an `in.(...)` list or the adapter-generated keyset + /// `or=(...)` expression — where commas and parentheses are syntax. + /// Values containing a comma, parenthesis, double quote, or + /// whitespace are double-quoted with backslash escapes, per + /// PostgREST's quoting rules. + pub(crate) fn quoted_literal(&self) -> Result { + let raw = self.literal()?; + if raw.is_empty() + || raw + .chars() + .any(|c| c == ',' || c == '(' || c == ')' || c == '"' || c.is_whitespace()) + { + Ok(format!( + "\"{}\"", + raw.replace('\\', "\\\\").replace('"', "\\\"") + )) + } else { + Ok(raw) + } + } +} diff --git a/pkgs/id/crates/id-pg/tests/property.proptest-regressions b/pkgs/id/crates/id-pg/tests/property.proptest-regressions new file mode 100644 index 0000000000..3e1125c381 --- /dev/null +++ b/pkgs/id/crates/id-pg/tests/property.proptest-regressions @@ -0,0 +1,7 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 399c6b7e56b99061941f32b2ac13f4146a1b4e1260f1cfd0dc7ea6e29362f4a4 # shrinks to (collection, query) = (CollectionAllowlist { schema: "public", relation: "items", columns: [ColumnDecl { name: "id", filterable: false, orderable: false }, ColumnDecl { name: "title", filterable: true, orderable: true }, ColumnDecl { name: "created_at", filterable: true, orderable: false }, ColumnDecl { name: "owner", filterable: true, orderable: false }], unique_key: ["id", "title"], max_limit: None }, Query { method: Get, target: Collection("items"), select: [], filter: Some(Leaf(FilterLeaf { column: "title", op: Neq, value: Int(-461) })), order: [OrderKey { column: "title", direction: Asc }, OrderKey { column: "title", direction: Desc }, OrderKey { column: "title", direction: Desc }], pagination: Keyset { cursor: [Int(237), Float(834456.4197682268)] }, limit: Some(40), count: None }) diff --git a/pkgs/id/crates/id-pg/tests/property.rs b/pkgs/id/crates/id-pg/tests/property.rs new file mode 100644 index 0000000000..c39da33c72 --- /dev/null +++ b/pkgs/id/crates/id-pg/tests/property.rs @@ -0,0 +1,319 @@ +//! Property tests over the query object (verification plan §10): +//! for every generated query in the supported set, the translated +//! request uses only declared columns and operators, and the +//! pagination key is total. Oracle: the §3 allowlist. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::BTreeSet; + +use id_pg::{ + CollectionAllowlist, ColumnDecl, CountPref, Direction, FilterExpr, FilterLeaf, FilterOp, + Method, OrderKey, Pagination, Query, SelectItem, Target, Translator, Value, effective_ordering, +}; +use proptest::prelude::*; +use proptest::sample; +use proptest::strategy::BoxedStrategy; + +const POOL: [&str; 6] = ["id", "title", "body", "score", "created_at", "owner"]; + +fn collection_from_masks( + mask: u32, + filterable_mask: u32, + orderable_mask: u32, + max_limit: Option, +) -> CollectionAllowlist { + let columns: Vec = POOL + .iter() + .enumerate() + .filter(|(i, _)| mask & (1 << i) != 0) + .map(|(i, name)| ColumnDecl { + name: (*name).to_string(), + filterable: filterable_mask & (1 << i) != 0, + orderable: orderable_mask & (1 << i) != 0, + }) + .collect(); + let unique_key: Vec = columns.iter().take(2).map(|c| c.name.clone()).collect(); + CollectionAllowlist { + schema: "public".to_string(), + relation: "items".to_string(), + columns, + unique_key, + max_limit, + } +} + +fn arb_collection() -> impl Strategy { + ( + 1u32..64u32, + any::(), + any::(), + prop_oneof![Just(None), (1u32..=600u32).prop_map(Some)], + ) + .prop_map(|(mask, f, o, cap)| collection_from_masks(mask, f, o, cap)) +} + +fn arb_text() -> impl Strategy { + proptest::collection::vec( + sample::select(vec!['a', 'b', 'Z', '0', ' ', ',', '"', '(', ')', '-', '_']), + 0..=10, + ) + .prop_map(|chars| chars.into_iter().collect()) +} + +fn arb_scalar() -> impl Strategy { + prop_oneof![ + any::().prop_map(Value::Bool), + (-1000i64..1000i64).prop_map(Value::Int), + (-1.0e6f64..1.0e6f64).prop_map(Value::Float), + arb_text().prop_map(Value::Text), + ] +} + +fn arb_op_value() -> impl Strategy { + prop_oneof![ + sample::select(vec![ + FilterOp::Eq, + FilterOp::Neq, + FilterOp::Lt, + FilterOp::Lte, + FilterOp::Gt, + FilterOp::Gte, + ]) + .prop_flat_map(|op| (Just(op), arb_scalar())), + Just((FilterOp::IsNull, Value::Null)), + proptest::collection::vec(arb_scalar(), 1..=4) + .prop_map(|list| (FilterOp::In, Value::List(list))), + ] +} + +fn arb_leaf(filterable: Vec) -> impl Strategy { + (sample::select(filterable), arb_op_value()) + .prop_map(|(column, (op, value))| FilterExpr::Leaf(FilterLeaf { column, op, value })) +} + +fn arb_filter(filterable: Vec) -> BoxedStrategy> { + if filterable.is_empty() { + return Just(None).boxed(); + } + prop_oneof![ + Just(None), + arb_leaf(filterable.clone()).prop_map(Some), + proptest::collection::vec(arb_leaf(filterable), 1..=3) + .prop_map(|leaves| Some(FilterExpr::And(leaves))), + ] + .boxed() +} + +fn arb_select(declared: Vec) -> BoxedStrategy> { + prop_oneof![ + Just(Vec::new()), + Just(vec![SelectItem::All]), + proptest::collection::vec(sample::select(declared).prop_map(SelectItem::Column), 1..=3), + ] + .boxed() +} + +fn arb_order(orderable: Vec) -> BoxedStrategy> { + if orderable.is_empty() { + return Just(Vec::new()).boxed(); + } + proptest::collection::vec((sample::select(orderable), any::()), 0..=3) + .prop_map(|pairs| { + pairs + .into_iter() + .map(|(column, asc)| OrderKey { + column, + direction: if asc { Direction::Asc } else { Direction::Desc }, + }) + .collect() + }) + .boxed() +} + +fn arb_pagination(effective_len: usize) -> impl Strategy { + prop_oneof![ + Just(Pagination::None), + proptest::collection::vec(arb_scalar(), effective_len..=effective_len) + .prop_map(|cursor| Pagination::Keyset { cursor }), + ] +} + +fn arb_limit(cap: u32) -> impl Strategy> { + prop_oneof![Just(None), (0u32..=cap).prop_map(Some)] +} + +/// Generate a (collection, query) pair where the query is entirely +/// inside the §3.1 supported set for that collection. +fn arb_supported() -> impl Strategy { + arb_collection().prop_flat_map(|collection| { + let declared: Vec = collection.columns.iter().map(|c| c.name.clone()).collect(); + let filterable: Vec = collection + .columns + .iter() + .filter(|c| c.filterable) + .map(|c| c.name.clone()) + .collect(); + let orderable: Vec = collection + .columns + .iter() + .filter(|c| c.orderable) + .map(|c| c.name.clone()) + .collect(); + ( + Just(collection), + arb_select(declared), + arb_filter(filterable), + arb_order(orderable), + ) + .prop_flat_map(|(collection, select, filter, order)| { + let effective_len = effective_ordering(&collection, &order).len(); + let cap = collection.effective_max_limit(); + ( + Just(collection), + Just(select), + Just(filter), + Just(order), + arb_pagination(effective_len), + arb_limit(cap), + ) + }) + .prop_map(|(collection, select, filter, order, pagination, limit)| { + let query = Query { + method: Method::Get, + target: Target::Collection(collection.relation.clone()), + select, + filter, + order, + pagination, + limit, + count: CountPref::None, + }; + (collection, query) + }) + }) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(128))] + + #[test] + fn supported_queries_translate_within_the_allowlist( + (collection, query) in arb_supported(), + ) { + let translator = Translator::new(vec![collection.clone()]); + let request = translator + .translate(&query) + .expect("a generated supported query must translate"); + + // One GET against the one relation, in the one schema. + prop_assert_eq!(request.method, "GET"); + prop_assert_eq!(&request.path, &format!("/{}", collection.relation)); + prop_assert_eq!(&request.accept_profile, &collection.schema); + + let declared: BTreeSet<&str> = collection + .declared_column_names() + .into_iter() + .collect(); + let filterable: BTreeSet<&str> = collection + .columns + .iter() + .filter(|c| c.filterable) + .map(|c| c.name.as_str()) + .collect(); + + let mut order_columns: Vec = Vec::new(); + for (key, value) in &request.params { + match key.as_str() { + "select" => { + // Only declared columns are ever projected. + prop_assert!(!value.is_empty()); + for name in value.split(',') { + prop_assert!(declared.contains(name), "undeclared select: {name}"); + } + } + "order" => { + for term in value.split(',') { + let (column, direction) = term + .rsplit_once('.') + .expect("order term is column.direction"); + prop_assert!(declared.contains(column)); + prop_assert!(direction == "asc" || direction == "desc"); + order_columns.push(column.to_string()); + } + } + "limit" => { + let limit: u32 = value.parse().expect("limit is a number"); + prop_assert!(limit <= collection.effective_max_limit()); + } + "or" => { + // The keyset condition is parenthesized and + // mentions every effective ordering column. + prop_assert!(value.starts_with('(') && value.ends_with(')')); + for key in effective_ordering(&collection, &query.order) { + prop_assert!( + value.contains(&format!("{}.", key.column)), + "cursor condition misses ordering column {}", + key.column + ); + } + } + column => { + // A filter parameter: declared + filterable column, + // closed operator set, never an offset. + prop_assert!(filterable.contains(column), "filter on {column}"); + prop_assert!( + value.starts_with("eq.") + || value.starts_with("neq.") + || value.starts_with("lt.") + || value.starts_with("lte.") + || value.starts_with("gt.") + || value.starts_with("gte.") + || value.starts_with("in.(") + || value.as_str() == "is.null", + "unsupported operator rendering: {value}" + ); + } + } + } + + // Totality: the emitted ordering is exactly the effective + // ordering, it has no duplicate columns, and it contains + // every unique-key column — so the tuple order is total. + // (A unique-key column the query already orders by keeps its + // earlier position; it is not appended a second time.) + let effective = effective_ordering(&collection, &query.order); + let effective_columns: Vec = + effective.iter().map(|k| k.column.clone()).collect(); + prop_assert_eq!(&order_columns, &effective_columns); + let distinct: BTreeSet<&String> = order_columns.iter().collect(); + prop_assert_eq!(distinct.len(), order_columns.len()); + for column in &collection.unique_key { + prop_assert!(order_columns.contains(column)); + } + + // Determinism: the same query translates to the same request. + let again = translator.translate(&query).expect("still translates"); + prop_assert_eq!(&request, &again); + } + + #[test] + fn undeclared_filter_column_is_always_field_unsupported( + collection in arb_collection(), + outsider in sample::select(vec!["salary", "secret", "ssn", "password"]), + ) { + // None of the outsider names is in the generator's column + // pool, so each is undeclared for every generated collection. + let mut query = Query::read(&collection.relation); + query.filter = Some(FilterExpr::Leaf(FilterLeaf { + column: outsider.to_string(), + op: FilterOp::Eq, + value: Value::Int(1), + })); + let translator = Translator::new(vec![collection]); + let refusal = translator.translate(&query).expect_err("must be refused"); + prop_assert_eq!( + refusal.body(), + "{\"code\":\"query_shape_refused\",\"feature\":\"field_unsupported\"}" + ); + } +} diff --git a/pkgs/id/crates/id-pg/tests/refusal_table.rs b/pkgs/id/crates/id-pg/tests/refusal_table.rs new file mode 100644 index 0000000000..21e930cddf --- /dev/null +++ b/pkgs/id/crates/id-pg/tests/refusal_table.rs @@ -0,0 +1,306 @@ +//! Model tests over the design's §3.2 refusal table (verification +//! plan §10): each refused shape maps to its stable feature name, and +//! an undeclared column and a withheld column produce identical error +//! bodies (oracle: the §6 table). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use id_pg::{ + CollectionAllowlist, ColumnDecl, CountPref, Direction, FilterExpr, FilterLeaf, FilterOp, + Method, OrderKey, Pagination, Query, Refusal, RefusalCode, SelectItem, Target, Translator, + Value, +}; + +fn collection(max_limit: Option) -> CollectionAllowlist { + CollectionAllowlist { + schema: "public".to_string(), + relation: "items".to_string(), + columns: vec![ + ColumnDecl { + name: "id".to_string(), + filterable: true, + orderable: true, + }, + ColumnDecl { + name: "title".to_string(), + filterable: true, + orderable: true, + }, + ColumnDecl { + name: "body".to_string(), + filterable: false, + orderable: false, + }, + ], + unique_key: vec!["id".to_string()], + max_limit, + } +} + +fn translator() -> Translator { + Translator::new(vec![collection(Some(50))]) +} + +fn refusal(translator: &Translator, query: &Query) -> Refusal { + translator + .translate(query) + .expect_err("query must be refused") +} + +fn leaf(column: &str, op: FilterOp, value: Value) -> FilterExpr { + FilterExpr::Leaf(FilterLeaf { + column: column.to_string(), + op, + value, + }) +} + +fn assert_shape(translator: &Translator, query: &Query, feature: &str) { + let refusal = refusal(translator, query); + assert_eq!(refusal.code, RefusalCode::QueryShapeRefused); + assert_eq!( + refusal.body(), + format!("{{\"code\":\"query_shape_refused\",\"feature\":\"{feature}\"}}") + ); +} + +#[test] +fn writes_are_refused_by_name() { + for method in [Method::Post, Method::Patch, Method::Put, Method::Delete] { + let mut query = Query::read("items"); + query.method = method; + assert_shape(&translator(), &query, "write_unsupported"); + } +} + +#[test] +fn rpc_is_refused_by_name() { + let mut query = Query::read("items"); + query.target = Target::Rpc("do_anything".to_string()); + assert_shape(&translator(), &query, "rpc_unsupported"); +} + +#[test] +fn discovery_is_refused_by_name() { + let mut query = Query::read("items"); + query.target = Target::Root; + assert_shape(&translator(), &query, "discovery_unsupported"); +} + +#[test] +fn raw_sql_is_refused_by_name() { + let mut query = Query::read("items"); + query.target = Target::Sql; + assert_shape(&translator(), &query, "sql_unsupported"); +} + +#[test] +fn counts_are_refused_by_name() { + for count in [CountPref::Exact, CountPref::Planned, CountPref::Estimated] { + let mut query = Query::read("items"); + query.count = count; + assert_shape(&translator(), &query, "count_unsupported"); + } +} + +#[test] +fn offset_and_page_pagination_are_refused_by_name() { + for pagination in [ + Pagination::Offset { offset: 100 }, + Pagination::Page { page: 3 }, + ] { + let mut query = Query::read("items"); + query.pagination = pagination; + assert_shape(&translator(), &query, "offset_unsupported"); + } +} + +#[test] +fn boolean_trees_are_refused_by_name() { + let eq = leaf("id", FilterOp::Eq, Value::Int(1)); + for filter in [ + FilterExpr::Or(vec![eq.clone(), eq.clone()]), + FilterExpr::Not(Box::new(eq.clone())), + FilterExpr::And(vec![ + eq, + FilterExpr::Or(vec![leaf("id", FilterOp::Eq, Value::Int(2))]), + ]), + ] { + let mut query = Query::read("items"); + query.filter = Some(filter); + assert_shape(&translator(), &query, "boolean_unsupported"); + } +} + +#[test] +fn embeds_are_refused_by_name() { + let mut query = Query::read("items"); + query.select = vec![ + SelectItem::Column("id".to_string()), + SelectItem::Embed { + relation: "owner".to_string(), + items: vec![SelectItem::All], + }, + ]; + assert_shape(&translator(), &query, "join_unsupported"); +} + +#[test] +fn undeclared_and_unusable_fields_are_refused_by_name() { + // Filtering on a column that was never declared. + let mut query = Query::read("items"); + query.filter = Some(leaf("salary", FilterOp::Eq, Value::Int(1))); + assert_shape(&translator(), &query, "field_unsupported"); + + // Filtering on a declared column that is not filterable. + let mut query = Query::read("items"); + query.filter = Some(leaf("body", FilterOp::Eq, Value::Text("x".to_string()))); + assert_shape(&translator(), &query, "field_unsupported"); + + // Ordering on a declared column that is not orderable. + let mut query = Query::read("items"); + query.order = vec![OrderKey { + column: "body".to_string(), + direction: Direction::Asc, + }]; + assert_shape(&translator(), &query, "field_unsupported"); + + // Projecting a column that was never declared. + let mut query = Query::read("items"); + query.select = vec![SelectItem::Column("salary".to_string())]; + assert_shape(&translator(), &query, "field_unsupported"); +} + +#[test] +fn text_patterns_are_refused_by_name() { + for op in [ + FilterOp::Like, + FilterOp::ILike, + FilterOp::Match, + FilterOp::Fts, + FilterOp::PlFts, + FilterOp::Wfts, + ] { + let mut query = Query::read("items"); + query.filter = Some(leaf("title", op, Value::Text("abc".to_string()))); + assert_shape(&translator(), &query, "text_pattern_unsupported"); + } +} + +#[test] +fn limit_above_cap_is_refused_not_clamped() { + let mut query = Query::read("items"); + query.limit = Some(51); + let over = refusal(&translator(), &query); + assert_eq!(over.code, RefusalCode::LimitExceeded); + assert_eq!( + over.body(), + "{\"code\":\"limit_exceeded\",\"feature\":\"limit_exceeded\"}" + ); + + // At the cap is fine. + let mut query = Query::read("items"); + query.limit = Some(50); + assert!(translator().translate(&query).is_ok()); + + // The default cap is 500 when the owner declares none. + let default_cap = Translator::new(vec![collection(None)]); + let mut query = Query::read("items"); + query.limit = Some(501); + let over_default = refusal(&default_cap, &query); + assert_eq!(over_default.code, RefusalCode::LimitExceeded); + let mut query = Query::read("items"); + query.limit = Some(500); + assert!(default_cap.translate(&query).is_ok()); +} + +#[test] +fn unknown_relation_collapses_to_not_available() { + let query = Query::read("secrets"); + let refusal = refusal(&translator(), &query); + assert_eq!(refusal.code, RefusalCode::NotAvailable); + assert_eq!(refusal.feature, None); + assert_eq!(refusal.body(), "{\"code\":\"not_available\"}"); +} + +#[test] +fn withheld_and_unknown_columns_produce_identical_bodies() { + // The translator only ever sees the allowlist, so a column the + // owner withheld from it and a column that does not exist at all + // are the same input — and §6.2 requires the same body. The body + // must not even carry the column's name. + let mut withheld = Query::read("items"); + withheld.filter = Some(leaf("salary", FilterOp::Eq, Value::Int(1))); + let mut unknown = Query::read("items"); + unknown.filter = Some(leaf("never_existed", FilterOp::Eq, Value::Int(1))); + let withheld_body = refusal(&translator(), &withheld).body(); + let unknown_body = refusal(&translator(), &unknown).body(); + assert_eq!(withheld_body, unknown_body); + assert!(!withheld_body.contains("salary")); + assert!(!unknown_body.contains("never_existed")); +} + +#[test] +fn refusal_precedence_is_deterministic() { + // Method is checked before target: a POST to an RPC target is a + // write refusal, not an RPC refusal. + let mut query = Query::read("items"); + query.method = Method::Post; + query.target = Target::Rpc("f".to_string()); + assert_shape(&translator(), &query, "write_unsupported"); + + // Target is checked before count. + let mut query = Query::read("items"); + query.target = Target::Rpc("f".to_string()); + query.count = CountPref::Exact; + assert_shape(&translator(), &query, "rpc_unsupported"); +} + +#[test] +fn a_fully_supported_query_translates() { + let mut query = Query::read("items"); + query.select = vec![ + SelectItem::Column("id".to_string()), + SelectItem::Column("title".to_string()), + ]; + query.filter = Some(FilterExpr::And(vec![ + leaf("id", FilterOp::Gte, Value::Int(10)), + leaf( + "title", + FilterOp::In, + Value::List(vec![ + Value::Text("a".to_string()), + Value::Text("b".to_string()), + ]), + ), + ])); + query.order = vec![OrderKey { + column: "title".to_string(), + direction: Direction::Asc, + }]; + query.pagination = Pagination::Keyset { + cursor: vec![Value::Text("a".to_string()), Value::Int(10)], + }; + query.limit = Some(25); + let request = translator().translate(&query).unwrap(); + assert_eq!(request.method, "GET"); + assert_eq!(request.path, "/items"); + assert_eq!(request.accept_profile, "public"); + assert!( + request + .params + .iter() + .any(|(k, v)| k == "select" && v == "id,title") + ); + assert!( + request + .params + .iter() + .any(|(k, v)| k == "order" && v == "title.asc,id.asc") + ); + assert!( + request + .params + .iter() + .any(|(k, v)| k == "limit" && v == "25") + ); +}