From 5d2fc0e140211ed32a3f6c4963f056e724585624 Mon Sep 17 00:00:00 2001 From: LucaCappelletti94 Date: Thu, 19 Nov 2026 14:55:22 +0100 Subject: [PATCH 1/2] Write OpenFGA DSL from openfga-model --- crates/openfga-language/README.md | 5 +- crates/openfga-language/src/lib.rs | 3 + crates/openfga-language/src/writer.rs | 257 ++++++++++++++++++++++++ crates/openfga-language/tests/writer.rs | 102 ++++++++++ 4 files changed, 365 insertions(+), 2 deletions(-) create mode 100644 crates/openfga-language/src/writer.rs create mode 100644 crates/openfga-language/tests/writer.rs diff --git a/crates/openfga-language/README.md b/crates/openfga-language/README.md index acf607c..6a627a1 100644 --- a/crates/openfga-language/README.md +++ b/crates/openfga-language/README.md @@ -8,11 +8,12 @@ Not published yet, so the crates.io and docs.rs badges resolve after the first release. -Parse [OpenFGA](https://openfga.dev) DSL into `openfga-model` types with `no_std` and `alloc`. +Parse [OpenFGA](https://openfga.dev) DSL into `openfga-model` types and write single-file models as DSL with `no_std` and `alloc`. ```rust let model = openfga_language::parse("model\n schema 1.1\n\ntype user")?; assert_eq!(model.schema_version, "1.1"); assert_eq!(model.type_definitions[0].r#type, "user"); -# Ok::<(), openfga_language::ParseError>(()) +assert_eq!(openfga_language::parse(&openfga_language::write(&model)?)?, model); +# Ok::<(), Box>(()) ``` diff --git a/crates/openfga-language/src/lib.rs b/crates/openfga-language/src/lib.rs index 6a12081..3718d70 100644 --- a/crates/openfga-language/src/lib.rs +++ b/crates/openfga-language/src/lib.rs @@ -4,6 +4,9 @@ extern crate alloc; mod lowering; +mod writer; + +pub use writer::{WriteError, write}; use alloc::string::{String, ToString}; use openfga_model::AuthorizationModel; diff --git a/crates/openfga-language/src/writer.rs b/crates/openfga-language/src/writer.rs new file mode 100644 index 0000000..c16496e --- /dev/null +++ b/crates/openfga-language/src/writer.rs @@ -0,0 +1,257 @@ +use alloc::string::String; +use core::fmt::Write as _; +use openfga_model::{ + AuthorizationModel, RelationReference, Userset, condition_param_type_ref::TypeName, + relation_reference::RelationOrWildcard, userset::Userset as Rewrite, +}; + +/// A model that cannot be represented in the `OpenFGA` DSL. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum WriteError { + /// A relation contains an unsupported rewrite or direct assignment position. + #[error( + "the '{relation_name}' relation definition under the '{type_name}' type is not supported by the OpenFGA DSL syntax yet" + )] + UnsupportedNesting { + /// The enclosing type. + type_name: String, + /// The enclosing relation. + relation_name: String, + }, + /// A condition map key differs from its nested name. + #[error( + "the '{condition_name}' condition has a different nested condition name ('{nested_name}')" + )] + ConditionNameMismatch { + /// The condition map key. + condition_name: String, + /// The nested condition name. + nested_name: String, + }, + /// A collection parameter has no element type. + #[error("the '{parameter_name}' parameter of condition '{condition_name}' has no generic type")] + MissingGenericType { + /// The enclosing condition. + condition_name: String, + /// The collection parameter. + parameter_name: String, + }, +} + +/// Writes a single-file model as `OpenFGA` DSL without source-information comments. +/// +/// # Errors +/// Returns an error for unsupported rewrites, mismatched condition names, or missing collection element types. +pub fn write(model: &AuthorizationModel) -> Result { + let mut output = String::from("model\n schema "); + output.push_str(&model.schema_version); + output.push('\n'); + for definition in &model.type_definitions { + output.push_str("\ntype "); + output.push_str(&definition.r#type); + if !definition.relations.is_empty() { + output.push_str("\n relations"); + } + for (relation_name, rewrite) in &definition.relations { + let restrictions = definition + .metadata + .as_ref() + .and_then(|metadata| metadata.relations.get(relation_name)) + .map_or(&[][..], |metadata| { + metadata.directly_related_user_types.as_slice() + }); + output.push_str("\n define "); + output.push_str(relation_name); + output.push_str(": "); + let mut occurrences = 0; + let result = write_rewrite( + &mut output, + Some(rewrite), + restrictions, + &mut occurrences, + false, + ); + if result.is_err() || (occurrences != 0 && (occurrences != 1 || !first_direct(rewrite))) + { + return Err(WriteError::UnsupportedNesting { + type_name: definition.r#type.clone(), + relation_name: relation_name.clone(), + }); + } + } + output.push('\n'); + } + for (condition_name, condition) in &model.conditions { + if condition_name != &condition.name { + return Err(WriteError::ConditionNameMismatch { + condition_name: condition_name.clone(), + nested_name: condition.name.clone(), + }); + } + output.push_str("\ncondition "); + output.push_str(condition_name); + output.push('('); + for (index, (parameter_name, parameter)) in condition.parameters.iter().enumerate() { + if index != 0 { + output.push_str(", "); + } + output.push_str(parameter_name); + output.push_str(": "); + write_type_name(&mut output, parameter.type_name); + if matches!( + TypeName::try_from(parameter.type_name), + Ok(TypeName::List | TypeName::Map) + ) { + let generic = parameter.generic_types.first().ok_or_else(|| { + WriteError::MissingGenericType { + condition_name: condition_name.clone(), + parameter_name: parameter_name.clone(), + } + })?; + output.push('<'); + write_type_name(&mut output, generic.type_name); + output.push('>'); + } + } + output.push_str(") {\n "); + output.push_str(&condition.expression); + output.push_str("\n}\n"); + } + Ok(output) +} + +fn write_type_name(output: &mut String, number: i32) { + if let Ok(name) = TypeName::try_from(number) { + for character in name.as_str_name().trim_start_matches("TYPE_NAME_").chars() { + output.push(character.to_ascii_lowercase()); + } + } else { + let _ = write!(output, "{number}"); + } +} + +fn is_direct(userset: &Userset) -> bool { + matches!(userset.userset, Some(Rewrite::This(_))) +} + +fn first_direct(userset: &Userset) -> bool { + match userset.userset.as_ref() { + Some(Rewrite::This(_)) => true, + Some(Rewrite::Difference(difference)) => { + difference.base.as_deref().is_some_and(first_direct) + } + Some(Rewrite::Union(children) | Rewrite::Intersection(children)) => { + children.child.iter().any(is_direct) || children.child.first().is_some_and(first_direct) + } + _ => false, + } +} + +fn write_restrictions(output: &mut String, restrictions: &[RelationReference]) { + output.push('['); + for (index, restriction) in restrictions.iter().enumerate() { + if index != 0 { + output.push_str(", "); + } + output.push_str(&restriction.r#type); + match restriction.relation_or_wildcard.as_ref() { + Some(RelationOrWildcard::Wildcard(_)) => output.push_str(":*"), + Some(RelationOrWildcard::Relation(relation)) if !relation.is_empty() => { + output.push('#'); + output.push_str(relation); + } + _ => {} + } + if !restriction.condition.is_empty() { + output.push_str(" with "); + output.push_str(&restriction.condition); + } + } + output.push(']'); +} + +fn write_rewrite( + output: &mut String, + userset: Option<&Userset>, + restrictions: &[RelationReference], + occurrences: &mut usize, + nested: bool, +) -> Result<(), ()> { + let rewrite = userset + .and_then(|userset| userset.userset.as_ref()) + .ok_or(())?; + let parenthesized = nested + && matches!( + rewrite, + Rewrite::Union(_) | Rewrite::Intersection(_) | Rewrite::Difference(_) + ); + if parenthesized { + output.push('('); + } + match rewrite { + Rewrite::This(_) => { + *occurrences += 1; + write_restrictions(output, restrictions); + } + Rewrite::ComputedUserset(computed) => output.push_str(&computed.relation), + Rewrite::TupleToUserset(tuple) => { + output.push_str( + tuple + .computed_userset + .as_ref() + .map_or("", |computed| computed.relation.as_str()), + ); + output.push_str(" from "); + output.push_str( + tuple + .tupleset + .as_ref() + .map_or("", |tupleset| tupleset.relation.as_str()), + ); + } + Rewrite::Difference(difference) => { + write_rewrite( + output, + difference.base.as_deref(), + restrictions, + occurrences, + true, + )?; + output.push_str(" but not "); + write_rewrite( + output, + difference.subtract.as_deref(), + restrictions, + occurrences, + true, + )?; + } + Rewrite::Union(children) | Rewrite::Intersection(children) => { + let separator = if matches!(rewrite, Rewrite::Union(_)) { + " or " + } else { + " and " + }; + let direct_position = children.child.iter().position(is_direct); + let prioritized = direct_position + .into_iter() + .chain((0..children.child.len()).filter(|index| Some(*index) != direct_position)); + for (position, index) in prioritized.enumerate() { + if position != 0 { + output.push_str(separator); + } + write_rewrite( + output, + Some(&children.child[index]), + restrictions, + occurrences, + true, + )?; + } + } + } + if parenthesized { + output.push(')'); + } + Ok(()) +} diff --git a/crates/openfga-language/tests/writer.rs b/crates/openfga-language/tests/writer.rs new file mode 100644 index 0000000..0019cba --- /dev/null +++ b/crates/openfga-language/tests/writer.rs @@ -0,0 +1,102 @@ +//! Model-to-DSL conformance with the upstream transformer. +use openfga_model::AuthorizationModel; +use std::{fs, path::Path}; + +#[test] +fn transformer_corpus() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../conformance/openfga-language/tests/data/transformer"); + let cases = fs::read_dir(root) + .expect("Run git submodule update --init to obtain the conformance corpus"); + let mut count = 0; + for entry in cases { + let directory = entry.unwrap().path(); + if !directory.is_dir() || directory.join("test.skip").exists() { + continue; + } + let expected = fs::read_to_string(directory.join("authorization-model.fga")).unwrap(); + let model: AuthorizationModel = serde_json::from_str( + &fs::read_to_string(directory.join("authorization-model.json")).unwrap(), + ) + .unwrap_or_else(|error| panic!("{} {error}", directory.display())); + let actual = openfga_language::write(&model) + .unwrap_or_else(|error| panic!("{} {error}", directory.display())); + assert_eq!(actual, expected, "{}", directory.display()); + let parsed = openfga_language::parse(&actual) + .unwrap_or_else(|error| panic!("{} {error}", directory.display())); + assert_eq!(parsed, model, "{}", directory.display()); + count += 1; + } + assert_ne!(count, 0, "the transformer corpus holds no cases"); +} + +#[derive(serde::Deserialize)] +struct SyntaxCase { + name: String, + json: String, + #[serde(default)] + error_message: String, +} + +#[test] +fn json_syntax_corpus() { + let source = include_str!( + "../../../conformance/openfga-language/tests/data/json-syntax-transformer-validation-cases.yaml" + ); + let cases: Vec = serde_norway::from_str(source).unwrap(); + assert!(!cases.is_empty(), "the JSON syntax corpus holds no cases"); + for case in cases { + let model: AuthorizationModel = serde_json::from_str(&case.json) + .unwrap_or_else(|error| panic!("{} {error}", case.name)); + let result = openfga_language::write(&model); + if case.error_message.is_empty() { + assert!(result.is_ok(), "{} {result:?}", case.name); + } else { + let error = result.expect_err(&case.name); + assert_eq!(error.to_string(), case.error_message, "{}", case.name); + } + } +} + +#[test] +fn collection_parameter_requires_element_type() { + let mut model = AuthorizationModel::default(); + model.conditions.insert( + "active".into(), + openfga_model::Condition { + name: "active".into(), + parameters: [( + "items".into(), + openfga_model::ConditionParamTypeRef { + type_name: openfga_model::condition_param_type_ref::TypeName::List.into(), + generic_types: Vec::new(), + }, + )] + .into(), + ..Default::default() + }, + ); + assert_eq!( + openfga_language::write(&model), + Err(openfga_language::WriteError::MissingGenericType { + condition_name: "active".into(), + parameter_name: "items".into(), + }), + ); +} + +#[test] +fn condition_name_must_match_map_key() { + let mut model = AuthorizationModel::default(); + model.conditions.insert( + "active".into(), + openfga_model::Condition { + name: "other".into(), + ..Default::default() + }, + ); + assert_eq!( + openfga_language::write(&model).unwrap_err().to_string(), + "the 'active' condition has a different nested condition name ('other')", + ); +} From ff932224af9b25d2ad01312a7aa2f7a3c8b4e5c6 Mon Sep 17 00:00:00 2001 From: LucaCappelletti94 Date: Thu, 19 Nov 2026 15:26:43 +0100 Subject: [PATCH 2/2] Test writing unknown parameter type numbers --- crates/openfga-language/tests/writer.rs | 40 +++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/crates/openfga-language/tests/writer.rs b/crates/openfga-language/tests/writer.rs index 0019cba..1dc9021 100644 --- a/crates/openfga-language/tests/writer.rs +++ b/crates/openfga-language/tests/writer.rs @@ -100,3 +100,43 @@ fn condition_name_must_match_map_key() { "the 'active' condition has a different nested condition name ('other')", ); } + +#[test] +fn unknown_parameter_types_are_written_as_numbers() { + let mut model = AuthorizationModel { + schema_version: "1.1".into(), + ..Default::default() + }; + model.conditions.insert( + "active".into(), + openfga_model::Condition { + name: "active".into(), + expression: "x".into(), + parameters: [ + ( + "x".into(), + openfga_model::ConditionParamTypeRef { + type_name: 99, + generic_types: Vec::new(), + }, + ), + ( + "y".into(), + openfga_model::ConditionParamTypeRef { + type_name: openfga_model::condition_param_type_ref::TypeName::List.into(), + generic_types: vec![openfga_model::ConditionParamTypeRef { + type_name: 42, + generic_types: Vec::new(), + }], + }, + ), + ] + .into(), + ..Default::default() + }, + ); + assert_eq!( + openfga_language::write(&model).unwrap(), + "model\n schema 1.1\n\ncondition active(x: 99, y: list<42>) {\n x\n}\n", + ); +}