diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6624ef2..bef4c04 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,7 +24,7 @@ jobs: - run: cargo fmt --all --check - run: cargo run -p codegen --locked -- --check - run: cargo clippy --workspace --all-targets --all-features --locked - - run: cargo build -p openfga-model --target thumbv7em-none-eabihf --locked + - run: cargo build -p openfga-model -p openfga-language --target thumbv7em-none-eabihf --locked - run: cargo doc --no-deps --all-features --locked env: RUSTDOCFLAGS: -D warnings @@ -37,7 +37,7 @@ jobs: with: persist-credentials: false - run: rustup toolchain install 1.88 --profile minimal && rustup default 1.88 - - run: cargo check -p openfga-model --lib --locked + - run: cargo check -p openfga-model -p openfga-language --lib --locked coverage: runs-on: ubuntu-latest @@ -56,8 +56,8 @@ jobs: with: tool: cargo-llvm-cov - run: mkdir -p target/coverage - - run: cargo llvm-cov -p openfga-model --all-targets --all-features --locked --no-report - - run: cargo llvm-cov -p openfga-model --doc --all-features --locked --no-clean --lcov --output-path target/coverage/coverage.lcov + - run: cargo llvm-cov -p openfga-model -p openfga-language --all-targets --all-features --locked --no-report + - run: cargo llvm-cov -p openfga-model -p openfga-language --doc --all-features --locked --no-clean --lcov --output-path target/coverage/coverage.lcov - uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 if: github.actor != 'dependabot[bot]' && (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) with: diff --git a/Cargo.lock b/Cargo.lock index cab037e..9de964b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,15 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + [[package]] name = "bitflags" version = "2.13.2" @@ -29,6 +38,16 @@ version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -74,6 +93,12 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + [[package]] name = "fixedbitset" version = "0.5.9" @@ -231,12 +256,34 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "openfga-language" +version = "0.1.0" +dependencies = [ + "openfga-model", + "pest", + "pest_derive", + "serde", + "serde_json", + "serde_norway", + "thiserror", +] + [[package]] name = "openfga-model" version = "0.1.0" @@ -257,6 +304,59 @@ dependencies = [ "prost-types", ] +[[package]] +name = "pest" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ec53fd1d256900a9a771bf2720d42cef6f8bc91b4e25065fbd291e3e7222576" +dependencies = [ + "memchr", + "pest_stack_guard", + "ucd-trie", +] + +[[package]] +name = "pest_derive" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adcf794fd301ddc20818a6b4de85ed507f4b45300245cec948982e69e12e3bd7" +dependencies = [ + "pest", + "pest_generator", +] + +[[package]] +name = "pest_generator" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3073afae5db334c25dea9fc3e230a4f191e920c1df080cb9c0b37c9ce1dbb41" +dependencies = [ + "pest", + "pest_meta", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "pest_meta" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bc7f614b3742541642af1685faaa910bf6333e3cd3729c2cccd118146a57327" +dependencies = [ + "pest", +] + +[[package]] +name = "pest_stack_guard" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ac6154fd4418b8f0b82532c59c26f303f9ca59a64c883e8ce3971fd82733439" +dependencies = [ + "psm", + "stacker", +] + [[package]] name = "petgraph" version = "0.8.3" @@ -377,6 +477,16 @@ dependencies = [ "thiserror", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "quote" version = "1.0.47" @@ -428,6 +538,12 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "serde" version = "1.0.229" @@ -435,6 +551,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -470,6 +587,38 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_norway" +version = "0.9.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e408f29489b5fd500fab51ff1484fc859bb655f32c671f307dcd733b72e8168c" +dependencies = [ + "indexmap", + "itoa", + "ryu", + "serde", + "unsafe-libyaml-norway", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys", +] + [[package]] name = "syn" version = "2.0.119" @@ -524,6 +673,12 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "ucd-trie" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f20bdbfc9915686faa18fb5bbe8b4552778505defbf9f12289beefbc44092a6" + [[package]] name = "unicode-ident" version = "1.0.27" @@ -536,6 +691,12 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" +[[package]] +name = "unsafe-libyaml-norway" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39abd59bf32521c7f2301b52d05a6a2c975b6003521cbd0c6dc1582f0a22104" + [[package]] name = "windows-link" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index f5e4e78..2fd0f79 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "3" -members = ["codegen", "crates/openfga-model"] +members = ["codegen", "crates/openfga-model", "crates/openfga-language"] [workspace.package] edition = "2024" diff --git a/README.md b/README.md index 7152ee8..bf8126b 100644 --- a/README.md +++ b/README.md @@ -9,5 +9,6 @@ | Crate | What it holds | |---|---| | [`openfga-model`](crates/openfga-model) | The model types generated from `authzmodel.proto`, with protobuf binary and JSON encodings | +| [`openfga-language`](crates/openfga-language) | The OpenFGA DSL parser and model lowering | Conformance tests read the pinned [openfga/language](https://github.com/openfga/language) corpus, so clone with `--recurse-submodules`. diff --git a/crates/openfga-language/Cargo.toml b/crates/openfga-language/Cargo.toml new file mode 100644 index 0000000..d156122 --- /dev/null +++ b/crates/openfga-language/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "openfga-language" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +description = "OpenFGA DSL parser and model lowering for no_std" +readme = "README.md" +documentation = "https://docs.rs/openfga-language" +keywords = ["openfga", "authorization", "zanzibar", "dsl", "no-std"] +categories = ["authentication", "parser-implementations", "no-std"] + +[dependencies] +openfga-model = { version = "0.1.0", path = "../openfga-model" } +pest = { version = "2.8", default-features = false } +pest_derive = { version = "2.8", default-features = false } +thiserror = { version = "2", default-features = false } + +[dev-dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" +serde_norway = "0.9" + +[lints] +workspace = true diff --git a/crates/openfga-language/README.md b/crates/openfga-language/README.md new file mode 100644 index 0000000..acf607c --- /dev/null +++ b/crates/openfga-language/README.md @@ -0,0 +1,18 @@ +# openfga-language + +[![CI](https://github.com/LucaCappelletti94/openfga-rs/actions/workflows/ci.yml/badge.svg)](https://github.com/LucaCappelletti94/openfga-rs/actions/workflows/ci.yml) +[![codecov](https://codecov.io/gh/LucaCappelletti94/openfga-rs/graph/badge.svg)](https://codecov.io/gh/LucaCappelletti94/openfga-rs) +[![crates.io](https://img.shields.io/crates/v/openfga-language.svg)](https://crates.io/crates/openfga-language) +[![docs.rs](https://docs.rs/openfga-language/badge.svg)](https://docs.rs/openfga-language) +[![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/LucaCappelletti94/openfga-rs/blob/main/LICENSE) + +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`. + +```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>(()) +``` diff --git a/crates/openfga-language/src/lib.rs b/crates/openfga-language/src/lib.rs new file mode 100644 index 0000000..6a12081 --- /dev/null +++ b/crates/openfga-language/src/lib.rs @@ -0,0 +1,63 @@ +#![no_std] +#![doc = include_str!("../README.md")] + +extern crate alloc; + +mod lowering; + +use alloc::string::{String, ToString}; +use openfga_model::AuthorizationModel; +use pest::{Parser, error::LineColLocation}; + +mod grammar { + #[derive(pest_derive::Parser)] + #[grammar = "openfga.pest"] + pub(super) struct DslParser; +} + +use grammar::{DslParser, Rule}; + +/// A DSL syntax or transformation error. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("line {line}, column {column}: {message}")] +pub struct ParseError { + /// One-based source line. + pub line: usize, + /// One-based source column. + pub column: usize, + /// Diagnostic description. + pub message: String, +} + +/// Parses an `OpenFGA` DSL model or module into protobuf model types. +/// +/// # Errors +/// Returns an error for invalid syntax or duplicate relation, condition, parameter, or extension declarations. +pub fn parse(dsl: &str) -> Result { + let mut cleaned = String::with_capacity(dsl.len()); + for (index, line) in dsl.split('\n').enumerate() { + if index != 0 { + cleaned.push('\n'); + } + if !line.trim_start_matches(' ').starts_with('#') { + cleaned.push_str( + line.split(" #") + .next() + .unwrap_or_default() + .trim_end_matches(' '), + ); + } + } + let source = cleaned.trim_end_matches('\n'); + let pairs = DslParser::parse(Rule::main, source).map_err(|error| { + let (line, column) = match error.line_col { + LineColLocation::Pos(position) | LineColLocation::Span(position, _) => position, + }; + ParseError { + line, + column, + message: error.variant.message().to_string(), + } + })?; + lowering::lower(pairs) +} diff --git a/crates/openfga-language/src/lowering.rs b/crates/openfga-language/src/lowering.rs new file mode 100644 index 0000000..90c1249 --- /dev/null +++ b/crates/openfga-language/src/lowering.rs @@ -0,0 +1,301 @@ +use crate::{ParseError, Rule}; +use alloc::{ + boxed::Box, + collections::BTreeSet, + format, + string::{String, ToString}, + vec::Vec, +}; +use openfga_model::{ + AuthorizationModel, Condition, ConditionMetadata, ConditionParamTypeRef, Difference, + DirectUserset, Metadata, ObjectRelation, RelationMetadata, RelationReference, TupleToUserset, + TypeDefinition, Userset, Usersets, Wildcard, condition_param_type_ref::TypeName, + relation_reference::RelationOrWildcard, userset::Userset as Rewrite, +}; +use pest::iterators::{Pair, Pairs}; + +pub(super) fn lower(pairs: Pairs<'_, Rule>) -> Result { + let mut model = AuthorizationModel::default(); + let mut module = String::new(); + let mut extensions = BTreeSet::new(); + for pair in pairs.flat_map(Pair::into_inner) { + match pair.as_rule() { + Rule::model_header => { + model.schema_version = tokens(pair).next().unwrap().as_str().to_string(); + } + Rule::module_header => { + module = pair.into_inner().next().unwrap().as_str().to_string(); + } + Rule::type_def => { + model + .type_definitions + .push(lower_type(pair, &module, &mut extensions)?); + } + Rule::condition => { + let position = tokens(pair.clone()) + .next() + .unwrap() + .into_inner() + .next() + .unwrap(); + let condition = lower_condition(pair, &module)?; + if model.conditions.contains_key(&condition.name) { + return Err(error( + &position, + format!( + "condition '{}' is already defined in the model", + condition.name + ), + )); + } + model.conditions.insert(condition.name.clone(), condition); + } + _ => {} + } + } + Ok(model) +} + +fn tokens(pair: Pair<'_, Rule>) -> impl Iterator> { + pair.into_inner() + .filter(|token| token.as_rule() != Rule::newline) +} + +fn error(pair: &Pair<'_, Rule>, message: String) -> ParseError { + let (line, column) = pair.as_span().start_pos().line_col(); + ParseError { + line, + column, + message, + } +} + +fn lower_type( + pair: Pair<'_, Rule>, + module: &str, + extensions: &mut BTreeSet, +) -> Result { + let mut children = tokens(pair); + let first = children.next().unwrap(); + let extension = first.as_rule() == Rule::extend; + let name = if extension { + children.next().unwrap() + } else { + first + }; + if extension && module.is_empty() { + return Err(error( + &name, + "extend can only be used in a modular model".to_string(), + )); + } + if extension && !extensions.insert(name.as_str().to_string()) { + return Err(error( + &name, + format!("'{}' is already extended in file.", name.as_str()), + )); + } + let mut definition = TypeDefinition { + r#type: name.as_str().to_string(), + ..TypeDefinition::default() + }; + let mut metadata = Metadata { + module: module.to_string(), + ..Metadata::default() + }; + for declaration in children { + let mut parts = tokens(declaration); + let relation = parts.next().unwrap(); + let mut restrictions = Vec::new(); + let rewrite = lower_rewrite(parts.next().unwrap(), &mut restrictions); + if definition.relations.contains_key(relation.as_str()) { + return Err(error( + &relation, + format!( + "'{}' is already defined in '{}'", + relation.as_str(), + definition.r#type + ), + )); + } + definition + .relations + .insert(relation.as_str().to_string(), rewrite); + metadata.relations.insert( + relation.as_str().to_string(), + RelationMetadata { + directly_related_user_types: restrictions, + module: if extension { + module.to_string() + } else { + String::new() + }, + ..RelationMetadata::default() + }, + ); + } + if !module.is_empty() || !metadata.relations.is_empty() { + definition.metadata = Some(metadata); + } + Ok(definition) +} + +fn lower_rewrite(pair: Pair<'_, Rule>, restrictions: &mut Vec) -> Userset { + let rewrite = match pair.as_rule() { + Rule::direct_assignment => { + restrictions.clear(); + restrictions.extend(pair.into_inner().map(lower_restriction)); + Rewrite::This(DirectUserset {}) + } + Rule::rewrite => { + let mut names = pair.into_inner(); + let computed = ObjectRelation { + relation: names.next().unwrap().as_str().to_string(), + ..ObjectRelation::default() + }; + if let Some(tupleset) = names.next() { + Rewrite::TupleToUserset(TupleToUserset { + tupleset: Some(ObjectRelation { + relation: tupleset.as_str().to_string(), + ..ObjectRelation::default() + }), + computed_userset: Some(computed), + }) + } else { + Rewrite::ComputedUserset(computed) + } + } + Rule::recurse | Rule::recurse_no_direct => { + return lower_rewrite(pair.into_inner().next().unwrap(), restrictions); + } + rule => { + assert!(matches!( + rule, + Rule::relation_def | Rule::relation_def_no_direct + )); + let mut parts = pair.into_inner(); + let first = lower_rewrite(parts.next().unwrap(), restrictions); + let Some(partials) = parts.next() else { + return first; + }; + let mut parts = partials.into_inner(); + let operator = parts.next().unwrap().as_rule(); + let mut children = Vec::new(); + children.push(first); + for part in parts { + if !matches!(part.as_rule(), Rule::and | Rule::or | Rule::but_not) { + children.push(lower_rewrite(part, restrictions)); + } + } + match operator { + Rule::or => Rewrite::Union(Usersets { child: children }), + Rule::and => Rewrite::Intersection(Usersets { child: children }), + operator => { + assert_eq!(operator, Rule::but_not); + let mut children = children.into_iter(); + Rewrite::Difference(Box::new(Difference { + base: children.next().map(Box::new), + subtract: children.next().map(Box::new), + })) + } + } + } + }; + Userset { + userset: Some(rewrite), + } +} + +fn lower_restriction(pair: Pair<'_, Rule>) -> RelationReference { + let mut parts = tokens(pair); + let mut base = parts.next().unwrap().into_inner(); + let mut reference = RelationReference { + r#type: base.next().unwrap().as_str().to_string(), + ..RelationReference::default() + }; + if let Some(suffix) = base.next() { + reference.relation_or_wildcard = Some(if suffix.as_rule() == Rule::wildcard { + RelationOrWildcard::Wildcard(Wildcard {}) + } else { + RelationOrWildcard::Relation(suffix.into_inner().next().unwrap().as_str().to_string()) + }); + } + if let Some(condition) = parts.next() { + reference.condition = condition.as_str().to_string(); + } + reference +} + +fn lower_condition(pair: Pair<'_, Rule>, module: &str) -> Result { + let mut parts = tokens(pair); + let mut signature = parts.next().unwrap().into_inner(); + let mut condition = Condition { + name: signature.next().unwrap().as_str().to_string(), + ..Condition::default() + }; + if !module.is_empty() { + condition.metadata = Some(ConditionMetadata { + module: module.to_string(), + ..ConditionMetadata::default() + }); + } + for part in signature { + let mut parameter = part.into_inner(); + let name = parameter.next().unwrap(); + if condition.parameters.contains_key(name.as_str()) { + return Err(error( + &name, + format!( + "parameter '{}' is already defined in the condition '{}'", + name.as_str(), + condition.name + ), + )); + } + let mut types = parameter.next().unwrap().into_inner(); + let outer = types.next().unwrap(); + condition.parameters.insert( + name.as_str().to_string(), + ConditionParamTypeRef { + type_name: type_number(outer.as_str()), + generic_types: types + .map(|generic| ConditionParamTypeRef { + type_name: type_number(generic.as_str()), + generic_types: Vec::new(), + }) + .collect(), + }, + ); + } + let expression = parts.next().unwrap(); + for token in expression.into_inner() { + condition.expression.push_str(token.as_str()); + } + condition + .expression + .truncate(condition.expression.trim_end_matches('\n').len()); + Ok(condition) +} + +/// Parameter types the grammar accepts, in `TypeName` order. +const PARAMETER_TYPES: [TypeName; 10] = [ + TypeName::Bool, + TypeName::String, + TypeName::Int, + TypeName::Uint, + TypeName::Double, + TypeName::Duration, + TypeName::Timestamp, + TypeName::Map, + TypeName::List, + TypeName::Ipaddress, +]; + +/// Maps a grammar parameter type keyword to its `TypeName` number. +fn type_number(name: &str) -> i32 { + PARAMETER_TYPES + .into_iter() + .find(|type_name| type_name.as_str_name()["TYPE_NAME_".len()..].eq_ignore_ascii_case(name)) + .expect("the grammar accepts only known parameter types") + .into() +} diff --git a/crates/openfga-language/src/openfga.pest b/crates/openfga-language/src/openfga.pest new file mode 100644 index 0000000..a141a80 --- /dev/null +++ b/crates/openfga-language/src/openfga.pest @@ -0,0 +1,159 @@ +// OpenFGALexer.HASH +hash = _{ "#" } +// OpenFGALexer.COLON +colon = _{ ":" } +// OpenFGALexer.COMMA +comma = _{ "," } +// OpenFGALexer.AND +and = { "and" ~ !identifier_tail } +// OpenFGALexer.OR +or = { "or" ~ !identifier_tail } +// OpenFGALexer.BUT_NOT +but_not = { "but not" ~ !identifier_tail } +// OpenFGALexer.FROM +from = _{ "from" ~ !identifier_tail } +// OpenFGALexer.MODULE +module = _{ "module" ~ !identifier_tail } +// OpenFGALexer.MODEL +model = _{ "model" ~ !identifier_tail } +// OpenFGALexer.SCHEMA +schema = _{ "schema" ~ !identifier_tail } +// OpenFGALexer.SCHEMA_VERSION +schema_version = @{ ASCII_DIGIT+ ~ "." ~ ASCII_DIGIT+ } +// OpenFGALexer.EXTEND +extend = { "extend" ~ !identifier_tail } +// OpenFGALexer.TYPE +type_keyword = _{ "type" ~ !identifier_tail } +// OpenFGALexer.CONDITION +condition_keyword = _{ "condition" ~ !identifier_tail } +// OpenFGALexer.RELATIONS +relations = _{ "relations" ~ !identifier_tail } +// OpenFGALexer.RELATION +relation = _{ "relation" ~ !identifier_tail } +// OpenFGALexer.DEFINE +define = _{ "define" ~ !identifier_tail } +// OpenFGALexer.KEYWORD_WITH +with = _{ "with" ~ !identifier_tail } +// OpenFGALexer.EQUALS, NOT_EQUALS, IN, LESS, LESS_EQUALS, GREATER_EQUALS, GREATER, LOGICAL_AND, LOGICAL_OR +cel_operator = _{ "==" | "!=" | "in" ~ !identifier_tail | "<=" | ">=" | "<" | ">" | "&&" | "||" } +// OpenFGALexer.LBRACKET, RPRACKET, LBRACE, RBRACE, LPAREN, RPAREN, DOT, MINUS, EXCLAM, QUESTIONMARK, PLUS, STAR, SLASH, PERCENT +punctuation = _{ "[" | "]" | "{" | "(" | ")" | "." | "-" | "!" | "?" | "+" | "*" | "/" | "%" | ":" | "," | "#" } +// OpenFGALexer.CEL_TRUE, CEL_FALSE, NUL +cel_literal = _{ ("true" | "false" | "null") ~ !identifier_tail } +// OpenFGALexer.BACKSLASH +backslash = _{ "\\" } +// OpenFGALexer.EXPONENT +exponent = _{ ("e" | "E") ~ ("+" | "-")? ~ ASCII_DIGIT+ } +// OpenFGALexer.RAW +raw = _{ "r" | "R" } +// OpenFGALexer.ESC_SEQ +escape = _{ escape_char | escape_byte | escape_unicode | escape_octal } +// OpenFGALexer.ESC_CHAR_SEQ +escape_char = _{ backslash ~ ("a" | "b" | "f" | "n" | "r" | "t" | "v" | "\"" | "'" | "\\" | "?" | "`") } +// OpenFGALexer.ESC_OCT_SEQ +escape_octal = _{ backslash ~ '0'..'3' ~ '0'..'7' ~ '0'..'7' } +// OpenFGALexer.ESC_BYTE_SEQ +escape_byte = _{ backslash ~ ("x" | "X") ~ ASCII_HEX_DIGIT{2} } +// OpenFGALexer.ESC_UNI_SEQ +escape_unicode = _{ backslash ~ ("u" ~ ASCII_HEX_DIGIT{4} | "U" ~ ASCII_HEX_DIGIT{8}) } +// OpenFGALexer.WHITESPACE +space = _{ ("\t" | " " | "\u{000C}")+ } +// OpenFGALexer.CEL_COMMENT hidden channel applies between default-mode tokens. +COMMENT = _{ "//" ~ (!"\n" ~ ANY)* } +// OpenFGALexer.NUM_FLOAT +num_float = _{ ASCII_DIGIT+ ~ "." ~ ASCII_DIGIT+ ~ exponent? | ASCII_DIGIT+ ~ exponent | "." ~ ASCII_DIGIT+ ~ exponent? } +// OpenFGALexer.NUM_INT +num_int = _{ "0x" ~ ASCII_HEX_DIGIT+ | ASCII_DIGIT+ } +// OpenFGALexer.NUM_UINT +num_uint = _{ num_int ~ ("u" | "U") } +// OpenFGALexer.STRING +string = _{ raw ~ ("\"\"\"" ~ (!"\"\"\"" ~ ANY)* ~ "\"\"\"" | "'''" ~ (!"'''" ~ ANY)* ~ "'''" | "\"" ~ (!("\"" | "\n" | "\r") ~ ANY)* ~ "\"" | "'" ~ (!("'" | "\n" | "\r") ~ ANY)* ~ "'") | "\"\"\"" ~ (escape | !("\\" | "\"\"\"") ~ ANY)* ~ "\"\"\"" | "'''" ~ (escape | !("\\" | "'''") ~ ANY)* ~ "'''" | "\"" ~ (escape | !("\\" | "\"" | "\n" | "\r") ~ ANY)* ~ "\"" | "'" ~ (escape | !("\\" | "'" | "\n" | "\r") ~ ANY)* ~ "'" } +// OpenFGALexer.BYTES +bytes = _{ ("b" | "B") ~ string } +// OpenFGALexer.DOLLAR_EXPRESSION +dollar_expression = @{ "$expression" } +// OpenFGALexer.IDENTIFIER +identifier_token = @{ (ASCII_ALPHA | "_") ~ identifier_tail* } +// OpenFGALexer.IDENTIFIER continuation. +identifier_tail = _{ ASCII_ALPHA | ASCII_DIGIT | "_" | "-" } +// OpenFGALexer.EXTENDED_IDENTIFIER +extended_token = @{ (ASCII_ALPHA | "_") ~ (("/" | "." | "-")? ~ (ASCII_ALPHA | ASCII_DIGIT | "_")+)* } +// OpenFGALexer.NEWLINE +newline = @{ space? ~ ("\r\n" | "\n" | "\r" | "\u{000C}") ~ space? ~ newline? } +// OpenFGALexer.CONDITION_DEF_END +condition_end = _{ ")" } +// OpenFGALexer.CONDITION_PARAM_CONTAINER +container = @{ ("map" | "list") ~ !identifier_tail } +// OpenFGALexer.CONDITION_PARAM_TYPE +primitive = @{ ("bool" | "string" | "int" | "uint" | "double" | "duration" | "timestamp" | "ipaddress") ~ !identifier_tail } +// OpenFGALexer.CONDITION_PARAM_TYPE_LESS, CONDITION_PARAM_TYPE_GREATER +parameter_generic = _{ "<" ~ primitive ~ ">" } +// OpenFGALexer.CONDITION_OPEN, CONDITION_COLON, CONDITION_COMMA, CONDITION_WS are literal delimiters and space below. +// OpenFGALexer.CONDITION_NAME +condition_identifier = @{ !(container | primitive) ~ identifier_token } +// OpenFGAParser.main +main = { SOI ~ space? ~ newline? ~ (model_header | module_header) ~ type_def* ~ condition* ~ newline? ~ EOI } +// OpenFGAParser.modelHeader +model_header = { (multi_line_comment ~ newline)? ~ model ~ newline ~ schema ~ space ~ schema_version ~ space? } +// OpenFGAParser.moduleHeader +module_header = { (multi_line_comment ~ newline)? ~ module ~ space ~ identifier ~ space? } +// OpenFGAParser.typeDefs is represented by type_def* in main. +// OpenFGAParser.typeDef +type_def = { (newline ~ multi_line_comment)? ~ newline ~ (extend ~ space)? ~ type_keyword ~ space ~ extended_identifier ~ (newline ~ relations ~ relation_declaration+)? } +// OpenFGAParser.relationDeclaration +relation_declaration = { (newline ~ multi_line_comment)? ~ newline ~ define ~ space ~ relation_name ~ space? ~ colon ~ space? ~ relation_def } +// OpenFGAParser.relationName +relation_name = { extended_identifier } +// OpenFGAParser.relationDef +relation_def = { (direct_assignment | rewrite | recurse) ~ partials? } +// OpenFGAParser.relationDefNoDirect +relation_def_no_direct = { (rewrite | recurse_no_direct) ~ partials? } +// OpenFGAParser.relationDefPartials +partials = { (space ~ or ~ space ~ (rewrite | recurse_no_direct))+ | (space ~ and ~ space ~ (rewrite | recurse_no_direct))+ | space ~ but_not ~ space ~ (rewrite | recurse_no_direct) } +// OpenFGAParser.relationRecurse +recurse = { "(" ~ space? ~ (relation_def | recurse_no_direct) ~ space? ~ ")" } +// OpenFGAParser.relationRecurseNoDirect +recurse_no_direct = { "(" ~ space? ~ (relation_def_no_direct | recurse_no_direct) ~ space? ~ ")" } +// OpenFGAParser.relationDefDirectAssignment +direct_assignment = { "[" ~ space? ~ restriction ~ space? ~ (comma ~ space? ~ restriction ~ space?)* ~ "]" } +// OpenFGAParser.relationDefRewrite +rewrite = { extended_identifier ~ (space ~ from ~ space ~ extended_identifier)? } +// OpenFGAParser.relationDefTypeRestriction +restriction = { newline? ~ restriction_base ~ (space ~ with ~ space ~ (condition_name | dollar_expression))? ~ newline? } +// OpenFGAParser.relationDefTypeRestrictionBase +restriction_base = { extended_identifier ~ (wildcard | relation_restriction)? } +// OpenFGAParser.relationDefTypeRestrictionBase wildcard branch. +wildcard = { ":*" } +// OpenFGAParser.relationDefTypeRestrictionBase relation branch. +relation_restriction = { hash ~ extended_identifier } +// OpenFGAParser.conditions is represented by condition* in main. +// OpenFGAParser.condition +condition = { (newline ~ multi_line_comment)? ~ newline ~ condition_signature ~ space? ~ "{" ~ newline? ~ space? ~ condition_expression ~ "}" } +// OpenFGAParser.condition parameter signature uses CONDITION_DEF without the hidden comment channel. +condition_signature = ${ condition_keyword ~ space ~ condition_identifier ~ space? ~ "(" ~ space? ~ condition_parameter ~ space? ~ (comma ~ space? ~ condition_parameter ~ space?)* ~ condition_end } +// OpenFGAParser.conditionName in default lexer mode. +condition_name = @{ !reserved ~ identifier_token } +// OpenFGAParser.conditionParameter (CONDITION_DEF mode has no newline token). +condition_parameter = { parameter_name ~ space? ~ colon ~ space? ~ parameter_type } +// OpenFGAParser.parameterName +parameter_name = { condition_identifier } +// OpenFGAParser.parameterType +parameter_type = { primitive | container ~ parameter_generic } +// OpenFGAParser.multiLineComment +multi_line_comment = _{ hash ~ (!newline ~ ANY)* ~ (newline ~ multi_line_comment)? } +// OpenFGAParser.identifier +identifier = @{ !(reserved_exclusive ~ !identifier_tail) ~ identifier_token } +// OpenFGAParser.identifier excluded default-mode keywords. +reserved_exclusive = _{ "and" | "or" | "but not" | "from" | "condition" | "relations" | "define" | "with" | "in" | "true" | "false" | "null" } +// OpenFGAParser.conditionName excludes all default-mode keywords. +reserved = _{ (reserved_exclusive | "model" | "schema" | "type" | "relation" | "module" | "extend") ~ !identifier_tail } +// OpenFGAParser.extended_identifier gives the longest extended token priority. +extended_identifier = @{ &(identifier_token ~ ("/" | ".")) ~ extended_token | identifier } +// OpenFGAParser.conditionExpression accepts default-mode tokens except RBRACE. +condition_expression = { expression_token* } +// OpenFGAParser.conditionExpression token alternatives, including its complement branch. +expression_token = @{ expression_condition | !condition_mode_start ~ (bytes | string | num_float | num_uint | num_int | extended_token | cel_operator | cel_literal | punctuation | dollar_expression | newline | space) } +// OpenFGALexer.CONDITION pushes CONDITION_DEF even inside conditionExpression. +condition_mode_start = _{ "condition" ~ !identifier_tail ~ !(("/" | ".") ~ (ASCII_ALPHA | ASCII_DIGIT | "_")) } +// OpenFGALexer.CONDITION_DEF accepts only its tokens until CONDITION_DEF_END. +expression_condition = _{ condition_mode_start ~ (identifier_token | space | "<" | ">" | "(" | ":" | ",")* ~ ")" } diff --git a/crates/openfga-language/tests/syntax.rs b/crates/openfga-language/tests/syntax.rs new file mode 100644 index 0000000..a8f233f --- /dev/null +++ b/crates/openfga-language/tests/syntax.rs @@ -0,0 +1,28 @@ +//! Upstream syntax conformance. +use serde::Deserialize; + +#[derive(Deserialize)] +struct Case { + name: String, + dsl: String, + #[serde(default)] + expected_errors: Vec, +} + +#[test] +fn syntax_corpus() { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../conformance/openfga-language/tests/data/dsl-syntax-validation-cases.yaml"); + let source = std::fs::read_to_string(path) + .expect("Run git submodule update --init to obtain the conformance corpus"); + let cases: Vec = serde_norway::from_str(&source).unwrap(); + for case in cases { + let result = openfga_language::parse(&case.dsl); + assert_eq!( + result.is_err(), + !case.expected_errors.is_empty(), + "{} {result:?}", + case.name + ); + } +} diff --git a/crates/openfga-language/tests/transformer.rs b/crates/openfga-language/tests/transformer.rs new file mode 100644 index 0000000..8b52343 --- /dev/null +++ b/crates/openfga-language/tests/transformer.rs @@ -0,0 +1,82 @@ +//! Upstream transformer conformance. +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"); + for entry in cases { + let directory = entry.unwrap().path(); + if !directory.is_dir() || directory.join("test.skip").exists() { + continue; + } + let source = fs::read_to_string(directory.join("authorization-model.fga")).unwrap(); + let expected: AuthorizationModel = serde_json::from_str( + &fs::read_to_string(directory.join("authorization-model.json")).unwrap(), + ) + .unwrap(); + let actual = openfga_language::parse(&source) + .unwrap_or_else(|error| panic!("{} {error}", directory.display())); + assert_eq!(actual, expected, "{}", directory.display()); + } +} + +#[test] +fn module_metadata_and_inline_conditions() { + let source = "module access\n\ + type user\n\ + extend type document\n\ + relations\n\ + define order: [user with $expression]\n\ + condition active(value: bool) { value }"; + let expected: AuthorizationModel = serde_json::from_str( + r#"{ + "type_definitions": [ + {"type": "user", "metadata": {"module": "access"}}, + {"type": "document", "relations": {"order": {"this": {}}}, + "metadata": {"module": "access", "relations": {"order": { + "module": "access", + "directly_related_user_types": [{"type": "user", "condition": "$expression"}] + }}}} + ], + "conditions": {"active": {"name": "active", "expression": "value ", + "parameters": {"value": {"type_name": "TYPE_NAME_BOOL"}}, + "metadata": {"module": "access"} + }} + }"#, + ) + .unwrap(); + assert_eq!(openfga_language::parse(source).unwrap(), expected); +} + +#[test] +fn condition_expression_preserves_visible_tokens() { + let source = "model\n schema 1.1\n\ + condition active(value: string) {\n value == \"//{}\" // hidden\n && value != \"\"\n}"; + let model = openfga_language::parse(source).unwrap(); + assert_eq!( + model.conditions["active"].expression, + "value == \"//{}\" \n && value != \"\"" + ); +} + +#[test] +fn condition_comments_preserve_surrounding_whitespace() { + let source = "model\n schema 1.1\n\ + condition active(value: bool) { // initial\n // standalone\n value // trailing\n}\n"; + let expected: AuthorizationModel = serde_json::from_str( + r#"{ + "schema_version": "1.1", + "conditions": {"active": { + "name": "active", + "expression": "\n \n value ", + "parameters": {"value": {"type_name": "TYPE_NAME_BOOL"}} + }} + }"#, + ) + .unwrap(); + assert_eq!(openfga_language::parse(source).unwrap(), expected); +}