From 2d40a2050c199590fd069b40c736ce174f9f3025 Mon Sep 17 00:00:00 2001 From: Shane McGuirt <10144278+srmcguirt@users.noreply.github.com> Date: Sat, 1 Aug 2026 10:27:12 -0400 Subject: [PATCH] =?UTF-8?q?feat(config):=20Exposure=20policy=20=E2=80=94?= =?UTF-8?q?=20narrow=20the=20auto-generated=20surface?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds `Exposure` to `Preset`, the fine-grained companion to `pg_schemas`: All every relation in the configured schemas (default; unchanged behavior, and what makes magna a Postgres gateway) Only(Vec<..>) exactly the named `schema.relation` entries ExtensionsOnly no auto-generated fields at all Motivation: `pg_schemas` was the ONLY exposure control, and it is schema- grained. An embedder pointing magna at a schema got every relation in it, which is correct for the gateway model (Postgres RLS plus the per-request role magna-serv sets are doing authorization) and wrong for an embedder that connects with a privileged role and authorizes in application code. There was no way to express the second case. `ExtensionsOnly` is that case: planning, fingerprint deduplication, and batched PgSelectStep still work for extension-registered fields, but no relation is reachable by default. Design notes: * The gate is ONE check in `gather`, not a filter at each registration pass. Everything downstream derives from `GatherOutput::resources`, so a filtered relation gets no object type, no query field, and no relation field pointing at it — unreachable rather than merely unqueryable at the root. * `build_relations` already resolves both FK endpoints against `resources` and skips when either is absent, so filtering one side of a foreign key drops the relation instead of leaving a reference to an unregistered type. Covered by a test rather than assumed. * `Only` matches the QUALIFIED name exactly — no globbing, no case folding, and an unqualified entry never matches. Every way of getting a rule wrong therefore hides a relation instead of exposing one. * A later `PresetOverride` that is silent about exposure leaves the narrower setting alone. A silent reset to the `All` default would mean layering an unrelated preset re-publishes every relation. The default is unchanged: `Preset::default()` is still `Exposure::All`. 13 tests, written as the security property — each negative case is one where a wrong answer publishes something nobody named. Co-Authored-By: Claude Opus 5 (1M context) --- crates/magna-build/src/gather.rs | 127 ++++++++++++++++++++++++++ crates/magna-config/src/lib.rs | 2 +- crates/magna-config/src/preset.rs | 137 +++++++++++++++++++++++++++++ crates/magna-config/src/resolve.rs | 43 ++++++++- 4 files changed, 307 insertions(+), 2 deletions(-) diff --git a/crates/magna-build/src/gather.rs b/crates/magna-build/src/gather.rs index fe459db..71db55c 100644 --- a/crates/magna-build/src/gather.rs +++ b/crates/magna-build/src/gather.rs @@ -37,6 +37,14 @@ pub fn gather( // 1. Resolve which namespaces match the configured schemas. let schema_oids = resolve_schema_oids(introspection, &preset.pg_schemas); + // Schema oid → name, so the exposure policy can be evaluated against a + // qualified `schema.relation` name rather than an opaque oid. + let schema_names: HashMap = introspection + .namespaces + .iter() + .map(|ns| (ns.oid, ns.name.as_str())) + .collect(); + // 2. Build (obj_oid, obj_sub_id) → description text lookup. let desc_map = build_description_map(&introspection.descriptions); @@ -54,6 +62,23 @@ pub fn gather( continue; } + // THE gate on the auto-generated surface. Everything downstream — + // object types, query fields, mutations, and the relation fields that + // other types would carry — is derived from `resources`, so a relation + // dropped here is unreachable rather than merely unqueryable at the + // root. `build_relations` below is already tolerant of a dangling FK + // target (it looks the endpoint up in `resources` and skips when + // absent), so filtering one side of a foreign key drops the relation + // field instead of producing a reference to a type that was never + // registered. + let schema_name = schema_names + .get(&class.schema_oid) + .copied() + .unwrap_or_default(); + if !preset.exposure.allows(schema_name, &class.name) { + continue; + } + let resource = build_resource(class, introspection, &desc_map)?; resources.push(resource); } @@ -542,6 +567,13 @@ mod tests { Preset::default() } + fn preset_with(exposure: magna_config::Exposure) -> Preset { + Preset { + exposure, + ..Preset::default() + } + } + fn make_registry(introspection: &IntrospectionResult) -> PgResourceRegistry { PgResourceRegistry::from_introspection(introspection) } @@ -725,4 +757,99 @@ mod tests { assert_eq!(resolved.pg_type_oid, 500); assert_eq!(resolved.values, vec!["active", "inactive"], "values sorted by sort_order"); } + + // ------------------------------------------------------------------ + // Exposure — the gate on the auto-generated surface + // ------------------------------------------------------------------ + // + // `gather` is the ONE place exposure is evaluated, so these tests are the + // real assertion that a filtered relation is unreachable. Everything + // downstream (object types, query fields, mutations, relation fields) + // derives from `GatherOutput::resources`. + + #[test] + fn exposure_all_is_the_unfiltered_baseline() { + let intro = make_introspection(); + let registry = make_registry(&intro); + + let output = gather(&intro, ®istry, &preset_with(magna_config::Exposure::All)) + .expect("gather failed"); + + assert_eq!(output.resources.len(), 2); + assert_eq!(output.relations.len(), 1, "the posts→users FK survives"); + } + + #[test] + fn exposure_only_narrows_resources_to_the_named_relation() { + let intro = make_introspection(); + let registry = make_registry(&intro); + let preset = preset_with(magna_config::Exposure::Only(vec![ + "public.users".to_string() + ])); + + let output = gather(&intro, ®istry, &preset).expect("gather failed"); + + let names: Vec<&str> = output.resources.iter().map(|r| r.name.as_str()).collect(); + assert_eq!(names, vec!["User"], "only the allowlisted relation is built"); + assert!( + !output.behaviors.contains_key("Post"), + "a filtered relation must not carry behaviors (it has no fields to act on)", + ); + } + + #[test] + fn exposure_only_drops_relations_whose_endpoint_was_filtered() { + let intro = make_introspection(); + let registry = make_registry(&intro); + // `posts` is filtered out; the posts→users FK has nowhere to hang. + let preset = preset_with(magna_config::Exposure::Only(vec![ + "public.users".to_string() + ])); + + let output = gather(&intro, ®istry, &preset).expect("gather failed"); + + assert!( + output.relations.is_empty(), + "a relation with a filtered endpoint must be dropped, not left \ + pointing at a type that never gets registered; got {:?}", + output.relations.iter().map(|r| &r.name).collect::>(), + ); + } + + #[test] + fn exposure_extensions_only_generates_an_empty_surface() { + let intro = make_introspection(); + let registry = make_registry(&intro); + + let output = gather( + &intro, + ®istry, + &preset_with(magna_config::Exposure::ExtensionsOnly), + ) + .expect("gather failed"); + + // The embedding mode: magna is a planner, not a gateway. Nothing is + // reachable except what an extension registers by hand. + assert!(output.resources.is_empty(), "no auto-generated resources"); + assert!(output.relations.is_empty(), "no auto-generated relations"); + assert!(output.behaviors.is_empty(), "no auto-generated behaviors"); + } + + #[test] + fn exposure_is_evaluated_per_schema_not_per_bare_name() { + // Guards the qualification: an allowlist entry naming another schema + // must not admit a same-named relation in `public`. + let intro = make_introspection(); + let registry = make_registry(&intro); + let preset = preset_with(magna_config::Exposure::Only(vec![ + "usr.users".to_string() + ])); + + let output = gather(&intro, ®istry, &preset).expect("gather failed"); + + assert!( + output.resources.is_empty(), + "public.users must not be admitted by an allowlist naming usr.users", + ); + } } diff --git a/crates/magna-config/src/lib.rs b/crates/magna-config/src/lib.rs index 9d24bdd..8c456e8 100644 --- a/crates/magna-config/src/lib.rs +++ b/crates/magna-config/src/lib.rs @@ -18,5 +18,5 @@ pub mod resolve; // Re-export primary public API. pub use plugin::{GatherContext, Plugin, SchemaContext}; -pub use preset::{JwtConfig, PoolConfig, Preset, SchemaBuildOptions}; +pub use preset::{Exposure, JwtConfig, PoolConfig, Preset, SchemaBuildOptions}; pub use resolve::{merge, validate, PresetOverride, ResolveError}; diff --git a/crates/magna-config/src/preset.rs b/crates/magna-config/src/preset.rs index 12a1731..83cea8d 100644 --- a/crates/magna-config/src/preset.rs +++ b/crates/magna-config/src/preset.rs @@ -112,6 +112,61 @@ impl Default for SchemaBuildOptions { } } +/// Which introspected relations become **auto-generated** GraphQL fields. +/// +/// This narrows the auto-generated surface only. Fields registered by a +/// `SchemaExtension` are unaffected by every variant here, including +/// [`Exposure::ExtensionsOnly`] — an extension field is hand-written, so it is +/// never something the engine decided to expose on your behalf. +/// +/// Exposure is evaluated once, in the gather phase, against the qualified +/// `schema.relation` name. A relation filtered out gets no object type, no +/// query field, and no relation field pointing at it from anywhere else, +/// because every downstream pass reads the same filtered resource list. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Exposure { + /// Every table and view in [`Preset::pg_schemas`]. The default, and what + /// makes magna a Postgres gateway. + All, + + /// Only the named relations, each written `schema.relation` + /// (e.g. `"public.author"`). + /// + /// Matched exactly — no globbing, no case folding. A typo therefore hides + /// a relation rather than silently widening the surface, which is the + /// direction a mistake should fail in. + Only(Vec), + + /// No auto-generated fields at all. The schema contains exactly what + /// extensions register. + /// + /// This is the mode for **embedding magna as a planning and execution + /// engine** rather than running it as a Postgres gateway: two-phase + /// planning, fingerprint deduplication, and batched `PgSelectStep` all + /// still work for extension-registered fields, but no relation is + /// reachable by default. + /// + /// Use this when authorization lives in your application rather than in + /// Postgres RLS — e.g. a service-role pool with redaction in Rust. In that + /// setup `Exposure::All` would publish every table in `pg_schemas` with no + /// row-level protection behind it. + ExtensionsOnly, +} + +impl Exposure { + /// Is `schema.relation` part of the auto-generated surface? + pub fn allows(&self, schema: &str, relation: &str) -> bool { + match self { + Exposure::All => true, + Exposure::ExtensionsOnly => false, + Exposure::Only(names) => names.iter().any(|n| { + n.split_once('.') + .is_some_and(|(s, r)| s == schema && r == relation) + }), + } + } +} + /// The single configuration object passed to all magna components. /// /// Presets are composable — start from [`Preset::default()`] (Supabase @@ -121,6 +176,12 @@ pub struct Preset { /// Postgres schemas to expose in the GraphQL API. pub pg_schemas: Vec, + /// Which relations *within* [`Preset::pg_schemas`] are auto-generated. + /// + /// `pg_schemas` is a coarse gate (whole schemas); this is the fine one. + /// Defaults to [`Exposure::All`] — every relation in the listed schemas. + pub exposure: Exposure, + /// The default Postgres role for unauthenticated requests. pub default_role: Option, @@ -151,14 +212,23 @@ pub struct Preset { impl Default for Preset { /// Sensible defaults for a Supabase-backed deployment: /// - Schema: `["public"]` + /// - Exposure: every relation in those schemas ([`Exposure::All`]) /// - Default role: `"anon"` /// - JWT secret read from `JWT_SECRET` env var /// - Subscriptions enabled /// - All CRUD mutations enabled /// - Relay support enabled + /// + /// `Exposure::All` is the gateway default: it is what makes "point magna + /// at a database and get an API" true. It assumes Postgres is enforcing + /// authorization — RLS policies plus the per-request role that + /// `magna-serv` sets. **An embedder that connects with a privileged role + /// and authorizes in application code must not keep this default**; see + /// [`Exposure::ExtensionsOnly`]. fn default() -> Self { Self { pg_schemas: vec!["public".to_string()], + exposure: Exposure::All, default_role: Some("anon".to_string()), jwt: JwtConfig::default(), pool: PoolConfig::default(), @@ -177,6 +247,7 @@ impl std::fmt::Debug for Preset { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Preset") .field("pg_schemas", &self.pg_schemas) + .field("exposure", &self.exposure) .field("default_role", &self.default_role) .field("jwt", &self.jwt) .field("pool", &self.pool) @@ -269,4 +340,70 @@ mod tests { assert!(opts.connections); assert!(!opts.simple_lists); } + + // ── Exposure ──────────────────────────────────────────────────────── + // Every negative case below is a case where a *wrong* answer publishes a + // relation the operator did not name. They are written as the security + // property, not as coverage. + + #[test] + fn default_exposure_is_all() { + // The gateway default. Changing it is a product decision, not a + // refactor — this test exists so the change is deliberate. + assert_eq!(Preset::default().exposure, Exposure::All); + } + + #[test] + fn exposure_all_admits_every_relation() { + assert!(Exposure::All.allows("public", "users")); + assert!(Exposure::All.allows("usr", "notes")); + } + + #[test] + fn exposure_extensions_only_admits_nothing() { + assert!(!Exposure::ExtensionsOnly.allows("public", "users")); + assert!(!Exposure::ExtensionsOnly.allows("usr", "notes")); + } + + #[test] + fn exposure_only_requires_the_schema_to_match_too() { + let e = Exposure::Only(vec!["public.users".to_string()]); + assert!(e.allows("public", "users")); + // The SAME relation name in another schema is a different relation. + // Matching on the bare name here would expose `usr.users` because + // someone allowlisted `public.users`. + assert!(!e.allows("usr", "users")); + assert!(!e.allows("public", "posts")); + } + + #[test] + fn exposure_only_does_not_glob() { + // `*` is an ordinary character, not a wildcard. Someone reaching for + // shell globbing must get nothing rather than everything. + let e = Exposure::Only(vec!["public.*".to_string()]); + assert!(!e.allows("public", "users")); + } + + #[test] + fn exposure_only_does_not_case_fold() { + // Postgres identifiers are case-sensitive once quoted; folding here + // would admit a relation the operator did not name. + let e = Exposure::Only(vec!["public.Users".to_string()]); + assert!(!e.allows("public", "users")); + assert!(!e.allows("public", "USERS")); + } + + #[test] + fn exposure_only_ignores_unqualified_entries() { + // A half-written rule names no schema. It must hide a relation, never + // expose one. + let e = Exposure::Only(vec!["users".to_string()]); + assert!(!e.allows("public", "users")); + assert!(!e.allows("", "users")); + } + + #[test] + fn exposure_only_with_an_empty_list_admits_nothing() { + assert!(!Exposure::Only(vec![]).allows("public", "users")); + } } diff --git a/crates/magna-config/src/resolve.rs b/crates/magna-config/src/resolve.rs index 2c12864..21772f7 100644 --- a/crates/magna-config/src/resolve.rs +++ b/crates/magna-config/src/resolve.rs @@ -6,7 +6,7 @@ //! overrides on top. use crate::plugin::Plugin; -use crate::preset::{PoolConfig, Preset, SchemaBuildOptions}; +use crate::preset::{Exposure, PoolConfig, Preset, SchemaBuildOptions}; /// Errors that can occur during preset validation. #[derive(Debug, thiserror::Error)] @@ -32,6 +32,7 @@ pub enum ResolveError { #[derive(Default)] pub struct PresetOverride { pub pg_schemas: Option>, + pub exposure: Option, pub default_role: Option>, pub jwt_secret: Option, pub jwks_url: Option>, @@ -47,6 +48,7 @@ impl std::fmt::Debug for PresetOverride { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("PresetOverride") .field("pg_schemas", &self.pg_schemas) + .field("exposure", &self.exposure) .field("default_role", &self.default_role) .field("jwt_secret", &self.jwt_secret.as_ref().map(|_| "***")) .field("jwks_url", &self.jwks_url) @@ -86,6 +88,9 @@ pub fn merge(mut base: Preset, overrides: &mut [PresetOverride]) -> Preset { if let Some(schemas) = ov.pg_schemas.take() { base.pg_schemas = schemas; } + if let Some(exposure) = ov.exposure.take() { + base.exposure = exposure; + } if let Some(role) = ov.default_role.take() { base.default_role = role; } @@ -161,6 +166,42 @@ mod tests { assert_eq!(merged.pg_schemas, vec!["public", "app"]); } + #[test] + fn merge_overrides_exposure() { + let base = Preset::default(); + assert_eq!(base.exposure, Exposure::All, "baseline"); + let mut overrides = vec![PresetOverride { + exposure: Some(Exposure::ExtensionsOnly), + ..Default::default() + }]; + let merged = merge(base, &mut overrides); + assert_eq!(merged.exposure, Exposure::ExtensionsOnly); + } + + #[test] + fn merge_does_not_widen_exposure_when_a_later_override_is_silent() { + // An override that says nothing about exposure must LEAVE the narrower + // setting alone. If a silent override reset it to the `All` default, + // layering an unrelated preset on top would republish every relation. + let base = Preset::default(); + let mut overrides = vec![ + PresetOverride { + exposure: Some(Exposure::Only(vec!["public.users".into()])), + ..Default::default() + }, + PresetOverride { + pg_schemas: Some(vec!["public".into()]), + ..Default::default() + }, + ]; + let merged = merge(base, &mut overrides); + assert_eq!( + merged.exposure, + Exposure::Only(vec!["public.users".into()]), + "a silent override must not widen the surface", + ); + } + #[test] fn merge_later_override_wins() { let base = Preset::default();