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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 127 additions & 0 deletions crates/magna-build/src/gather.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32, &str> = 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);

Expand All @@ -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);
}
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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, &registry, &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, &registry, &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, &registry, &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::<Vec<_>>(),
);
}

#[test]
fn exposure_extensions_only_generates_an_empty_surface() {
let intro = make_introspection();
let registry = make_registry(&intro);

let output = gather(
&intro,
&registry,
&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, &registry, &preset).expect("gather failed");

assert!(
output.resources.is_empty(),
"public.users must not be admitted by an allowlist naming usr.users",
);
}
}
2 changes: 1 addition & 1 deletion crates/magna-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
137 changes: 137 additions & 0 deletions crates/magna-config/src/preset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>),

/// 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
Expand All @@ -121,6 +176,12 @@ pub struct Preset {
/// Postgres schemas to expose in the GraphQL API.
pub pg_schemas: Vec<String>,

/// 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<String>,

Expand Down Expand Up @@ -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(),
Expand All @@ -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)
Expand Down Expand Up @@ -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"));
}
}
Loading
Loading