diff --git a/docs/followups/4-values.md b/docs/followups/4-values.md new file mode 100644 index 0000000..9d4caab --- /dev/null +++ b/docs/followups/4-values.md @@ -0,0 +1,18 @@ +# Follow-ups for branch 4 — values (review) + +## PR description + +Sets, records, computed entities, `in` over sets and shared sub-expressions (`docs/plans/4-values.md`); after +it, the differential test in `cedar-sql-spec` reports no benign skip on generated inputs. + +## Review findings + +The review (about ninety probe conditions in both hierarchy modes, plus partial-request probes) found no +semantic bug in the generated SQL: `cedar_eq`, the JSON conversions, the `NULL` guards of set and record +literals, the computed-entity subqueries and the `LATERAL` sharing all matched `cedar-policy`. Its one code +finding — join aliases joining attribute path segments with `.`, so that `principal["b.c"]` and +`principal.b.c` collide with a loud SQL error — is fixed in branch 6. + +## Suggested follow-ups + +- Measure the planner's behaviour on the `LATERAL` chain for long policies (Plan 9's benchmarks). diff --git a/docs/plans/4-values.md b/docs/plans/4-values.md new file mode 100644 index 0000000..d6fa482 --- /dev/null +++ b/docs/plans/4-values.md @@ -0,0 +1,53 @@ +# Plan 4 — values: sets, records, computed entities, and shared sub-expressions + +## Goal + +Every construct the type-directed generators produce (without extension types) compiles: sets and records +end to end, entity values that are not row-anchored chains, `in` over sets, and a query whose size stays +linear in the policy. After this branch the differential test in `cedar-sql-spec` asserts that no benign +skip remains. + +## Design + +- **Set and record equality** (`src/dialect.rs`, `src/ddl.rs`): `create_tables` installs the PL/pgSQL helper + `cedar_eq(a jsonb, b jsonb)` (`STRICT`, so an error operand stays `NULL`): arrays compare as sets (each + element of one has an equal element in the other, recursively), objects by key set and values, anything + else by JSON equality. No element ordering is relied on anywhere, so the loader's canonical order is only + for determinism. +- **Set operations** (`src/compile.rs`): `==` on two JSON values is `cedar_eq`; `contains` is an `EXISTS` + over `jsonb_array_elements` with `cedar_eq` against the element (native values converted with `to_jsonb` + after an explicit cast, entities wrapped as `{"e": {"t", "i"}}`); `containsAll` is a double `NOT EXISTS`, + `containsAny` a join; `isEmpty` is `jsonb_array_length = 0`; every one is guarded by a `NULL` check of its + inputs. `Set` and `Record` nodes with computed children build `jsonb_build_array`/`jsonb_build_object` + under a guard, since a `NULL` child would silently become JSON `null`. +- **Computed entities**: an entity value that is not a root-anchored chain (a tag value, the result of an + `if`, a record field) is dereferenced by a scalar subquery on its type's table: `getAttr` is + `(SELECT t.col FROM table t WHERE t.id = v)` (no row is `NULL`, an error), `hasAttr` is `COALESCE((SELECT + t.col IS NOT NULL …), FALSE)` under a guard on `v` (a missing entity is `false`). With a closed hierarchy + table `in` works on any entity value; with the recursive CTE only anchored values are supported. +- **`in` over sets**: the right side may be any JSON set of entities, literal or computed: `EXISTS` over its + elements, each checked for identity or ancestry (dynamic ancestor type and id from the element). +- **Sharing**: `Compiler::share` binds an operand used more than once — the guard of `&&`, `||` and `if`, + an arithmetic result, `in`/tag/set operands — to a `CROSS JOIN LATERAL (SELECT … AS "v") AS "nK"` node, so + each sub-expression appears once and a chain of `n` conjunctions renders in `O(n)`, not `O(2^n)`. +- **Names** (`src/config.rs`): `DatabaseConfiguration::from_schema_shortening_names` shortens over-long + default table, tags table and column names with `ident::shortened` instead of demanding an annotation, for + schemas nobody annotates (generated ones); `from_schema` keeps the README's rule. + +## Files + +`src/{compile,config,dialect,ddl,error}.rs`, `tests/{authorize_pg,config,ddl_golden}.rs`, `tests/golden/*.sql`, +`docs/plans/4-values.md`. + +## Verification + +`cargo test --all-features` with `CEDAR_SQL_PG_URL` set: `tests/authorize_pg.rs` gains set and record +equality, `contains*`, `isEmpty`, set and record literals with computed elements, `if`-computed entities, +tag values dereferenced and used on the left of `in`, computed sets on the right of `in`, and a check that +doubling a conjunction chain at most doubles the query text; the goldens gain the helper function. Then +`cargo clippy --all-targets --all-features -- -D warnings`, `cargo fmt --all --check`, and the +`sql-is-authorized-drt` smoke test in `cedar-sql-spec` with no benign skips. + +## History + +New; the fourth `cedar-sql` branch. diff --git a/src/compile.rs b/src/compile.rs index 985eae7..4ad956d 100644 --- a/src/compile.rs +++ b/src/compile.rs @@ -6,7 +6,9 @@ //! `error && false` is an error), arithmetic is guarded so that no bigint //! overflow reaches Postgres (which would abort the statement), and every //! `EXISTS` is guarded by a `NULL` check of its inputs, since `EXISTS` never -//! yields `NULL` by itself. +//! yields `NULL` by itself. Sets and records are the canonical JSON of +//! [`crate::load::canonical_json`], compared with the +//! [`crate::dialect::CEDAR_EQ`] helper (arrays as sets). //! //! Entity data is fetched by CTEs: one per *root* — an unknown request //! variable, or an entity literal that is dereferenced — with one `LEFT JOIN` @@ -15,12 +17,19 @@ //! path. A referenced attribute that is absent, or whose entity row is //! missing, reads as `NULL`, which is exactly Cedar's error for `getAttr`; //! `hasAttr` is `IS NOT NULL` guarded by the parent value, so that a missing -//! entity gives `false` and an errored parent gives an error. +//! entity gives `false` and an errored parent gives an error. An entity value +//! that is not such a chain (the result of an `if`, a tag, a record field) is +//! dereferenced by a scalar subquery on its type's table. +//! +//! An operand used more than once (the guard of a `CASE`, an arithmetic +//! result) is bound to a `LATERAL` node, so every sub-expression appears once +//! in the query text and nested `&&` chains do not grow exponentially. //! //! [`Compiler::render`] assembles the query: the CTEs, one boolean column per //! policy, and the `FROM (SELECT 1) CROSS JOIN LEFT JOIN -//! ON TRUE` skeleton, which yields exactly one row for a -//! concrete request and one row per candidate entity otherwise. +//! ON TRUE CROSS JOIN LATERAL ` skeleton, which yields +//! exactly one row for a concrete request and one row per candidate entity +//! otherwise. use std::fmt::Write as _; @@ -38,7 +47,7 @@ use crate::config::{ DatabaseConfiguration, HIERARCHY_COLUMNS, SQLType, TAGS_ENTITY_ID_COLUMN, TAGS_TAG_COLUMN, TAGS_VALUE_COLUMN, }; -use crate::dialect::Dialect; +use crate::dialect::{CEDAR_EQ, Dialect}; use crate::ident::{SQLIdentifier, quoted_literal, shortened}; use crate::load::canonical_json; use crate::{Error, Result}; @@ -142,6 +151,8 @@ pub struct Compiler<'a> { request: &'a PartialRequest, roots: IndexMap, ancestors: Vec, + /// Shared sub-expressions, each a `LATERAL` node `nK` with one column `v`. + nodes: Vec, } impl<'a> Compiler<'a> { @@ -159,6 +170,7 @@ impl<'a> Compiler<'a> { request, roots: IndexMap::new(), ancestors: Vec::new(), + nodes: Vec::new(), } } @@ -177,11 +189,7 @@ impl<'a> Compiler<'a> { let kind = match r { Residual::Concrete { value, .. } => return self.value(value, repr), Residual::Error(_) => { - return Ok(Compiled { - sql: format!("NULL::{}", repr.sql_type()), - repr, - anchor: None, - }); + return Ok(plain(format!("NULL::{}", repr.sql_type()), repr)); } Residual::Partial { kind, .. } => kind, }; @@ -192,12 +200,12 @@ impl<'a> Compiler<'a> { return Err(Error::Unsupported("an unknown action or context")); } ResidualKind::And { left, right } => { - let a = self.bool(left)?; + let a = self.shared_bool(left)?; let b = self.bool(right)?; format!("(CASE WHEN {a} IS NULL THEN NULL WHEN {a} THEN {b} ELSE FALSE END)") } ResidualKind::Or { left, right } => { - let a = self.bool(left)?; + let a = self.shared_bool(left)?; let b = self.bool(right)?; format!("(CASE WHEN {a} IS NULL THEN NULL WHEN {a} THEN TRUE ELSE {b} END)") } @@ -206,7 +214,7 @@ impl<'a> Compiler<'a> { then_expr, else_expr, } => { - let c = self.bool(test_expr)?; + let c = self.shared_bool(test_expr)?; let t = self.expr(then_expr)?; let e = self.expr(else_expr)?; if t.repr != repr || e.repr != repr { @@ -223,12 +231,20 @@ impl<'a> Compiler<'a> { let a = self.expr(arg)?; match op { UnaryOp::Not => format!("(NOT {})", a.sql), - UnaryOp::Neg => format!( - "(CASE WHEN {a} = {min} THEN NULL ELSE -{a} END)", - a = a.sql, - min = self.dialect.bigint_literal(i64::MIN) - ), - UnaryOp::IsEmpty => return Err(Error::Unsupported("isEmpty")), + UnaryOp::Neg => { + let a = self.share(a); + format!( + "(CASE WHEN {a} = {min} THEN NULL ELSE -{a} END)", + a = a.sql, + min = self.dialect.bigint_literal(i64::MIN) + ) + } + UnaryOp::IsEmpty => { + if a.repr != Repr::Json { + return Err(Error::Unsupported("isEmpty on a non-set")); + } + format!("(jsonb_array_length({}) = 0)", a.sql) + } } } ResidualKind::BinaryApp { op, arg1, arg2 } => { @@ -262,14 +278,50 @@ impl<'a> Compiler<'a> { ResidualKind::ExtensionFunctionApp { .. } => { return Err(Error::Unsupported("extension functions")); } - ResidualKind::Set(_) => return Err(Error::Unsupported("set expressions")), - ResidualKind::Record(_) => return Err(Error::Unsupported("record expressions")), + ResidualKind::Set(items) => { + let mut elements = Vec::new(); + let mut guards = Vec::new(); + for item in items.iter() { + let c = self.expr(item)?; + let c = self.share(c); + guards.push(format!("{} IS NULL", c.sql)); + elements.push(self.to_json(&c)); + } + if elements.is_empty() { + "'[]'::jsonb".to_owned() + } else { + format!( + "(CASE WHEN {} THEN NULL ELSE jsonb_build_array({}) END)", + guards.join(" OR "), + elements.join(", ") + ) + } + } + ResidualKind::Record(fields) => { + let mut pairs = Vec::new(); + let mut guards = Vec::new(); + for (key, field) in fields.iter() { + let c = self.expr(field)?; + let c = self.share(c); + guards.push(format!("{} IS NULL", c.sql)); + pairs.push(format!("{}, {}", quoted_literal(key)?, self.to_json(&c))); + } + let record = if pairs.is_empty() { + "'{}'::jsonb".to_owned() + } else { + format!("jsonb_build_object({})", pairs.join(", ")) + }; + if guards.is_empty() { + format!("jsonb_build_object('r', {record})") + } else { + format!( + "(CASE WHEN {} THEN NULL ELSE jsonb_build_object('r', {record}) END)", + guards.join(" OR ") + ) + } + } }; - Ok(Compiled { - sql, - repr, - anchor: None, - }) + Ok(plain(sql, repr)) } fn bool(&mut self, r: &Residual) -> Result { @@ -282,6 +334,52 @@ impl<'a> Compiler<'a> { } } + /// A boolean operand that the caller uses more than once. + fn shared_bool(&mut self, r: &Residual) -> Result { + let c = self.expr(r)?; + match c.repr { + Repr::Bool => Ok(self.share(c).sql), + _ => Err(Error::Unsupported( + "a non-boolean operand of a boolean operator", + )), + } + } + + /// Binds `c` to a `LATERAL` node unless it is already a reference or a + /// literal, so that its expression appears once in the query. + fn share(&mut self, c: Compiled) -> Compiled { + let sql = c.sql.trim(); + let is_reference = sql.starts_with('"') && !sql.contains(' '); + let is_literal = + sql.starts_with('\'') || sql == "TRUE" || sql == "FALSE" || sql.starts_with("NULL::"); + if is_reference || is_literal { + return c; + } + let index = self.nodes.len(); + self.nodes.push(c.sql); + Compiled { + sql: format!("\"n{index}\".\"v\""), + repr: c.repr, + anchor: c.anchor, + } + } + + /// `c` in the canonical JSON encoding (`NULL` stays `NULL`). + fn to_json(&self, c: &Compiled) -> String { + match &c.repr { + // Cast explicitly: a bare literal has an unknown type. + Repr::Bool => format!("to_jsonb(({})::boolean)", c.sql), + Repr::Long => format!("to_jsonb(({})::bigint)", c.sql), + Repr::Text => format!("to_jsonb(({})::text)", c.sql), + Repr::Entity(ety) => format!( + "(CASE WHEN {v} IS NULL THEN NULL ELSE jsonb_build_object('e', jsonb_build_object('t', {t}, 'i', {v})) END)", + v = c.sql, + t = quoted_literal(&ety.to_string()).expect("type names have no NUL") + ), + Repr::Json => c.sql.clone(), + } + } + fn value(&mut self, value: &Value, repr: Repr) -> Result { let sql = match (value.value_kind(), &repr) { (ValueKind::Lit(Literal::Bool(b)), Repr::Bool) => { @@ -318,11 +416,7 @@ impl<'a> Compiler<'a> { )); } }; - Ok(Compiled { - sql, - repr, - anchor: None, - }) + Ok(plain(sql, repr)) } fn var(&mut self, root: RootKey, repr: Repr) -> Result { @@ -360,6 +454,14 @@ impl<'a> Compiler<'a> { }); } + fn root_type(&self, anchor: &Anchor) -> EntityType { + match &anchor.root { + RootKey::Principal => self.request.principal_type().clone(), + RootKey::Resource => self.request.resource_type().clone(), + RootKey::Literal(uid) => uid.entity_type().clone(), + } + } + /// The column of `anchor`'s attribute `attr`, registering the joins and /// the exported value. fn anchored_attr( @@ -387,11 +489,11 @@ impl<'a> Compiler<'a> { )) } - fn root_type(&self, anchor: &Anchor) -> EntityType { - match &anchor.root { - RootKey::Principal => self.request.principal_type().clone(), - RootKey::Resource => self.request.resource_type().clone(), - RootKey::Literal(uid) => uid.entity_type().clone(), + /// The table and entity id column of `ety`. + fn table_of(&self, ety: &EntityType) -> Result<(&SQLIdentifier, &SQLIdentifier)> { + match self.config.table_for(ety) { + Some((name, table)) => Ok((name, &table.entity_id_column)), + None => Err(Error::Unsupported("an entity type without a table")), } } @@ -399,33 +501,36 @@ impl<'a> Compiler<'a> { let inner = self.expr(expr)?; match &inner.repr { Repr::Entity(ety) => { - let Some(anchor) = &inner.anchor else { - return Err(Error::Unsupported( - "attribute access on a computed entity value", - )); - }; - let sql = self.anchored_attr(anchor, ety, attr)?; - let anchor = match &repr { - Repr::Entity(_) => { - let mut path = anchor.path.clone(); - path.push(attr.clone()); - Some(Anchor { - root: anchor.root.clone(), - path, - }) - } - _ => None, + let ety = ety.clone(); + if let Some(anchor) = &inner.anchor { + let sql = self.anchored_attr(anchor, &ety, attr)?; + let anchor = match &repr { + Repr::Entity(_) => { + let mut path = anchor.path.clone(); + path.push(attr.clone()); + Some(Anchor { + root: anchor.root.clone(), + path, + }) + } + _ => None, + }; + return Ok(Compiled { sql, repr, anchor }); + } + // A computed entity: one row at most, `NULL` when missing. + let Some(column) = self.config.column_for(&ety, attr).cloned() else { + return Err(Error::Unsupported("an attribute without a column")); }; - Ok(Compiled { sql, repr, anchor }) + let (table, id_column) = self.table_of(&ety)?; + let sql = format!( + "(SELECT t.{column} FROM {table} AS t WHERE t.{id_column} = {})", + inner.sql + ); + Ok(plain(sql, repr)) } Repr::Json => { let field = format!("({} -> 'r' -> {})", inner.sql, quoted_literal(attr)?); - let sql = json_to_repr(&field, &repr); - Ok(Compiled { - sql, - repr, - anchor: None, - }) + Ok(plain(json_to_repr(&field, &repr), repr)) } _ => Err(Error::Unsupported( "attribute access on a non-entity, non-record value", @@ -437,12 +542,11 @@ impl<'a> Compiler<'a> { let inner = self.expr(expr)?; match &inner.repr { Repr::Entity(ety) => { - let Some(anchor) = &inner.anchor else { - return Err(Error::Unsupported("has on a computed entity value")); - }; + let ety = ety.clone(); + let inner = self.share(inner); if self .schema - .get_entity_type(ety) + .get_entity_type(&ety) .is_none_or(|vet| vet.attr(attr).is_none()) { // The attribute is not declared, so no entity of the type has it. @@ -451,10 +555,21 @@ impl<'a> Compiler<'a> { inner.sql )); } - let column = self.anchored_attr(anchor, ety, attr)?; + if let Some(anchor) = &inner.anchor { + let column = self.anchored_attr(anchor, &ety, attr)?; + return Ok(format!( + "(CASE WHEN {} IS NULL THEN NULL ELSE {column} IS NOT NULL END)", + inner.sql + )); + } + let Some(column) = self.config.column_for(&ety, attr).cloned() else { + return Err(Error::Unsupported("an attribute without a column")); + }; + let (table, id_column) = self.table_of(&ety)?; + // No row (a missing entity) is `false`, like an absent attribute. Ok(format!( - "(CASE WHEN {} IS NULL THEN NULL ELSE {column} IS NOT NULL END)", - inner.sql + "(CASE WHEN {v} IS NULL THEN NULL ELSE COALESCE((SELECT t.{column} IS NOT NULL FROM {table} AS t WHERE t.{id_column} = {v}), FALSE) END)", + v = inner.sql )) } Repr::Json => Ok(format!( @@ -483,9 +598,7 @@ impl<'a> Compiler<'a> { (Repr::Entity(t1), Repr::Entity(t2)) if t1 == t2 => { format!("({} = {})", a.sql, b.sql) } - (Repr::Json, Repr::Json) => { - return Err(Error::Unsupported("equality of sets or records")); - } + (Repr::Json, Repr::Json) => format!("{CEDAR_EQ}({}, {})", a.sql, b.sql), // Values of different types are never equal, but an error stays one. _ => format!( "(CASE WHEN {} IS NULL OR {} IS NULL THEN NULL ELSE FALSE END)", @@ -509,14 +622,18 @@ impl<'a> Compiler<'a> { _ => "*", }; // Computed in `numeric`, which cannot overflow, then range-checked. - let r = format!("({}::numeric {sym} {}::numeric)", a.sql, b.sql); + let r = self.share(plain( + format!("({}::numeric {sym} {}::numeric)", a.sql, b.sql), + Repr::Long, + )); format!( "(CASE WHEN {r} BETWEEN {min} AND {max} THEN {r}::bigint ELSE NULL END)", + r = r.sql, min = i64::MIN, max = i64::MAX ) } - BinaryOp::In => return self.in_op(&a, arg2, &b, repr), + BinaryOp::In => return self.in_op(a, b, repr), BinaryOp::HasTag | BinaryOp::GetTag => { let Repr::Entity(ety) = &a.repr else { return Err(Error::Unsupported("tags of a non-entity value")); @@ -527,9 +644,10 @@ impl<'a> Compiler<'a> { let Some((_, table)) = self.config.table_for(ety) else { return Err(Error::Unsupported("tags of an entity type without a table")); }; - let Some(tags) = &table.tags else { + let Some(tags) = table.tags.clone() else { return Err(Error::Unsupported("tags of an entity type without tags")); }; + let (a, b) = (self.share(a), self.share(b)); let lookup = format!( "FROM {} AS t WHERE t.\"{TAGS_ENTITY_ID_COLUMN}\" = {} AND t.\"{TAGS_TAG_COLUMN}\" = {}", tags.table, a.sql, b.sql @@ -556,61 +674,72 @@ impl<'a> Compiler<'a> { format!("(SELECT t.\"{TAGS_VALUE_COLUMN}\" {lookup})") } } - BinaryOp::Contains | BinaryOp::ContainsAll | BinaryOp::ContainsAny => { - return Err(Error::Unsupported("set operations")); + BinaryOp::Contains => { + if a.repr != Repr::Json { + return Err(Error::Unsupported("contains on a non-set")); + } + let (a, b) = (self.share(a), self.share(b)); + let element = self.to_json(&b); + format!( + "(CASE WHEN {a} IS NULL OR {b} IS NULL THEN NULL ELSE EXISTS (SELECT 1 FROM jsonb_array_elements({a}) AS el WHERE {CEDAR_EQ}(el.value, {element})) END)", + a = a.sql, + b = b.sql + ) + } + BinaryOp::ContainsAll | BinaryOp::ContainsAny => { + if a.repr != Repr::Json || b.repr != Repr::Json { + return Err(Error::Unsupported("containsAll/containsAny on non-sets")); + } + let (a, b) = (self.share(a), self.share(b)); + let check = if op == BinaryOp::ContainsAll { + // Every element of `b` has an equal element in `a`. + format!( + "NOT EXISTS (SELECT 1 FROM jsonb_array_elements({b}) AS y WHERE NOT EXISTS (SELECT 1 FROM jsonb_array_elements({a}) AS x WHERE {CEDAR_EQ}(x.value, y.value)))", + a = a.sql, + b = b.sql + ) + } else { + format!( + "EXISTS (SELECT 1 FROM jsonb_array_elements({a}) AS x JOIN jsonb_array_elements({b}) AS y ON {CEDAR_EQ}(x.value, y.value))", + a = a.sql, + b = b.sql + ) + }; + format!( + "(CASE WHEN {} IS NULL OR {} IS NULL THEN NULL ELSE {check} END)", + a.sql, b.sql + ) } }; - Ok(Compiled { - sql, - repr, - anchor: None, - }) + Ok(plain(sql, repr)) } - fn in_op( - &mut self, - a: &Compiled, - arg2: &Residual, - b: &Compiled, - repr: Repr, - ) -> Result { + fn in_op(&mut self, a: Compiled, b: Compiled, repr: Repr) -> Result { let Repr::Entity(t1) = &a.repr else { return Err(Error::Unsupported("in on a non-entity value")); }; let t1 = t1.clone(); + let a = self.share(a); + let b = self.share(b); let sql = match &b.repr { Repr::Entity(t2) => { - let check = self.ancestor_check(a, &t1, &b.sql, t2)?; + let t2 = t2.clone(); + let check = self.ancestor_check(&a, &t1, &b.sql, &t2)?; format!( "(CASE WHEN {} IS NULL OR {} IS NULL THEN NULL ELSE {check} END)", a.sql, b.sql ) } Repr::Json => { - // Only a literal set of entities, whose elements need no guard. - let Residual::Concrete { value, .. } = arg2 else { - return Err(Error::Unsupported("in with a computed set")); - }; - let ValueKind::Set(set) = value.value_kind() else { - return Err(Error::Unsupported("in with a non-set")); - }; - let mut checks = Vec::new(); - for element in set.iter() { - let ValueKind::Lit(Literal::EntityUID(uid)) = element.value_kind() else { - return Err(Error::Unsupported("in with a set of non-entities")); - }; - let id = quoted_literal(uid.eid().as_ref())?; - checks.push(self.ancestor_check(a, &t1, &id, uid.entity_type())?); - } - if checks.is_empty() { - format!("(CASE WHEN {} IS NULL THEN NULL ELSE FALSE END)", a.sql) - } else { - format!( - "(CASE WHEN {} IS NULL THEN NULL ELSE ({}) END)", - a.sql, - checks.join(" OR ") - ) - } + // A set of entities, literal or computed: `a` is in the set or + // has an ancestor in it. + let element_type = "(el.value -> 'e' ->> 't')"; + let element_id = "(el.value -> 'e' ->> 'i')"; + let check = self.ancestor_check_dynamic(&a, &t1, element_type, element_id)?; + format!( + "(CASE WHEN {} IS NULL OR {} IS NULL THEN NULL ELSE EXISTS (SELECT 1 FROM jsonb_array_elements({}) AS el WHERE {check}) END)", + a.sql, b.sql, b.sql + ) } _ => { return Err(Error::Unsupported( @@ -618,11 +747,7 @@ impl<'a> Compiler<'a> { )); } }; - Ok(Compiled { - sql, - repr, - anchor: None, - }) + Ok(plain(sql, repr)) } /// `a in b` for non-NULL `a` (of type `t1`) and `b` (of type `t2`). @@ -638,37 +763,59 @@ impl<'a> Compiler<'a> { } else { "FALSE".to_owned() }; - let ancestor = if self.config.hierarchy_closed { - format!( - "EXISTS (SELECT 1 FROM {} AS h WHERE h.\"{}\" = {} AND h.\"{}\" = {} AND h.\"{}\" = {} AND h.\"{}\" = {b})", + let ancestor = self.ancestor_exists(a, t1, "ed_literal(&t2.to_string())?, b)?; + Ok(format!("({same} OR {ancestor})")) + } + + /// `a in ` for an entity given by SQL expressions for its type + /// and id (an element of a set). + fn ancestor_check_dynamic( + &mut self, + a: &Compiled, + t1: &EntityType, + b_type: &str, + b_id: &str, + ) -> Result { + let same = format!( + "({b_type} = {} AND {b_id} = {})", + quoted_literal(&t1.to_string())?, + a.sql + ); + let ancestor = self.ancestor_exists(a, t1, b_type, b_id)?; + Ok(format!("({same} OR {ancestor})")) + } + + /// Whether the entity `b_type`/`b_id` (SQL expressions) is an ancestor of + /// `a` (of type `t1`). + fn ancestor_exists( + &mut self, + a: &Compiled, + t1: &EntityType, + b_type: &str, + b_id: &str, + ) -> Result { + let [dt, di, at, ai] = HIERARCHY_COLUMNS; + if self.config.hierarchy_closed { + return Ok(format!( + "EXISTS (SELECT 1 FROM {} AS h WHERE h.\"{dt}\" = {} AND h.\"{di}\" = {} AND h.\"{at}\" = {b_type} AND h.\"{ai}\" = {b_id})", self.config.entity_hierarchy_table, - HIERARCHY_COLUMNS[0], quoted_literal(&t1.to_string())?, - HIERARCHY_COLUMNS[1], a.sql, - HIERARCHY_COLUMNS[2], - quoted_literal(&t2.to_string())?, - HIERARCHY_COLUMNS[3], - ) - } else { - let Some(anchor) = &a.anchor else { - return Err(Error::Unsupported( - "in on a computed entity value over a hierarchy table without its closure", - )); - }; - let cte = self.ensure_ancestors(anchor, t1)?; - format!( - "EXISTS (SELECT 1 FROM {cte} AS anc WHERE anc.{ID_COLUMN} = {}.{ID_COLUMN} AND anc.\"{}\" = {} AND anc.\"{}\" = {b})", - root_name(&anchor.root), - HIERARCHY_COLUMNS[2], - quoted_literal(&t2.to_string())?, - HIERARCHY_COLUMNS[3], - ) + )); + } + let Some(anchor) = &a.anchor else { + return Err(Error::Unsupported( + "in on a computed entity value over a hierarchy table without its closure", + )); }; - Ok(format!("({same} OR {ancestor})")) + let cte = self.ensure_ancestors(anchor, t1); + Ok(format!( + "EXISTS (SELECT 1 FROM {cte} AS anc WHERE anc.{ID_COLUMN} = {}.{ID_COLUMN} AND anc.\"{at}\" = {b_type} AND anc.\"{ai}\" = {b_id})", + root_name(&anchor.root), + )) } - fn ensure_ancestors(&mut self, anchor: &Anchor, ety: &EntityType) -> Result { + fn ensure_ancestors(&mut self, anchor: &Anchor, ety: &EntityType) -> SQLIdentifier { let root_type = self.root_type(anchor); self.ensure_root(&anchor.root, &root_type); if !anchor.path.is_empty() { @@ -733,6 +880,12 @@ impl<'a> Compiler<'a> { } } } + for (index, node) in self.nodes.iter().enumerate() { + let _ = write!( + sql, + "\nCROSS JOIN LATERAL (SELECT {node} AS \"v\") AS \"n{index}\"" + ); + } Ok(sql) } @@ -747,7 +900,7 @@ impl<'a> Compiler<'a> { ordered.sort_by_key(|(path, _)| path.len()); for (path, ety) in ordered { let (attr, prefix) = path.split_last().expect("join paths are non-empty"); - let parent_alias = alias_name(key, prefix)?; + let parent_alias = alias_name(key, prefix); let parent_type = if prefix.is_empty() { &root.ety } else { @@ -759,7 +912,7 @@ impl<'a> Compiler<'a> { let Some((joined_table, joined)) = self.config.table_for(ety) else { return Err(Error::Unsupported("an entity type without a table")); }; - let alias = alias_name(key, path)?; + let alias = alias_name(key, path); let _ = write!( joins, "\n LEFT JOIN {joined_table} AS {alias} ON {parent_alias}.{column} = {alias}.{}", @@ -778,7 +931,7 @@ impl<'a> Compiler<'a> { }; select.push(format!( "{}.{column} AS {}", - alias_name(key, prefix)?, + alias_name(key, prefix), value_column(path) )); } @@ -797,7 +950,7 @@ impl<'a> Compiler<'a> { } fn render_ancestors(&self, cte: &AncestorsCte) -> Result { - let name = ancestors_name(&cte.anchor)?; + let name = ancestors_name(&cte.anchor); let root = root_name(&cte.anchor.root); let value = if cte.anchor.path.is_empty() { format!("{root}.{ID_COLUMN}") @@ -821,6 +974,15 @@ impl<'a> Compiler<'a> { } } +/// A compiled expression that is not a row-anchored entity. +fn plain(sql: String, repr: Repr) -> Compiled { + Compiled { + sql, + repr, + anchor: None, + } +} + /// The column every root CTE exports for its entity id. const ID_COLUMN: &str = "\"$id\""; @@ -844,18 +1006,21 @@ fn root_name(root: &RootKey) -> String { } } +fn root_raw_name(root: &RootKey) -> String { + match root { + RootKey::Principal => "principal".to_owned(), + RootKey::Resource => "resource".to_owned(), + RootKey::Literal(uid) => uid.to_string(), + } +} + /// The quoted alias of the join for `path` under `root` (the root itself /// for the empty path). -fn alias_name(root: &RootKey, path: &[SmolStr]) -> Result { +fn alias_name(root: &RootKey, path: &[SmolStr]) -> String { if path.is_empty() { - return Ok(root_name(root)); + return root_name(root); } - let raw = match root { - RootKey::Principal => "principal".to_owned(), - RootKey::Resource => "resource".to_owned(), - RootKey::Literal(uid) => uid.to_string(), - }; - Ok(shortened(&format!("{raw}.{}", path.join("."))).to_string()) + shortened(&format!("{}.{}", root_raw_name(root), path.join("."))).to_string() } /// The quoted CTE column holding the value of an attribute path. @@ -863,16 +1028,11 @@ fn value_column(path: &[SmolStr]) -> String { shortened(&format!("$v:{}", path.join("."))).to_string() } -fn ancestors_name(anchor: &Anchor) -> Result { - let raw = match &anchor.root { - RootKey::Principal => "principal".to_owned(), - RootKey::Resource => "resource".to_owned(), - RootKey::Literal(uid) => uid.to_string(), - }; +fn ancestors_name(anchor: &Anchor) -> SQLIdentifier { let path = if anchor.path.is_empty() { String::new() } else { format!(".{}", anchor.path.join(".")) }; - Ok(shortened(&format!("{raw}{path}$ancestors"))) + shortened(&format!("{}{path}$ancestors", root_raw_name(&anchor.root))) } diff --git a/src/config.rs b/src/config.rs index b4f8934..b15c102 100644 --- a/src/config.rs +++ b/src/config.rs @@ -18,7 +18,7 @@ use serde::{Deserialize, Serialize}; use smol_str::SmolStr; use crate::annotations::{EntityTypeAnnotations, SqlAnnotations}; -use crate::ident::SQLIdentifier; +use crate::ident::{SQLIdentifier, shortened}; use crate::{Error, Result}; /// The default name of the interface column holding the entity id. @@ -223,7 +223,15 @@ impl DatabaseConfiguration { schema: &Schema, annotations: &SqlAnnotations, ) -> Result { - Builder::new(schema.as_ref(), annotations).build() + Builder::new(schema.as_ref(), annotations, false).build() + } + + /// Like [`Self::from_schema`], but a default table, tags table or column + /// name longer than the identifier limit is shortened with a hash + /// (`ident::shortened`) instead of requiring an annotation — for schemas + /// nobody annotates, such as generated ones. + pub fn from_schema_shortening_names(schema: &Schema) -> Result { + Builder::new(schema.as_ref(), &SqlAnnotations::default(), true).build() } /// Parses a schema in the Cedar schema syntax, collecting its annotations. @@ -275,14 +283,30 @@ struct Draft { struct Builder<'a> { schema: &'a ValidatorSchema, annotations: &'a SqlAnnotations, + /// Whether over-long default names are shortened instead of rejected. + shorten: bool, } impl<'a> Builder<'a> { - fn new(schema: &'a ValidatorSchema, annotations: &'a SqlAnnotations) -> Self { + fn new(schema: &'a ValidatorSchema, annotations: &'a SqlAnnotations, shorten: bool) -> Self { Self { schema, annotations, + shorten, + } + } + + /// A default name: `raw` as an identifier, shortened when allowed, else + /// an error telling which annotation to use. + fn default_name(&self, raw: &str, on: &str, annotation: &str) -> Result { + if self.shorten { + return Ok(shortened(raw)); } + SQLIdentifier::new(raw).map_err(|_| { + Error::Schema(format!( + "{on} is not a valid name ({raw:?}); use @{annotation}" + )) + }) } fn build(self) -> Result { @@ -380,11 +404,11 @@ impl<'a> Builder<'a> { let ety = vet.name().clone(); let name = match &ann.table { Some(name) => name.clone(), - None => SQLIdentifier::new(ety.to_string()).map_err(|_| { - Error::Schema(format!( - "the entity type name {ety} is not a valid table name; use @sql_table" - )) - })?, + None => self.default_name( + &ety.to_string(), + &format!("the table name for entity type {ety}"), + crate::annotations::TABLE, + )?, }; if vet.open_attributes() == OpenTag::OpenAttributes { return Err(Error::Unsupported( @@ -398,11 +422,11 @@ impl<'a> Builder<'a> { let attr_ann = ann.attributes.get(attr); let column = match attr_ann.and_then(|a| a.column.clone()) { Some(column) => column, - None => SQLIdentifier::new(attr.as_str()).map_err(|_| { - Error::Schema(format!( - "attribute {attr} of {ety} is not a valid column name; use @sql_column" - )) - })?, + None => self.default_name( + attr, + &format!("the column name for attribute {attr} of {ety}"), + crate::annotations::COLUMN, + )?, }; if let Some(other) = attribute_columns .iter() @@ -474,11 +498,11 @@ impl<'a> Builder<'a> { let (ty, reference) = SQLType::for_cedar_type(tag_ty)?; let table = match &ann.tags_table { Some(table) => table.clone(), - None => name.with_suffix(TAGS_TABLE_SUFFIX).map_err(|_| { - Error::Schema(format!( - "the tags table name for {ety} is too long; use @sql_tags_table" - )) - })?, + None => self.default_name( + &format!("{}{TAGS_TABLE_SUFFIX}", name.as_str()), + &format!("the tags table name for entity type {ety}"), + crate::annotations::TAGS_TABLE, + )?, }; Some((table, ty, reference)) } diff --git a/src/ddl.rs b/src/ddl.rs index 7b4694b..0b47730 100644 --- a/src/ddl.rs +++ b/src/ddl.rs @@ -15,7 +15,7 @@ use crate::ident::{SQLIdentifier, shortened}; /// order and reference cycles do not matter. The foreign keys are deferred /// to the end of the transaction, so rows may be loaded in any order. pub fn create_tables(config: &DatabaseConfiguration, dialect: &dyn Dialect) -> Result> { - let mut statements = Vec::new(); + let mut statements = dialect.helper_functions().0; let mut foreign_keys = Vec::new(); for (name, table) in &config.tables { statements.push(create_entity_table(name, table, dialect)); @@ -68,8 +68,9 @@ pub fn create_tables(config: &DatabaseConfiguration, dialect: &dyn Dialect) -> R Ok(statements) } -/// The statements dropping every table of `config`, if they exist. -pub fn drop_tables(config: &DatabaseConfiguration) -> Vec { +/// The statements dropping every table of `config`, if they exist, and the +/// helper functions. +pub fn drop_tables(config: &DatabaseConfiguration, dialect: &dyn Dialect) -> Vec { let mut names = vec![config.entity_hierarchy_table.clone()]; for (name, table) in config.tables.iter().rev() { if let Some(tags) = &table.tags { @@ -80,6 +81,7 @@ pub fn drop_tables(config: &DatabaseConfiguration) -> Vec { names .into_iter() .map(|name| format!("DROP TABLE IF EXISTS {name} CASCADE")) + .chain(dialect.helper_functions().1) .collect() } diff --git a/src/dialect.rs b/src/dialect.rs index 76f409b..2f19819 100644 --- a/src/dialect.rs +++ b/src/dialect.rs @@ -15,8 +15,17 @@ pub trait Dialect { /// A 64-bit integer literal. `i64::MIN` needs care: as a bare literal /// Postgres parses it as the negation of a too-large number. fn bigint_literal(&self, n: i64) -> String; + /// The statements defining the helper functions the compiled queries call + /// (see [`CEDAR_EQ`]), and the statements dropping them. + fn helper_functions(&self) -> (Vec, Vec); } +/// The name of the helper function comparing two canonical JSON values as +/// Cedar values: arrays as sets (each element of one has an equal element in +/// the other), objects by keys and values, everything else by JSON equality. +/// `STRICT`, so a `NULL` argument (an error) yields `NULL`. +pub const CEDAR_EQ: &str = "cedar_eq"; + /// Postgres 18. #[derive(Debug, Clone, Copy, Default)] pub struct Postgres; @@ -48,4 +57,33 @@ impl Dialect for Postgres { fn bigint_literal(&self, n: i64) -> String { format!("'{n}'::bigint") } + + fn helper_functions(&self) -> (Vec, Vec) { + let create = format!( + r#"CREATE OR REPLACE FUNCTION {CEDAR_EQ}(a jsonb, b jsonb) RETURNS boolean +LANGUAGE plpgsql IMMUTABLE STRICT AS $cedar$ +BEGIN + IF jsonb_typeof(a) = 'array' AND jsonb_typeof(b) = 'array' THEN + RETURN NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements(a) AS x + WHERE NOT EXISTS (SELECT 1 FROM jsonb_array_elements(b) AS y WHERE {CEDAR_EQ}(x.value, y.value))) + AND NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements(b) AS y + WHERE NOT EXISTS (SELECT 1 FROM jsonb_array_elements(a) AS x WHERE {CEDAR_EQ}(x.value, y.value))); + ELSIF jsonb_typeof(a) = 'object' AND jsonb_typeof(b) = 'object' THEN + RETURN (SELECT coalesce(array_agg(k ORDER BY k), '{{}}') FROM jsonb_object_keys(a) AS k) + = (SELECT coalesce(array_agg(k ORDER BY k), '{{}}') FROM jsonb_object_keys(b) AS k) + AND NOT EXISTS ( + SELECT 1 FROM jsonb_each(a) AS e WHERE NOT {CEDAR_EQ}(e.value, b -> e.key)); + ELSE + RETURN a = b; + END IF; +END +$cedar$"# + ); + ( + vec![create], + vec![format!("DROP FUNCTION IF EXISTS {CEDAR_EQ}(jsonb, jsonb)")], + ) + } } diff --git a/src/error.rs b/src/error.rs index 4efea1f..809fae6 100644 --- a/src/error.rs +++ b/src/error.rs @@ -59,6 +59,18 @@ pub enum Error { Provision(String), } +impl Error { + /// Whether the database cancelled the statement (a `statement_timeout`). + pub fn is_timeout(&self) -> bool { + match self { + Error::Database(e) => e + .as_db_error() + .is_some_and(|db| *db.code() == postgres::error::SqlState::QUERY_CANCELED), + _ => false, + } + } +} + /// The server's message when there is one (`postgres::Error`'s own `Display` /// is only "db error"), else the client-side description. fn describe(error: &postgres::Error) -> String { diff --git a/tests/authorize_pg.rs b/tests/authorize_pg.rs index ff57ca5..449b115 100644 --- a/tests/authorize_pg.rs +++ b/tests/authorize_pg.rs @@ -398,8 +398,9 @@ fn records_like_is_arithmetic() { fx.errored(&permit("resource.owner == Doc::\"nope\".owner"), ALICE, D1); fx.clean(&permit("context.ip == \"1.2.3.4\""), ALICE, D1); assert_eq!( - fx.unsupported(&permit("principal.groups == [\"a\"]"), ALICE, D1), - "equality of sets or records" + fx.check(&permit("principal.groups == [\"a\"]"), ALICE, D1) + .decision, + Decision::Deny ); } @@ -490,16 +491,50 @@ fn hierarchy_and_tags() { ); deny(&mut fx, "resource.hasTag(principal.name)", ALICE); fx.errored(&permit("resource.hasTag(User::\"ghost\".name)"), ALICE, D1); - assert_eq!( - fx.unsupported( - &permit( - "resource.hasTag(\"reviewer\") && resource.getTag(\"reviewer\").name == \"Bob\"" - ), - ALICE, - D1 - ), - "attribute access on a computed entity value" + // Computed entities (a tag value) are dereferenced by subqueries. + allow( + &mut fx, + "resource.hasTag(\"reviewer\") && resource.getTag(\"reviewer\").name == \"Bob\"", + ALICE, ); + deny( + &mut fx, + "resource.hasTag(\"reviewer\") && resource.getTag(\"reviewer\") has age", + ALICE, + ); + deny( + &mut fx, + "resource.hasTag(\"reviewer\") && resource.getTag(\"reviewer\") has friend && resource.getTag(\"reviewer\").friend.name == \"x\"", + ALICE, + ); + if closed { + deny( + &mut fx, + "resource.hasTag(\"reviewer\") && resource.getTag(\"reviewer\") in Group::\"admins\"", + ALICE, + ); + allow( + &mut fx, + "resource.hasTag(\"reviewer\") && resource.getTag(\"reviewer\") in User::\"bob\"", + ALICE, + ); + } else { + assert_eq!( + fx.unsupported( + &permit("resource.hasTag(\"reviewer\") && resource.getTag(\"reviewer\") in Group::\"admins\""), + ALICE, + D1 + ), + "in on a computed entity value over a hierarchy table without its closure" + ); + } + // Sets of entities on the right of `in`, literal and computed. + deny(&mut fx, "principal in principal.friends", ALICE); + allow(&mut fx, "User::\"bob\" in principal.friends", ALICE); + deny(&mut fx, "principal in User::\"carol\".friends", ALICE); + deny(&mut fx, "resource in Doc::\"d1\".owner.friends", ALICE); + allow(&mut fx, "resource in [Group::\"admins\"]", ALICE); + fx.errored(&permit("principal in User::\"ghost\".friends"), ALICE, D1); } } @@ -569,3 +604,139 @@ fn decisions() { Err(Error::Validation(_)) )); } + +#[test] +fn sets_and_records() { + let mut fx = Fixture::new(true); + let allow = |fx: &mut Fixture, p: &str, principal: &str| { + assert_eq!( + fx.clean(&permit(p), principal, D1).decision, + Decision::Allow, + "{p} {principal}" + ); + }; + let deny = |fx: &mut Fixture, p: &str, principal: &str| { + assert_eq!( + fx.clean(&permit(p), principal, D1).decision, + Decision::Deny, + "{p} {principal}" + ); + }; + allow(&mut fx, "principal.groups == [\"b\", \"a\"]", ALICE); + deny(&mut fx, "principal.groups == [\"a\"]", ALICE); + allow(&mut fx, "principal.groups == User::\"bob\".groups", BOB); + deny(&mut fx, "principal.groups == User::\"bob\".groups", ALICE); + allow(&mut fx, "principal.groups.contains(\"a\")", ALICE); + deny(&mut fx, "principal.groups.contains(\"z\")", ALICE); + allow(&mut fx, "principal.groups.containsAll([\"a\"])", ALICE); + allow( + &mut fx, + "principal.groups.containsAll(User::\"bob\".groups)", + ALICE, + ); + deny( + &mut fx, + "principal.groups.containsAll([\"a\", \"z\"])", + ALICE, + ); + allow( + &mut fx, + "principal.groups.containsAny([\"z\", \"b\"])", + ALICE, + ); + deny(&mut fx, "principal.groups.containsAny([\"z\"])", ALICE); + allow(&mut fx, "principal.groups.isEmpty()", BOB); + deny(&mut fx, "principal.groups.isEmpty()", ALICE); + allow( + &mut fx, + "[principal.name, \"x\"].contains(\"Alice\")", + ALICE, + ); + allow( + &mut fx, + "[principal.name, \"x\"] == [\"x\", \"Alice\", \"x\"]", + ALICE, + ); + allow(&mut fx, "{a: principal.name}.a == \"Alice\"", ALICE); + allow(&mut fx, "{a: principal.name} == {a: \"Alice\"}", ALICE); + allow( + &mut fx, + "{a: principal.name, s: principal.groups} == {a: \"Alice\", s: [\"a\", \"b\"]}", + ALICE, + ); + allow(&mut fx, "principal.friends == [User::\"bob\"]", ALICE); + allow(&mut fx, "principal.friends.contains(User::\"bob\")", ALICE); + deny( + &mut fx, + "principal.friends.contains(User::\"carol\")", + ALICE, + ); + allow(&mut fx, "principal.profile.pets.contains(3)", ALICE); + allow(&mut fx, "principal.profile.pets == [3, 2, 1]", ALICE); + allow( + &mut fx, + "principal has age && [principal.age, 1].contains(30)", + ALICE, + ); + allow( + &mut fx, + "principal has age && [[principal.age], [1]] == [[1], [30]]", + ALICE, + ); + fx.errored(&permit("User::\"ghost\".groups.contains(\"a\")"), ALICE, D1); + fx.errored(&permit("[User::\"ghost\".name].contains(\"a\")"), ALICE, D1); + fx.errored(&permit("{a: User::\"ghost\".name}.a == \"a\""), ALICE, D1); + fx.errored( + &permit("principal.groups == User::\"ghost\".groups"), + ALICE, + D1, + ); + // Computed entities from `if`. + allow( + &mut fx, + "(if principal.name == \"Alice\" then principal else User::\"bob\").name == \"Alice\"", + ALICE, + ); + allow( + &mut fx, + "(if principal.name == \"Alice\" then principal else User::\"bob\").name == \"Bob\"", + CAROL, + ); + fx.errored( + &permit( + "(if principal.name == \"Alice\" then principal else User::\"ghost\").name == \"Bob\"", + ), + CAROL, + D1, + ); +} + +#[test] +fn sharing_keeps_queries_linear() { + let fx = Fixture::new(true); + let sizes: Vec = [4usize, 8, 16] + .into_iter() + .map(|n| { + let conjuncts = (0..n) + .map(|i| format!("(principal.name == \"{i}\" || principal.admin)")) + .collect::>() + .join(" && "); + let policies = PolicySet::from_str(&permit(&conjuncts)).unwrap(); + let request = fx.request(ALICE, D1); + let authorizer = + SqlAuthorizer::new(&fx.schema, &fx.config, &Postgres, &policies).unwrap(); + let compiled = authorizer + .compile( + &cedar_sql::authorizer::concrete_request(&request, &fx.schema).unwrap(), + &cedar_sql::authorizer::action_entities(&fx.entities, &fx.schema).unwrap(), + ) + .unwrap(); + compiled.sql.unwrap().len() + }) + .collect(); + // Doubling the conjuncts at most doubles the query, plus a constant. + assert!( + sizes[2] - sizes[1] <= 2 * (sizes[1] - sizes[0]) + 64, + "{sizes:?}" + ); +} diff --git a/tests/config.rs b/tests/config.rs index 32c206d..3d121f4 100644 --- a/tests/config.rs +++ b/tests/config.rs @@ -289,6 +289,27 @@ fn json_common_type_annotations() { ); } +#[test] +fn long_default_names() { + let long = "A".repeat(70); + let src = format!( + "entity {long} = {{ {long}: String }} tags String; action a appliesTo {{ principal: [{long}], resource: [{long}] }};" + ); + let e = err(&src); + assert!(e.contains("use @sql_table"), "{e}"); + let (_, schema) = DatabaseConfiguration::from_cedarschema_str( + "entity User; action a appliesTo { principal: [User], resource: [User] };", + ) + .unwrap(); + let _ = schema; + let schema = cedar_policy::Schema::from_cedarschema_str(&src).unwrap().0; + let c = DatabaseConfiguration::from_schema_shortening_names(&schema).unwrap(); + let (name, table) = c.table_for(&long.parse().unwrap()).unwrap(); + assert!(name.as_str().len() <= 63 && name.as_str().starts_with("AAAA")); + assert!(table.tags.as_ref().unwrap().table.as_str().len() <= 63); + assert!(table.attribute_columns[long.as_str()].as_str().len() <= 63); +} + #[test] fn json_schema_annotations() { let (c, _) = DatabaseConfiguration::from_json_str( diff --git a/tests/ddl_golden.rs b/tests/ddl_golden.rs index 583147d..7f7cc0e 100644 --- a/tests/ddl_golden.rs +++ b/tests/ddl_golden.rs @@ -33,7 +33,7 @@ fn check(name: &str) -> Vec { db.execute_batch(statement) .unwrap_or_else(|e| panic!("{statement}\n{e}")); } - for statement in drop_tables(&config) { + for statement in drop_tables(&config, &Postgres) { db.execute_batch(&statement).unwrap(); } db.rollback().unwrap(); diff --git a/tests/golden/kitchen_sink.sql b/tests/golden/kitchen_sink.sql index 6cc747e..9c30d92 100644 --- a/tests/golden/kitchen_sink.sql +++ b/tests/golden/kitchen_sink.sql @@ -1,3 +1,23 @@ +CREATE OR REPLACE FUNCTION cedar_eq(a jsonb, b jsonb) RETURNS boolean +LANGUAGE plpgsql IMMUTABLE STRICT AS $cedar$ +BEGIN + IF jsonb_typeof(a) = 'array' AND jsonb_typeof(b) = 'array' THEN + RETURN NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements(a) AS x + WHERE NOT EXISTS (SELECT 1 FROM jsonb_array_elements(b) AS y WHERE cedar_eq(x.value, y.value))) + AND NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements(b) AS y + WHERE NOT EXISTS (SELECT 1 FROM jsonb_array_elements(a) AS x WHERE cedar_eq(x.value, y.value))); + ELSIF jsonb_typeof(a) = 'object' AND jsonb_typeof(b) = 'object' THEN + RETURN (SELECT coalesce(array_agg(k ORDER BY k), '{}') FROM jsonb_object_keys(a) AS k) + = (SELECT coalesce(array_agg(k ORDER BY k), '{}') FROM jsonb_object_keys(b) AS k) + AND NOT EXISTS ( + SELECT 1 FROM jsonb_each(a) AS e WHERE NOT cedar_eq(e.value, b -> e.key)); + ELSE + RETURN a = b; + END IF; +END +$cedar$; CREATE TABLE "Doc" ( "__entity_id" TEXT NOT NULL, "__entity_type" TEXT NOT NULL GENERATED ALWAYS AS ('Doc') STORED, diff --git a/tests/golden/pk_and_refs.sql b/tests/golden/pk_and_refs.sql index e9ad565..bc45b68 100644 --- a/tests/golden/pk_and_refs.sql +++ b/tests/golden/pk_and_refs.sql @@ -1,3 +1,23 @@ +CREATE OR REPLACE FUNCTION cedar_eq(a jsonb, b jsonb) RETURNS boolean +LANGUAGE plpgsql IMMUTABLE STRICT AS $cedar$ +BEGIN + IF jsonb_typeof(a) = 'array' AND jsonb_typeof(b) = 'array' THEN + RETURN NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements(a) AS x + WHERE NOT EXISTS (SELECT 1 FROM jsonb_array_elements(b) AS y WHERE cedar_eq(x.value, y.value))) + AND NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements(b) AS y + WHERE NOT EXISTS (SELECT 1 FROM jsonb_array_elements(a) AS x WHERE cedar_eq(x.value, y.value))); + ELSIF jsonb_typeof(a) = 'object' AND jsonb_typeof(b) = 'object' THEN + RETURN (SELECT coalesce(array_agg(k ORDER BY k), '{}') FROM jsonb_object_keys(a) AS k) + = (SELECT coalesce(array_agg(k ORDER BY k), '{}') FROM jsonb_object_keys(b) AS k) + AND NOT EXISTS ( + SELECT 1 FROM jsonb_each(a) AS e WHERE NOT cedar_eq(e.value, b -> e.key)); + ELSE + RETURN a = b; + END IF; +END +$cedar$; CREATE TABLE "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaääääääää" ( "__entity_id" TEXT NOT NULL, "__entity_type" TEXT NOT NULL GENERATED ALWAYS AS ('Doc') STORED, diff --git a/tests/golden/readme_annotated.sql b/tests/golden/readme_annotated.sql index c52c114..4ee600d 100644 --- a/tests/golden/readme_annotated.sql +++ b/tests/golden/readme_annotated.sql @@ -1,3 +1,23 @@ +CREATE OR REPLACE FUNCTION cedar_eq(a jsonb, b jsonb) RETURNS boolean +LANGUAGE plpgsql IMMUTABLE STRICT AS $cedar$ +BEGIN + IF jsonb_typeof(a) = 'array' AND jsonb_typeof(b) = 'array' THEN + RETURN NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements(a) AS x + WHERE NOT EXISTS (SELECT 1 FROM jsonb_array_elements(b) AS y WHERE cedar_eq(x.value, y.value))) + AND NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements(b) AS y + WHERE NOT EXISTS (SELECT 1 FROM jsonb_array_elements(a) AS x WHERE cedar_eq(x.value, y.value))); + ELSIF jsonb_typeof(a) = 'object' AND jsonb_typeof(b) = 'object' THEN + RETURN (SELECT coalesce(array_agg(k ORDER BY k), '{}') FROM jsonb_object_keys(a) AS k) + = (SELECT coalesce(array_agg(k ORDER BY k), '{}') FROM jsonb_object_keys(b) AS k) + AND NOT EXISTS ( + SELECT 1 FROM jsonb_each(a) AS e WHERE NOT cedar_eq(e.value, b -> e.key)); + ELSE + RETURN a = b; + END IF; +END +$cedar$; CREATE TABLE "App::User" ( "__entity_id3" TEXT NOT NULL GENERATED ALWAYS AS ("user_id") STORED, "__entity_type2" TEXT NOT NULL GENERATED ALWAYS AS ('App::User') STORED, diff --git a/tests/golden/readme_simple.sql b/tests/golden/readme_simple.sql index f738930..1900cce 100644 --- a/tests/golden/readme_simple.sql +++ b/tests/golden/readme_simple.sql @@ -1,3 +1,23 @@ +CREATE OR REPLACE FUNCTION cedar_eq(a jsonb, b jsonb) RETURNS boolean +LANGUAGE plpgsql IMMUTABLE STRICT AS $cedar$ +BEGIN + IF jsonb_typeof(a) = 'array' AND jsonb_typeof(b) = 'array' THEN + RETURN NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements(a) AS x + WHERE NOT EXISTS (SELECT 1 FROM jsonb_array_elements(b) AS y WHERE cedar_eq(x.value, y.value))) + AND NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements(b) AS y + WHERE NOT EXISTS (SELECT 1 FROM jsonb_array_elements(a) AS x WHERE cedar_eq(x.value, y.value))); + ELSIF jsonb_typeof(a) = 'object' AND jsonb_typeof(b) = 'object' THEN + RETURN (SELECT coalesce(array_agg(k ORDER BY k), '{}') FROM jsonb_object_keys(a) AS k) + = (SELECT coalesce(array_agg(k ORDER BY k), '{}') FROM jsonb_object_keys(b) AS k) + AND NOT EXISTS ( + SELECT 1 FROM jsonb_each(a) AS e WHERE NOT cedar_eq(e.value, b -> e.key)); + ELSE + RETURN a = b; + END IF; +END +$cedar$; CREATE TABLE "documents" ( "__entity_id" TEXT NOT NULL, "__entity_type" TEXT NOT NULL GENERATED ALWAYS AS ('Document') STORED,