diff --git a/Cargo.lock b/Cargo.lock index 9de964b..911416a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -26,6 +26,12 @@ dependencies = [ "object", ] +[[package]] +name = "arraydeque" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236" + [[package]] name = "bitflags" version = "2.13.2" @@ -278,6 +284,7 @@ dependencies = [ "openfga-model", "pest", "pest_derive", + "saphyr-parser", "serde", "serde_json", "serde_norway", @@ -544,6 +551,16 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "saphyr-parser" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a425f8285f1321dd220c4d781a7f757eccd6639359f72bdeceec3cdaac8b3a7" +dependencies = [ + "arraydeque", + "thiserror", +] + [[package]] name = "serde" version = "1.0.229" diff --git a/crates/openfga-language/Cargo.toml b/crates/openfga-language/Cargo.toml index d156122..3aa1393 100644 --- a/crates/openfga-language/Cargo.toml +++ b/crates/openfga-language/Cargo.toml @@ -16,6 +16,7 @@ categories = ["authentication", "parser-implementations", "no-std"] openfga-model = { version = "0.1.0", path = "../openfga-model" } pest = { version = "2.8", default-features = false } pest_derive = { version = "2.8", default-features = false } +saphyr-parser = { version = "0.4.0", default-features = false } thiserror = { version = "2", default-features = false } [dev-dependencies] diff --git a/crates/openfga-language/src/lib.rs b/crates/openfga-language/src/lib.rs index 5621fae..e13e363 100644 --- a/crates/openfga-language/src/lib.rs +++ b/crates/openfga-language/src/lib.rs @@ -4,14 +4,21 @@ extern crate alloc; mod lowering; +mod mod_file; +mod modules; mod validation; mod writer; +pub use mod_file::{ + ModFile, ModFileArrayProperty, ModFileError, ModFileErrors, ModFileStringProperty, + parse_mod_file, +}; +pub use modules::{ModuleError, ModuleErrorKind, ModuleErrors, ModuleFile, merge_modules}; pub use validation::{ DslError, ErrorType, PositionRange, ValidationError, ValidationErrors, ValidationPosition, validate, validate_dsl, }; -pub use writer::{WriteError, write}; +pub use writer::{WriteError, write, write_with_source_information}; use alloc::string::{String, ToString}; use openfga_model::AuthorizationModel; @@ -42,6 +49,12 @@ pub struct ParseError { /// # Errors /// Returns an error for invalid syntax or duplicate relation, condition, parameter, or extension declarations. pub fn parse(dsl: &str) -> Result { + let cleaned = clean_source(dsl); + lowering::lower(parse_pairs(&cleaned)?).map(|(model, _)| model) +} + +/// Removes DSL comments while retaining source coordinates. +fn clean_source(dsl: &str) -> String { let mut cleaned = String::with_capacity(dsl.len()); for (index, line) in dsl.split('\n').enumerate() { if index != 0 { @@ -56,8 +69,12 @@ pub fn parse(dsl: &str) -> Result { ); } } - let source = cleaned.trim_end_matches('\n'); - let pairs = DslParser::parse(Rule::main, source).map_err(|error| { + cleaned +} + +/// Parses source whose comments have been removed. +fn parse_pairs(source: &str) -> Result, ParseError> { + DslParser::parse(Rule::main, source.trim_end_matches('\n')).map_err(|error| { let (line, column) = match error.line_col { LineColLocation::Pos(position) | LineColLocation::Span(position, _) => position, }; @@ -66,6 +83,5 @@ pub fn parse(dsl: &str) -> Result { 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 index 90c1249..a984553 100644 --- a/crates/openfga-language/src/lowering.rs +++ b/crates/openfga-language/src/lowering.rs @@ -14,7 +14,10 @@ use openfga_model::{ }; use pest::iterators::{Pair, Pairs}; -pub(super) fn lower(pairs: Pairs<'_, Rule>) -> Result { +/// Lowers model declarations and records extended type names. +pub(super) fn lower( + pairs: Pairs<'_, Rule>, +) -> Result<(AuthorizationModel, BTreeSet), ParseError> { let mut model = AuthorizationModel::default(); let mut module = String::new(); let mut extensions = BTreeSet::new(); @@ -53,7 +56,7 @@ pub(super) fn lower(pairs: Pairs<'_, Rule>) -> Result {} } } - Ok(model) + Ok((model, extensions)) } fn tokens(pair: Pair<'_, Rule>) -> impl Iterator> { diff --git a/crates/openfga-language/src/mod_file.rs b/crates/openfga-language/src/mod_file.rs new file mode 100644 index 0000000..d400091 --- /dev/null +++ b/crates/openfga-language/src/mod_file.rs @@ -0,0 +1,658 @@ +//! Positioned parsing of `fga.mod` manifests. + +use alloc::{ + borrow::Cow, + collections::BTreeMap, + format, + string::{String, ToString}, + vec::Vec, +}; +use core::fmt; +use core::fmt::Write as _; +use saphyr_parser::{Event, Marker, Parser, ScalarStyle, Span, SpannedEventReceiver, Tag}; + +/// A manifest string with its zero-based source position. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ModFileStringProperty { + /// The decoded property value. + pub value: String, + /// The zero-based source line. + pub line: usize, + /// The zero-based source column. + pub column: usize, +} + +/// Manifest paths with their zero-based sequence position. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ModFileArrayProperty { + /// The normalized module paths. + pub value: Vec, + /// The zero-based source line. + pub line: usize, + /// The zero-based source column. + pub column: usize, +} + +/// A validated `fga.mod` manifest. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ModFile { + /// The supported schema version. + pub schema: ModFileStringProperty, + /// The module paths in declaration order. + pub contents: ModFileArrayProperty, +} + +/// A positioned manifest validation diagnostic. +#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] +#[error("validation error at line={line}, column={column}: {message}")] +pub struct ModFileError { + /// The validation message. + pub message: String, + /// The zero-based source line. + pub line: usize, + /// The zero-based source column. + pub column: usize, +} + +/// Manifest syntax, decoding, or validation failures. +#[derive(Debug, thiserror::Error)] +pub enum ModFileErrors { + /// YAML syntax could not be parsed. + #[error("YAML syntax error at line={}, column={}: {}", .0.line, .0.column, .0.message)] + Syntax(ModFileError), + /// YAML values could not be decoded into manifest fields. + #[error("{message}")] + Decode { + /// The YAML decoding diagnostic. + message: String, + /// The zero-based source line. + line: usize, + /// The zero-based source column. + column: usize, + }, + /// Manifest fields failed validation in declaration-independent order. + #[error("{}", ValidationDisplay(errors))] + Validation { + /// Schema diagnostics followed by contents diagnostics. + errors: Vec, + }, +} + +struct ValidationDisplay<'errors>(&'errors [ModFileError]); + +impl fmt::Display for ValidationDisplay<'_> { + /// Formats the aggregate validation diagnostic. + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + writeln!( + formatter, + "{} error{} occurred:", + self.0.len(), + if self.0.len() == 1 { "" } else { "s" } + ) + .and_then(|()| { + self.0 + .iter() + .try_for_each(|error| writeln!(formatter, "\t* {error}")) + }) + .and_then(|()| writeln!(formatter)) + } +} + +#[derive(Clone, Copy, Eq, PartialEq)] +enum Kind { + Scalar, + Sequence, + Mapping, + Alias(usize), +} + +struct Node<'input> { + kind: Kind, + tag: Cow<'input, str>, + value: Cow<'input, str>, + marker: Marker, + children: Vec, +} + +struct Document<'input> { + source: &'input str, + nodes: Vec>, + parents: Vec, + anchors: BTreeMap, +} + +impl<'input> SpannedEventReceiver<'input> for Document<'input> { + /// Records YAML nodes without expanding aliases. + fn on_event(&mut self, event: Event<'input>, span: Span) { + let (kind, tag, value, anchor) = match event { + Event::Scalar(value, style, anchor, tag) => { + let resolved = match tag.filter(|tag| !(tag.handle.is_empty() && tag.suffix == "!")) + { + Some(tag) => explicit_tag(tag), + None if style != ScalarStyle::Plain => Cow::Borrowed("str"), + None => Cow::Borrowed(scalar_tag(&value)), + }; + (Kind::Scalar, resolved, value, anchor) + } + Event::SequenceStart(anchor, tag) => ( + Kind::Sequence, + tag.filter(|tag| !(tag.handle.is_empty() && tag.suffix == "!")) + .map_or(Cow::Borrowed("seq"), explicit_tag), + Cow::Borrowed(""), + anchor, + ), + Event::MappingStart(anchor, tag) => ( + Kind::Mapping, + tag.filter(|tag| !(tag.handle.is_empty() && tag.suffix == "!")) + .map_or(Cow::Borrowed("map"), explicit_tag), + Cow::Borrowed(""), + anchor, + ), + Event::Alias(anchor) => { + let name: String = self + .source + .chars() + .skip(span.start.index() + 1) + .take(span.end.index() - span.start.index() - 1) + .collect(); + (Kind::Alias(anchor), Cow::Borrowed(""), Cow::Owned(name), 0) + } + Event::SequenceEnd | Event::MappingEnd => { + self.parents.pop(); + return; + } + Event::Nothing + | Event::StreamStart + | Event::StreamEnd + | Event::DocumentStart(_) + | Event::DocumentEnd => return, + }; + let index = self.nodes.len(); + if let Some(&parent) = self.parents.last() { + self.nodes[parent].children.push(index); + } + if anchor != 0 { + self.anchors.insert(anchor, index); + } + self.nodes.push(Node { + kind, + tag, + value, + marker: span.start, + children: Vec::new(), + }); + if matches!(kind, Kind::Sequence | Kind::Mapping) { + self.parents.push(index); + } + } +} + +/// Resolves explicit core tags without accepting custom tag suffixes. +fn explicit_tag(tag: Cow<'_, Tag>) -> Cow<'_, str> { + let tag = tag.into_owned(); + if tag.is_yaml_core_schema() { + Cow::Owned(tag.suffix) + } else { + Cow::Owned(format!("{}{}", tag.handle, tag.suffix)) + } +} + +/// Resolves plain scalars into their implicit YAML categories. +fn scalar_tag(value: &str) -> &'static str { + match value { + "" | "~" | "null" | "Null" | "NULL" => return "null", + "true" | "True" | "TRUE" | "false" | "False" | "FALSE" => return "bool", + ".nan" | ".NaN" | ".NAN" | ".inf" | ".Inf" | ".INF" | "+.inf" | "+.Inf" | "+.INF" + | "-.inf" | "-.Inf" | "-.INF" => return "float", + "<<" => return "merge", + _ => {} + } + if is_timestamp(value) { + return "timestamp"; + } + let plain = if value.contains('_') { + Cow::Owned(value.replace('_', "")) + } else { + Cow::Borrowed(value) + }; + let unsigned = plain.strip_prefix(['+', '-']).unwrap_or(&plain); + let negative = plain.starts_with('-'); + let (digits, radix) = if let Some(digits) = unsigned + .strip_prefix("0x") + .or_else(|| unsigned.strip_prefix("0X")) + { + (digits, 16) + } else if let Some(digits) = unsigned + .strip_prefix("0o") + .or_else(|| unsigned.strip_prefix("0O")) + { + (digits, 8) + } else if let Some(digits) = unsigned + .strip_prefix("0b") + .or_else(|| unsigned.strip_prefix("0B")) + { + (digits, 2) + } else if unsigned.len() > 1 && unsigned.starts_with('0') { + (unsigned, 8) + } else { + (unsigned, 10) + }; + if digits.chars().all(|character| character.is_digit(radix)) + && u64::from_str_radix(digits, radix).is_ok_and(|number| !negative || number <= 1_u64 << 63) + { + return "int"; + } + if plain.bytes().all(|character| { + character.is_ascii_digit() || matches!(character, b'+' | b'-' | b'.' | b'e' | b'E') + }) && plain.parse::().is_ok_and(f64::is_finite) + { + return "float"; + } + "str" +} + +/// Recognizes calendar dates and accepted timestamp formats. +fn is_timestamp(value: &str) -> bool { + if !value.is_ascii() { + return false; + } + let (date, time) = value.find(['T', 't', ' ']).map_or((value, None), |index| { + (&value[..index], Some(&value[index..])) + }); + let mut parts = date.split('-'); + let Some(year) = parts + .next() + .filter(|part| part.len() == 4) + .and_then(|part| decimal_component(part, 4)) + else { + return false; + }; + let Some(month) = parts + .next() + .and_then(|part| decimal_component(part, 2)) + .filter(|month| (1..=12).contains(month)) + else { + return false; + }; + let Some(day) = parts.next().and_then(|part| decimal_component(part, 2)) else { + return false; + }; + let days = match month { + 2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29, + 2 => 28, + 4 | 6 | 9 | 11 => 30, + _ => 31, + }; + if parts.next().is_some() || !(1..=days).contains(&day) { + return false; + } + let Some(time) = time else { + return true; + }; + let (clock, zone) = time[1..] + .find(['Z', '+', '-']) + .map_or((&time[1..], None), |index| { + (&time[1..=index], Some(&time[index + 1..])) + }); + if time.starts_with(' ') && zone.is_some() || !time.starts_with(' ') && zone.is_none() { + return false; + } + let mut parts = clock.split(':'); + let hour = parts.next().and_then(|part| decimal_component(part, 2)); + let minute = parts.next().and_then(|part| decimal_component(part, 2)); + let second = parts.next().and_then(|part| { + let (integer, fraction) = part + .split_once(['.', ',']) + .map_or((part, None), |(integer, fraction)| { + (integer, Some(fraction)) + }); + if fraction.is_some_and(|fraction| { + fraction.is_empty() || !fraction.bytes().all(|character| character.is_ascii_digit()) + }) { + return None; + } + decimal_component(integer, 2) + }); + if hour.is_none_or(|hour| hour >= 24) + || minute.is_none_or(|minute| minute >= 60) + || second.is_none_or(|second| second >= 60) + || parts.next().is_some() + { + return false; + } + match zone { + None | Some("Z") => true, + Some(zone) => { + zone.len() == 6 + && zone.as_bytes()[3] == b':' + && decimal_component(&zone[1..3], 2).is_some_and(|hour| hour <= 24) + && decimal_component(&zone[4..], 2).is_some_and(|minute| minute <= 60) + } + } +} + +/// Parses a bounded, unsigned decimal timestamp component. +fn decimal_component(value: &str, maximum_digits: usize) -> Option { + if value.len() > maximum_digits || !value.bytes().all(|character| character.is_ascii_digit()) { + return None; + } + value.parse().ok() +} + +/// Parses and validates a module manifest with zero-based source positions. +/// +/// # Errors +/// Returns YAML decoding errors or all schema and contents validation errors. +pub fn parse_mod_file(source: &str) -> Result { + let mut document = Document { + source, + nodes: Vec::new(), + parents: Vec::new(), + anchors: BTreeMap::new(), + }; + Parser::new_from_str(source) + .load(&mut document, false) + .map_err(|error| { + ModFileErrors::Syntax(ModFileError { + message: error.info().to_string(), + line: error.marker().line() - 1, + column: error.marker().col(), + }) + })?; + let mut fields = [None, None]; + if let Some(root) = document.nodes.first() { + if root.kind == Kind::Mapping { + document.fields(0, &mut fields, &mut Vec::new())?; + } else if root.tag != "null" { + let value = if root.value.is_empty() { + String::new() + } else { + format!(" `{}`", root.value) + }; + return Err(ModFileErrors::Decode { + message: format!( + "yaml: unmarshal errors:\n line {}: cannot unmarshal !!{}{value} into transformer.YAMLModFile", + root.marker.line(), + root.tag + ), + line: root.marker.line() - 1, + column: root.marker.col(), + }); + } + } + let mut errors = Vec::new(); + let schema = match fields[0].map(|index| &document.nodes[index]) { + None => { + errors.push(missing("schema")); + None + } + Some(node) if node.tag != "str" => { + errors.push(node.error(format!( + "unexpected schema type, expected string got value {}", + node.value + ))); + None + } + Some(node) if node.value != "1.2" => { + errors.push(node.error( + "unsupported schema version, fga.mod only supported in version `1.2`".into(), + )); + None + } + Some(node) => Some(node.property(node.value.to_string())), + }; + let contents = match fields[1].map(|index| &document.nodes[index]) { + None => { + errors.push(missing("contents")); + None + } + Some(node) if node.tag != "seq" => { + errors.push(node.error(format!( + "unexpected contents type, expected list of strings got value {}", + node.value + ))); + None + } + Some(node) => { + let mut value = Vec::with_capacity(node.children.len()); + for &index in &node.children { + let item = &document.nodes[index]; + match item.path() { + Ok(path) => value.push(item.property(path)), + Err(error) => errors.push(error), + } + } + Some(ModFileArrayProperty { + value, + line: node.marker.line() - 1, + column: node.marker.col(), + }) + } + }; + match (schema, contents) { + (Some(schema), Some(contents)) if errors.is_empty() => Ok(ModFile { schema, contents }), + _ => Err(ModFileErrors::Validation { errors }), + } +} + +impl Document<'_> { + /// Collects explicit fields before applying YAML merge mappings. + fn fields( + &self, + index: usize, + fields: &mut [Option; 2], + visiting: &mut Vec, + ) -> Result<(), ModFileErrors> { + let node = &self.nodes[index]; + visiting.push(index); + self.validate_keys(node)?; + for pair in node.children.as_chunks::<2>().0 { + let key = &self.nodes[pair[0]]; + let field = match key.value.as_ref() { + "schema" => Some(0), + "contents" => Some(1), + _ => None, + }; + if let Some(field) = field + && fields[field].is_none() + { + fields[field] = Some(pair[1]); + } + } + for pair in node.children.as_chunks::<2>().0 { + if self.nodes[pair[0]].tag == "merge" { + self.merge(pair[1], fields, visiting)?; + } + } + visiting.pop(); + Ok(()) + } + + /// Collects duplicate mapping keys before decoding their values. + fn validate_keys(&self, node: &Node<'_>) -> Result<(), ModFileErrors> { + let mut duplicate: Option<(String, Marker)> = None; + let pairs = node.children.as_chunks::<2>().0; + for (position, pair) in pairs.iter().enumerate() { + let previous = &self.nodes[pair[0]]; + for pair in &pairs[position + 1..] { + let key = &self.nodes[pair[0]]; + if previous.kind == key.kind && previous.value == key.value { + let (message, _) = duplicate + .get_or_insert_with(|| ("yaml: unmarshal errors:".into(), key.marker)); + let _ = write!( + message, + "\n line {}: mapping key {:?} already defined at line {}", + key.marker.line(), + key.value, + previous.marker.line() + ); + } + } + } + match duplicate { + Some((message, marker)) => Err(ModFileErrors::Decode { + message, + line: marker.line() - 1, + column: marker.col(), + }), + None => Ok(()), + } + } + + /// Applies mappings and alias sequences used by YAML merge keys. + fn merge( + &self, + index: usize, + fields: &mut [Option; 2], + visiting: &mut Vec, + ) -> Result<(), ModFileErrors> { + let node = &self.nodes[index]; + if node.kind == Kind::Sequence { + for &child in &node.children { + self.merge_mapping(child, fields, visiting)?; + } + Ok(()) + } else { + self.merge_mapping(index, fields, visiting) + } + } + + /// Resolves a merge alias and rejects non-mapping values. + fn merge_mapping( + &self, + index: usize, + fields: &mut [Option; 2], + visiting: &mut Vec, + ) -> Result<(), ModFileErrors> { + let node = &self.nodes[index]; + let target = match node.kind { + Kind::Alias(anchor) => self.anchors[&anchor], + _ => index, + }; + if visiting.contains(&target) { + return Err(ModFileErrors::Decode { + message: format!("yaml: anchor '{}' value contains itself", node.value), + line: node.marker.line() - 1, + column: node.marker.col(), + }); + } + if self.nodes[target].kind == Kind::Mapping { + self.fields(target, fields, visiting) + } else { + Err(ModFileErrors::Decode { + message: "yaml: map merge requires map or sequence of maps as the value".into(), + line: node.marker.line() - 1, + column: node.marker.col(), + }) + } + } +} + +impl Node<'_> { + /// Creates a diagnostic at this node's source position. + fn error(&self, message: String) -> ModFileError { + ModFileError { + message, + line: self.marker.line() - 1, + column: self.marker.col(), + } + } + + /// Attaches this node's source position to a decoded value. + fn property(&self, value: String) -> ModFileStringProperty { + ModFileStringProperty { + value, + line: self.marker.line() - 1, + column: self.marker.col(), + } + } + + /// Validates and normalizes a module path. + #[expect( + clippy::case_sensitive_file_extension_comparisons, + reason = "Manifest paths require the lowercase .fga extension." + )] + fn path(&self) -> Result { + if self.tag != "str" { + return Err(self.error(format!( + "unexpected contents item type, expected string got value {}", + self.value + ))); + } + let mut decoded = Vec::with_capacity(self.value.len()); + let mut bytes = self.value.bytes(); + while let Some(byte) = bytes.next() { + let byte = match byte { + b'+' => b' ', + b'%' => { + let pair = bytes + .next() + .and_then(hexadecimal) + .zip(bytes.next().and_then(hexadecimal)); + let Some((high, low)) = pair else { + return Err(self.error(format!("failed to decode path: {}", self.value))); + }; + high * 16 + low + } + byte => byte, + }; + decoded.push(if byte == b'\\' { b'/' } else { byte }); + } + let normalized = match String::from_utf8(decoded) { + Ok(normalized) => normalized, + Err(error) => replace_invalid_utf8(error.as_bytes()), + }; + if normalized.contains("../") || normalized.starts_with('/') { + return Err(self.error(format!("invalid contents item {}", self.value))); + } + if !normalized.ends_with(".fga") { + return Err(self.error(format!( + "contents items should use fga file extension, got {}", + self.value + ))); + } + Ok(normalized) + } +} + +/// Constructs a diagnostic for an absent manifest field. +fn missing(field: &str) -> ModFileError { + ModFileError { + message: format!("missing {field} field"), + line: 0, + column: 0, + } +} + +/// Decodes one hexadecimal URI digit. +fn hexadecimal(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + b'A'..=b'F' => Some(byte - b'A' + 10), + _ => None, + } +} + +/// Replaces each invalid UTF-8 byte with a replacement character. +fn replace_invalid_utf8(mut bytes: &[u8]) -> String { + let mut result = String::with_capacity(bytes.len()); + while !bytes.is_empty() { + match core::str::from_utf8(bytes) { + Ok(valid) => { + result.push_str(valid); + break; + } + Err(error) => { + let (valid, remaining) = bytes.split_at(error.valid_up_to()); + result.push_str(&String::from_utf8_lossy(valid)); + let invalid_length = error.error_len().unwrap_or(remaining.len()); + for _ in 0..invalid_length { + result.push('\u{fffd}'); + } + bytes = &remaining[invalid_length..]; + } + } + } + result +} diff --git a/crates/openfga-language/src/modules.rs b/crates/openfga-language/src/modules.rs new file mode 100644 index 0000000..0536dca --- /dev/null +++ b/crates/openfga-language/src/modules.rs @@ -0,0 +1,326 @@ +use crate::{ParseError, PositionRange, clean_source, lowering, parse_pairs}; +use alloc::{ + collections::BTreeSet, + format, + string::{String, ToString}, + vec::Vec, +}; +use core::fmt; +use openfga_model::{AuthorizationModel, SourceInfo, TypeDefinition}; + +/// A named DSL source borrowed for modular transformation. +#[derive(Clone, Copy, Debug)] +pub struct ModuleFile<'source> { + /// Source file name. + pub name: &'source str, + /// DSL module contents. + pub contents: &'source str, +} + +/// The stage producing a module diagnostic. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum ModuleErrorKind { + /// Invalid DSL syntax or declarations. + #[error("syntax")] + Syntax, + /// Incompatible declarations across files. + #[error("transformation")] + Transformation, +} + +/// A diagnostic located in a modular source file. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +#[error("{kind} error at line={line_start}, column={column_start}: {message}", line_start = .line.start, column_start = .column.start)] +pub struct ModuleError { + /// Diagnostic description. + pub message: String, + /// Source file name. + pub file: String, + /// Zero-based line range. + pub line: PositionRange, + /// Zero-based column range. + pub column: PositionRange, + /// Diagnostic category. + pub kind: ModuleErrorKind, +} + +/// Module diagnostics in transformation order. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +#[error("{diagnostics}", diagnostics = Diagnostics(.errors))] +pub struct ModuleErrors { + /// Individual diagnostics. + pub errors: Vec, +} + +struct Diagnostics<'errors>(&'errors [ModuleError]); + +impl fmt::Display for Diagnostics<'_> { + /// Formats the complete diagnostic list. + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + let count = self.0.len(); + let plural = if count == 1 { "" } else { "s" }; + write!(formatter, "{count} error{plural} occurred:\n\t* ")?; + for (index, error) in self.0.iter().enumerate() { + if index != 0 { + formatter.write_str("\n\t* ")?; + } + write!(formatter, "{error}")?; + } + formatter.write_str("\n\n") + } +} + +/// Combines modular declarations without validating model semantics. +/// +/// # Errors +/// Returns syntax errors and conflicting or missing modular declarations. +pub fn merge_modules( + modules: &[ModuleFile<'_>], + schema_version: &str, +) -> Result { + let mut model = AuthorizationModel { + schema_version: schema_version.to_string(), + ..AuthorizationModel::default() + }; + let mut errors = Vec::new(); + let mut types = BTreeSet::new(); + let mut extensions = Vec::new(); + for module in modules { + let cleaned = clean_source(module.contents); + let parsed = parse_pairs(&cleaned) + .and_then(|pairs| lowering::lower(pairs.clone()).map(|lowered| (pairs, lowered))); + let (pairs, (mut parsed, extended)) = match parsed { + Ok(parsed) => parsed, + Err(error) => { + errors.push(syntax_error(module, error)); + continue; + } + }; + if !parsed.schema_version.is_empty() { + errors.push(ModuleError { + message: "file is not a module".to_string(), + file: module.name.to_string(), + line: PositionRange { start: 0, end: 0 }, + column: PositionRange { start: 0, end: 0 }, + kind: ModuleErrorKind::Transformation, + }); + continue; + } + for mut definition in parsed.type_definitions { + if extended.contains(&definition.r#type) { + extensions.push((module, definition)); + continue; + } + if !types.insert(definition.r#type.clone()) { + errors.push(declaration_error( + module, + "type", + &definition.r#type, + format!("duplicate type definition {}", definition.r#type), + )); + continue; + } + definition + .metadata + .get_or_insert_with(Default::default) + .source_info = Some(SourceInfo { + file: module.name.to_string(), + }); + model.type_definitions.push(definition); + } + for declaration in pairs + .flat_map(pest::iterators::Pair::into_inner) + .filter(|pair| pair.as_rule() == crate::Rule::condition) + { + let name = condition_name(declaration); + merge_condition( + &mut model, + &mut parsed.conditions, + module, + name, + &mut errors, + ); + } + } + for (module, definition) in extensions { + if let Some(original) = model + .type_definitions + .iter_mut() + .find(|original| original.r#type == definition.r#type) + { + merge_extension(original, definition, module, &mut errors); + } else { + errors.push(declaration_error( + module, + "extend type", + &definition.r#type, + format!("extended type {} does not exist", definition.r#type), + )); + } + } + if errors.is_empty() { + Ok(model) + } else { + Err(ModuleErrors { errors }) + } +} + +/// Adds extension relations while retaining their source metadata. +fn merge_extension( + original: &mut TypeDefinition, + mut extension: TypeDefinition, + module: &ModuleFile<'_>, + errors: &mut Vec, +) { + let mut metadata = extension.metadata.unwrap(); + let declarations = module + .contents + .lines() + .skip_while(|line| declaration_name(line, "extend type") != Some(extension.r#type.as_str())) + .skip(1) + .take_while(|line| { + declaration_name(line, "type").is_none() + && declaration_name(line, "extend type").is_none() + && declaration_name(line, "condition").is_none() + }); + for name in declarations.filter_map(|line| declaration_name(line, "define")) { + let relation = extension.relations.remove(name).unwrap(); + if original.relations.contains_key(name) { + errors.push(declaration_error( + module, + "define", + name, + format!("relation {name} already exists on type {}", original.r#type), + )); + continue; + } + let mut relation_metadata = metadata.relations.remove(name).unwrap(); + relation_metadata.source_info = Some(SourceInfo { + file: module.name.to_string(), + }); + original + .metadata + .as_mut() + .unwrap() + .relations + .insert(name.to_string(), relation_metadata); + original.relations.insert(name.to_string(), relation); + } +} + +/// Extracts an identifier following a declaration keyword sequence. +fn declaration_name<'source>(source: &'source str, keyword: &str) -> Option<&'source str> { + let mut words = source.split_whitespace(); + if !keyword + .split(' ') + .all(|keyword| words.next() == Some(keyword)) + { + return None; + } + words.next()?.split([':', '(']).next() +} + +/// Returns the name token of a parsed condition declaration. +fn condition_name(pair: pest::iterators::Pair<'_, crate::Rule>) -> &str { + pair.into_inner() + .find(|pair| pair.as_rule() != crate::Rule::newline) + .unwrap() + .into_inner() + .next() + .unwrap() + .as_str() +} + +/// Transfers one parsed condition and reports duplicate names. +fn merge_condition( + model: &mut AuthorizationModel, + conditions: &mut alloc::collections::BTreeMap, + module: &ModuleFile<'_>, + name: &str, + errors: &mut Vec, +) { + if model.conditions.contains_key(name) { + errors.push(declaration_error( + module, + "condition", + name, + format!("duplicate condition {name}"), + )); + return; + } + let mut condition = conditions.remove(name).unwrap(); + condition + .metadata + .get_or_insert_with(Default::default) + .source_info = Some(SourceInfo { + file: module.name.to_string(), + }); + model.conditions.insert(name.to_string(), condition); +} + +/// Locates a declaration by its complete keyword sequence and identifier. +fn declaration_error( + module: &ModuleFile<'_>, + keyword: &str, + name: &str, + message: String, +) -> ModuleError { + let (line, source) = module + .contents + .lines() + .enumerate() + .find(|(_, source)| { + let mut words = source.split_whitespace(); + keyword + .split(' ') + .all(|keyword| words.next() == Some(keyword)) + && words + .next() + .is_some_and(|word| word.split([':', '(']).next() == Some(name)) + }) + .unwrap(); + let column = source.find(name).unwrap(); + ModuleError { + message, + file: module.name.to_string(), + line: PositionRange { + start: line, + end: line, + }, + column: PositionRange { + start: column, + end: column + name.len(), + }, + kind: ModuleErrorKind::Transformation, + } +} + +/// Converts parser coordinates into zero-based module diagnostics. +fn syntax_error(module: &ModuleFile<'_>, error: ParseError) -> ModuleError { + let line = error.line - 1; + let column = error.column - 1; + let width = module + .contents + .lines() + .nth(line) + .unwrap_or_default() + .chars() + .skip(column) + .take_while(|character| { + character.is_alphanumeric() || matches!(character, '_' | '-' | '.' | '/') + }) + .count(); + ModuleError { + message: error.message, + file: module.name.to_string(), + line: PositionRange { + start: line, + end: line, + }, + column: PositionRange { + start: column, + end: column + width, + }, + kind: ModuleErrorKind::Syntax, + } +} diff --git a/crates/openfga-language/src/writer.rs b/crates/openfga-language/src/writer.rs index c16496e..3ebacc9 100644 --- a/crates/openfga-language/src/writer.rs +++ b/crates/openfga-language/src/writer.rs @@ -1,7 +1,7 @@ -use alloc::string::String; +use alloc::{string::String, vec::Vec}; use core::fmt::Write as _; use openfga_model::{ - AuthorizationModel, RelationReference, Userset, condition_param_type_ref::TypeName, + AuthorizationModel, RelationReference, SourceInfo, Userset, condition_param_type_ref::TypeName, relation_reference::RelationOrWildcard, userset::Userset as Rewrite, }; @@ -38,39 +38,87 @@ pub enum WriteError { }, } -/// Writes a single-file model as `OpenFGA` DSL without source-information comments. +/// Writes a 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 { + write_model(model, false) +} + +/// Writes a model as `OpenFGA` DSL with source-information comments. +/// +/// # Errors +/// Returns an error for unsupported rewrites, mismatched condition names, or missing collection element types. +pub fn write_with_source_information(model: &AuthorizationModel) -> Result { + write_model(model, true) +} + +/// Writes a model using the requested source-comment policy. +fn write_model( + model: &AuthorizationModel, + include_source_information: bool, +) -> Result { let mut output = String::from("model\n schema "); output.push_str(&model.schema_version); output.push('\n'); - for definition in &model.type_definitions { + write_types(&mut output, model, include_source_information)?; + write_conditions(&mut output, model, include_source_information)?; + Ok(output) +} + +/// Writes type definitions and their relations in model order. +fn write_types( + output: &mut String, + model: &AuthorizationModel, + include_source_information: bool, +) -> Result<(), WriteError> { + let modular = model.type_definitions.iter().any(|definition| { + definition + .metadata + .as_ref() + .is_some_and(|metadata| !metadata.module.is_empty()) + }); + let definitions = modular_order(model.type_definitions.iter(), modular, |definition| { + let (module, source) = definition.metadata.as_ref().map_or(("", None), |metadata| { + (metadata.module.as_str(), metadata.source_info.as_ref()) + }); + source_order(&definition.r#type, module, source) + }); + for definition in definitions { output.push_str("\ntype "); output.push_str(&definition.r#type); + let (module, source) = definition.metadata.as_ref().map_or(("", None), |metadata| { + (metadata.module.as_str(), metadata.source_info.as_ref()) + }); + write_source_comment(output, module, source, false, include_source_information); if !definition.relations.is_empty() { output.push_str("\n relations"); } - for (relation_name, rewrite) in &definition.relations { - let restrictions = definition + let relations = modular_order(definition.relations.iter(), modular, |(name, _)| { + let (module, source) = definition .metadata .as_ref() - .and_then(|metadata| metadata.relations.get(relation_name)) - .map_or(&[][..], |metadata| { - metadata.directly_related_user_types.as_slice() + .and_then(|metadata| metadata.relations.get(*name)) + .map_or(("", None), |metadata| { + (metadata.module.as_str(), metadata.source_info.as_ref()) }); + source_order(name, module, source) + }); + for (relation_name, rewrite) in relations { + let metadata = definition + .metadata + .as_ref() + .and_then(|metadata| metadata.relations.get(relation_name)); + let restrictions = metadata.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, - ); + let result = + write_rewrite(output, Some(rewrite), restrictions, &mut occurrences, false); if result.is_err() || (occurrences != 0 && (occurrences != 1 || !first_direct(rewrite))) { return Err(WriteError::UnsupportedNesting { @@ -78,10 +126,39 @@ pub fn write(model: &AuthorizationModel) -> Result { relation_name: relation_name.clone(), }); } + let (module, source) = metadata.map_or(("", None), |metadata| { + (metadata.module.as_str(), metadata.source_info.as_ref()) + }); + write_source_comment(output, module, source, true, include_source_information); } output.push('\n'); } - for (condition_name, condition) in &model.conditions { + Ok(()) +} + +/// Writes conditions in module, file, and name order. +fn write_conditions( + output: &mut String, + model: &AuthorizationModel, + include_source_information: bool, +) -> Result<(), WriteError> { + let modular_conditions = model.conditions.values().any(|condition| { + condition + .metadata + .as_ref() + .is_some_and(|metadata| !metadata.module.is_empty()) + }); + let conditions = modular_order( + model.conditions.iter(), + modular_conditions, + |(name, condition)| { + let (module, source) = condition.metadata.as_ref().map_or(("", None), |metadata| { + (metadata.module.as_str(), metadata.source_info.as_ref()) + }); + source_order(name, module, source) + }, + ); + for (condition_name, condition) in conditions { if condition_name != &condition.name { return Err(WriteError::ConditionNameMismatch { condition_name: condition_name.clone(), @@ -97,7 +174,7 @@ pub fn write(model: &AuthorizationModel) -> Result { } output.push_str(parameter_name); output.push_str(": "); - write_type_name(&mut output, parameter.type_name); + write_type_name(output, parameter.type_name); if matches!( TypeName::try_from(parameter.type_name), Ok(TypeName::List | TypeName::Map) @@ -109,17 +186,73 @@ pub fn write(model: &AuthorizationModel) -> Result { } })?; output.push('<'); - write_type_name(&mut output, generic.type_name); + write_type_name(output, generic.type_name); output.push('>'); } } output.push_str(") {\n "); output.push_str(&condition.expression); - output.push_str("\n}\n"); + output.push_str("\n}"); + let (module, source) = condition.metadata.as_ref().map_or(("", None), |metadata| { + (metadata.module.as_str(), metadata.source_info.as_ref()) + }); + write_source_comment(output, module, source, false, include_source_information); + output.push('\n'); + } + Ok(()) +} + +/// Orders modular entries without collecting single-file entries. +fn modular_order<'a, Entry, Entries, Key>( + mut entries: Entries, + modular: bool, + key: Key, +) -> impl Iterator +where + Entries: ExactSizeIterator, + Key: Fn(&Entry) -> (&'a str, &'a str, &'a str), +{ + let mut sorted = Vec::new(); + if modular && entries.len() > 1 { + sorted.extend(entries.by_ref()); + sorted.sort_by_key(key); + } + entries.chain(sorted) +} + +/// Sorts unassigned entries by name and modular entries by module, file, and name. +fn source_order<'a>( + name: &'a str, + module: &'a str, + source: Option<&'a SourceInfo>, +) -> (&'a str, &'a str, &'a str) { + let file = if module.is_empty() { + "" + } else { + source.map_or("", |source| source.file.as_str()) + }; + (module, file, name) +} + +/// Appends available source information when requested. +fn write_source_comment( + output: &mut String, + module: &str, + source: Option<&SourceInfo>, + relation: bool, + include_source_information: bool, +) { + let file = source.map_or("", |source| source.file.as_str()); + if include_source_information && (!module.is_empty() || !file.is_empty()) { + output.push_str(if relation { " # extended by:" } else { " #" }); + output.push_str(" module: "); + output.push_str(module); + output.push_str(", file: "); + output.push_str(file); } - Ok(output) } +/// Writes a parameter type name or its unknown numeric value. 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() { @@ -130,10 +263,12 @@ fn write_type_name(output: &mut String, number: i32) { } } +/// Reports whether a rewrite is direct assignment. fn is_direct(userset: &Userset) -> bool { matches!(userset.userset, Some(Rewrite::This(_))) } +/// Reports whether direct assignment occupies the first permitted position. fn first_direct(userset: &Userset) -> bool { match userset.userset.as_ref() { Some(Rewrite::This(_)) => true, @@ -147,6 +282,7 @@ fn first_direct(userset: &Userset) -> bool { } } +/// Writes direct-assignment type restrictions. fn write_restrictions(output: &mut String, restrictions: &[RelationReference]) { output.push('['); for (index, restriction) in restrictions.iter().enumerate() { @@ -170,6 +306,7 @@ fn write_restrictions(output: &mut String, restrictions: &[RelationReference]) { output.push(']'); } +/// Writes a relation rewrite and counts direct assignments. fn write_rewrite( output: &mut String, userset: Option<&Userset>, diff --git a/crates/openfga-language/tests/mod_file.rs b/crates/openfga-language/tests/mod_file.rs new file mode 100644 index 0000000..1de7554 --- /dev/null +++ b/crates/openfga-language/tests/mod_file.rs @@ -0,0 +1,738 @@ +//! Module manifest values, diagnostics, and source positions. + +use openfga_language::{ + ModFile, ModFileArrayProperty, ModFileError, ModFileErrors, ModFileStringProperty, + parse_mod_file, +}; +use serde::Deserialize; + +#[derive(Deserialize)] +struct Case { + name: String, + #[serde(rename = "modFile")] + source: String, + json: Option, + #[serde(default)] + expected_errors: Vec, +} + +#[derive(Deserialize)] +struct Start { + start: usize, +} + +#[derive(Deserialize)] +struct ExpectedProperty { + value: String, + line: Start, + column: Start, +} + +#[derive(Deserialize)] +struct ExpectedArray { + value: Vec, + line: Start, + column: Start, +} + +#[derive(Deserialize)] +struct ExpectedModel { + schema: ExpectedProperty, + contents: ExpectedArray, +} + +#[derive(Deserialize)] +struct ExpectedError { + msg: String, + line: Start, + column: Start, +} + +/// Converts corpus source ranges to zero-based start positions. +fn property(expected: ExpectedProperty) -> ModFileStringProperty { + ModFileStringProperty { + value: expected.value, + line: expected.line.start, + column: expected.column.start, + } +} + +/// Every pinned manifest case preserves values and complete diagnostics. +#[test] +fn corpus_cases() { + let cases: Vec = serde_norway::from_str(include_str!( + "../../../conformance/openfga-language/tests/data/fga-mod-transformer-cases.yaml" + )) + .expect("manifest corpus"); + assert_eq!(cases.len(), 9); + for case in cases { + if let Some(json) = case.json { + let expected: ExpectedModel = serde_json::from_str(&json).expect("expected model"); + assert_eq!( + parse_mod_file(&case.source).expect(&case.name), + ModFile { + schema: property(expected.schema), + contents: ModFileArrayProperty { + value: expected.contents.value.into_iter().map(property).collect(), + line: expected.contents.line.start, + column: expected.contents.column.start, + }, + }, + "{}", + case.name + ); + } else { + let expected: Vec<_> = case + .expected_errors + .into_iter() + .map(|error| ModFileError { + message: error.msg, + line: error.line.start, + column: error.column.start, + }) + .collect(); + let errors = parse_mod_file(&case.source).expect_err(&case.name); + let ModFileErrors::Validation { errors: actual } = &errors else { + panic!("{} returned YAML diagnostics", case.name); + }; + assert_eq!(*actual, expected, "{}", case.name); + assert_eq!( + errors.to_string(), + display_errors(&expected), + "{}", + case.name + ); + } + } +} + +/// Formats the aggregate diagnostic contract. +fn display_errors(errors: &[ModFileError]) -> String { + format!( + "{} error{} occurred:\n\t* {}\n\n", + errors.len(), + if errors.len() == 1 { "" } else { "s" }, + errors + .iter() + .map(|error| format!( + "validation error at line={}, column={}: {}", + error.line, error.column, error.message + )) + .collect::>() + .join("\n\t* ") + ) +} + +/// Checks complete ordered diagnostics and their positions. +fn assert_errors(source: &str, expected: &[(usize, usize, &str)]) { + let expected: Vec<_> = expected + .iter() + .map(|&(line, column, message)| ModFileError { + message: message.to_owned(), + line, + column, + }) + .collect(); + let actual = parse_mod_file(source).expect_err(source); + let ModFileErrors::Validation { errors: validation } = &actual else { + panic!("expected validation diagnostics"); + }; + assert_eq!(*validation, expected); + assert_eq!(actual.to_string(), display_errors(&expected)); +} + +/// Empty documents report both absent properties. +#[test] +fn empty_documents() { + for source in ["", "null"] { + assert_errors( + source, + &[ + (0, 0, "missing schema field"), + (0, 0, "missing contents field"), + ], + ); + } +} + +/// URI query decoding replaces plus signs and normalizes separators. +#[test] +fn decoded_paths_and_tag_positions() { + let actual = parse_mod_file( + "schema: !!str 1.2\ncontents: [a+b.fga, 'folder\\core%2efga', 'a%2Bb.fga', '%FF.fga']\n", + ) + .expect("valid paths"); + assert_eq!( + actual, + ModFile { + schema: ModFileStringProperty { + value: "1.2".into(), + line: 0, + column: 8 + }, + contents: ModFileArrayProperty { + value: [ + ("a b.fga", 11), + ("folder/core.fga", 20), + ("a+b.fga", 41), + ("�.fga", 54) + ] + .into_iter() + .map(|(value, column)| ModFileStringProperty { + value: value.into(), + line: 1, + column + }) + .collect(), + line: 1, + column: 10, + }, + } + ); +} + +/// Invalid percent escapes retain the original path and its position. +#[test] +fn malformed_percent_escapes() { + assert_errors( + "schema: !!str 1.2\ncontents: [a+b.fga, 'folder\\core%2efga', '%ZZ.fga', '%', '%2', '%FF.fga']\n", + &[ + (1, 41, "failed to decode path: %ZZ.fga"), + (1, 52, "failed to decode path: %"), + (1, 57, "failed to decode path: %2"), + ], + ); +} + +/// YAML scalar tags determine field and item types. +#[test] +fn scalar_and_collection_types() { + assert_errors( + "schema: 1.2\ncontents: []\n", + &[( + 0, + 8, + "unexpected schema type, expected string got value 1.2", + )], + ); + assert_errors( + "schema: null\ncontents: null\n", + &[ + ( + 0, + 8, + "unexpected schema type, expected string got value null", + ), + ( + 1, + 10, + "unexpected contents type, expected list of strings got value null", + ), + ], + ); + assert_errors( + "schema: {}\ncontents: {}\n", + &[ + (0, 8, "unexpected schema type, expected string got value "), + ( + 1, + 10, + "unexpected contents type, expected list of strings got value ", + ), + ], + ); + assert_errors( + "schema: '1.2'\ncontents: [null, {}, [], 2026-01-01, yes, 0xFF, .inf]\n", + &[ + ( + 1, + 11, + "unexpected contents item type, expected string got value null", + ), + ( + 1, + 17, + "unexpected contents item type, expected string got value ", + ), + ( + 1, + 21, + "unexpected contents item type, expected string got value ", + ), + ( + 1, + 25, + "unexpected contents item type, expected string got value 2026-01-01", + ), + ( + 1, + 37, + "contents items should use fga file extension, got yes", + ), + ( + 1, + 42, + "unexpected contents item type, expected string got value 0xFF", + ), + ( + 1, + 48, + "unexpected contents item type, expected string got value .inf", + ), + ], + ); + assert_errors( + "schema: '1.2'\ncontents: !!str [a.fga]\n", + &[( + 1, + 10, + "unexpected contents type, expected list of strings got value ", + )], + ); + assert_errors( + "schema: '1.2'\ncontents: [!!str true, !custom a.fga]\n", + &[ + ( + 1, + 11, + "contents items should use fga file extension, got true", + ), + ( + 1, + 23, + "unexpected contents item type, expected string got value a.fga", + ), + ], + ); +} + +/// Anchors retain their start position while field aliases remain alias nodes. +#[test] +fn anchors_and_aliases() { + assert_eq!( + parse_mod_file("schema: &version '1.2'\ncontents: [&path a.fga]\n") + .expect("anchored values"), + ModFile { + schema: ModFileStringProperty { + value: "1.2".into(), + line: 0, + column: 8 + }, + contents: ModFileArrayProperty { + value: vec![ModFileStringProperty { + value: "a.fga".into(), + line: 1, + column: 11 + }], + line: 1, + column: 10 + }, + } + ); + assert_errors( + "schema: &version '1.2'\ncontents: [&path a.fga, *path]\n", + &[( + 1, + 24, + "unexpected contents item type, expected string got value path", + )], + ); + assert_errors( + "version: &version '1.2'\nschema: *version\ncontents: []\n", + &[( + 1, + 8, + "unexpected schema type, expected string got value version", + )], + ); +} + +/// Merge mappings inherit values and source positions. +#[test] +fn merge_mapping() { + assert_eq!( + parse_mod_file("defaults: &defaults {schema: '1.2', contents: [a.fga]}\n<<: *defaults\n") + .expect("merged fields"), + ModFile { + schema: ModFileStringProperty { + value: "1.2".into(), + line: 0, + column: 29 + }, + contents: ModFileArrayProperty { + value: vec![ModFileStringProperty { + value: "a.fga".into(), + line: 0, + column: 47 + }], + line: 0, + column: 46 + }, + } + ); +} + +/// Only the first YAML document supplies manifest properties. +#[test] +fn first_document_and_empty_contents() { + let expected = ModFile { + schema: ModFileStringProperty { + value: "1.2".into(), + line: 0, + column: 8, + }, + contents: ModFileArrayProperty { + value: vec![], + line: 1, + column: 10, + }, + }; + for source in [ + "schema: '1.2'\ncontents: []\n", + "schema: '1.2'\ncontents: []\n---\ninvalid: [\n", + ] { + assert_eq!(parse_mod_file(source).expect("first document"), expected); + } +} + +/// Duplicate root keys retain their YAML diagnostic. +#[test] +fn duplicate_keys() { + let errors = parse_mod_file("schema: '1.2'\nschema: '1.2'\ncontents: []\n") + .expect_err("duplicate schema"); + assert_eq!( + errors.to_string(), + "yaml: unmarshal errors:\n line 2: mapping key \"schema\" already defined at line 1" + ); +} + +/// Traversal checks apply after normalization and inspect substrings. +#[test] +fn embedded_traversal() { + assert_errors( + "schema: '1.2'\ncontents: [C:\\core.fga, './a.fga', 'a..fga', '.../a.fga', 'a%2Bb.fga']\n", + &[(1, 45, "invalid contents item .../a.fga")], + ); +} + +/// Scalar resolution distinguishes invalid dates and overflowing numbers. +#[test] +fn scalar_resolution_boundaries() { + assert_errors( + "schema: '1.2'\ncontents: [2024-2-29, 2023-2-29, --1, +01, 1e400, 0b101, 0o77]\n", + &[ + ( + 1, + 11, + "unexpected contents item type, expected string got value 2024-2-29", + ), + ( + 1, + 22, + "contents items should use fga file extension, got 2023-2-29", + ), + ( + 1, + 33, + "contents items should use fga file extension, got --1", + ), + ( + 1, + 38, + "unexpected contents item type, expected string got value +01", + ), + ( + 1, + 43, + "contents items should use fga file extension, got 1e400", + ), + ( + 1, + 50, + "unexpected contents item type, expected string got value 0b101", + ), + ( + 1, + 57, + "unexpected contents item type, expected string got value 0o77", + ), + ], + ); +} + +/// Block scalar diagnostics point to the scalar indicator. +#[test] +fn block_scalar_indicator_position() { + assert_errors( + "schema: |\n 1.2\ncontents: []\n", + &[( + 0, + 8, + "unsupported schema version, fga.mod only supported in version `1.2`", + )], + ); +} + +/// Unicode source columns count characters rather than UTF-8 bytes. +#[test] +fn unicode_positions() { + assert_eq!( + parse_mod_file("schema: '1.2'\ncontents: [é.fga, '猫.fga', 'x.fga']\n") + .expect("Unicode paths"), + ModFile { + schema: ModFileStringProperty { + value: "1.2".into(), + line: 0, + column: 8 + }, + contents: ModFileArrayProperty { + value: [("é.fga", 11), ("猫.fga", 18), ("x.fga", 27)] + .into_iter() + .map(|(value, column)| ModFileStringProperty { + value: value.into(), + line: 1, + column + }) + .collect(), + line: 1, + column: 10, + }, + } + ); +} + +/// Invalid root values preserve YAML decoding diagnostics. +#[test] +fn invalid_root_values() { + for (source, message) in [ + ( + "[]", + "yaml: unmarshal errors:\n line 1: cannot unmarshal !!seq into transformer.YAMLModFile", + ), + ( + "hello", + "yaml: unmarshal errors:\n line 1: cannot unmarshal !!str `hello` into transformer.YAMLModFile", + ), + ] { + let errors = parse_mod_file(source).expect_err(source); + assert_eq!(errors.to_string(), message); + let ModFileErrors::Decode { line, column, .. } = errors else { + panic!("expected decoding error"); + }; + assert_eq!((line, column), (0, 0)); + } +} + +/// Duplicate keys accumulate before field validation. +#[test] +fn multiple_duplicate_keys() { + let errors = parse_mod_file("schema: '1.2'\nschema: '1.2'\ncontents: []\ncontents: []\n") + .expect_err("duplicate properties"); + assert_eq!( + errors.to_string(), + "yaml: unmarshal errors:\n line 2: mapping key \"schema\" already defined at line 1\n line 4: mapping key \"contents\" already defined at line 3" + ); +} + +/// Merge sequences accept only mappings or aliases to mappings. +#[test] +fn invalid_merge_values() { + for source in [ + "schema: '1.2'\ncontents: []\n<<: [[]]\n", + "base: &base 1\nschema: '1.2'\ncontents: []\n<<: *base\n", + ] { + assert_eq!( + parse_mod_file(source).expect_err(source).to_string(), + "yaml: map merge requires map or sequence of maps as the value" + ); + } +} + +/// Non-specific tags retain implicit node types. +#[test] +fn non_specific_tags() { + assert_eq!( + parse_mod_file("schema: ! '1.2'\ncontents: ! [! a.fga]\n").expect("non-specific tags"), + ModFile { + schema: ModFileStringProperty { + value: "1.2".into(), + line: 0, + column: 8 + }, + contents: ModFileArrayProperty { + value: vec![ModFileStringProperty { + value: "a.fga".into(), + line: 1, + column: 13 + }], + line: 1, + column: 10 + }, + } + ); + assert_errors( + "schema: '1.2'\ncontents: [! 1.2]\n", + &[( + 1, + 11, + "unexpected contents item type, expected string got value 1.2", + )], + ); +} + +/// Invalid UTF-8 escapes produce one replacement character per byte. +#[test] +fn invalid_utf8_escapes() { + assert_eq!( + parse_mod_file("schema: '1.2'\ncontents: ['%E1%80.fga']\n").expect("escaped bytes"), + ModFile { + schema: ModFileStringProperty { + value: "1.2".into(), + line: 0, + column: 8 + }, + contents: ModFileArrayProperty { + value: vec![ModFileStringProperty { + value: "��.fga".into(), + line: 1, + column: 11 + }], + line: 1, + column: 10 + }, + } + ); +} + +/// Malformed YAML exposes crate-owned zero-based diagnostics. +#[test] +fn malformed_yaml_position() { + let errors = + parse_mod_file("schema: '1.2'\ncontents: [a.fga}\n").expect_err("malformed sequence"); + let ModFileErrors::Syntax(error) = errors else { + panic!("expected syntax error"); + }; + assert_eq!((error.line, error.column), (1, 16)); +} + +/// Malformed numbers and timestamps remain string values. +#[test] +fn malformed_scalar_spellings() { + assert_errors( + "schema: '1.2'\ncontents: [++1, -+1, 0x+1, 2024-+1-1, 2024-01-001, 2024-1-1T1:1:1e1Z]\n", + &[ + ( + 1, + 11, + "contents items should use fga file extension, got ++1", + ), + ( + 1, + 16, + "contents items should use fga file extension, got -+1", + ), + ( + 1, + 21, + "contents items should use fga file extension, got 0x+1", + ), + ( + 1, + 27, + "contents items should use fga file extension, got 2024-+1-1", + ), + ( + 1, + 38, + "contents items should use fga file extension, got 2024-01-001", + ), + ( + 1, + 51, + "contents items should use fga file extension, got 2024-1-1T1:1:1e1Z", + ), + ], + ); +} + +/// Plain numeric and timestamp spellings retain their resolved types. +#[test] +fn timestamp_and_numeric_resolution() { + for scalar in [ + "1_000", + "2024-4-30", + "2024-1-2T3:4:5.25Z", + "2024-1-2 3:4:5.25", + "2024-1-2T3:4:5+02:30", + "2024-1-2T3:4:5-02:30", + ] { + let source = format!("schema: '1.2'\ncontents: [{scalar}]\n"); + let message = format!("unexpected contents item type, expected string got value {scalar}"); + assert_errors(&source, &[(1, 11, &message)]); + } + for scalar in [ + "2024-4-31", + "2024-1-2T3:4:5", + "2024-1-2 3:4:5Z", + "2024-1-2T3:4:5.Z", + "2024-1-2T3:4:5.xZ", + "2024-1-2T24:4:5Z", + "2024-1-2T3:60:5Z", + "2024-1-2T3:4:60Z", + "2024-1-2T3:4:5:6Z", + "2024-1-2T3:4:5+02", + "2024-1-2T3:4:5+02-30", + "2024-1-2T3:4:5+25:30", + "2024-1-2T3:4:5+02:61", + ] { + let source = format!("schema: '1.2'\ncontents: [{scalar}]\n"); + let message = format!("contents items should use fga file extension, got {scalar}"); + assert_errors(&source, &[(1, 11, &message)]); + } +} + +/// Merge sequences combine fields while preserving explicit declarations. +#[test] +fn merge_sequence_precedence() { + assert_eq!( + parse_mod_file("<<: [{schema: '1.2'}, {contents: [a.fga]}]\n").expect("merged sequence"), + ModFile { + schema: ModFileStringProperty { + value: "1.2".into(), + line: 0, + column: 14 + }, + contents: ModFileArrayProperty { + value: vec![ModFileStringProperty { + value: "a.fga".into(), + line: 0, + column: 34 + }], + line: 0, + column: 33, + }, + } + ); + assert_eq!( + parse_mod_file("schema: '1.2'\ncontents: [direct.fga]\n<<: [{schema: '1.1', contents: [first.fga]}, {contents: [second.fga]}]\n").expect("explicit fields"), + ModFile { + schema: ModFileStringProperty { value: "1.2".into(), line: 0, column: 8 }, + contents: ModFileArrayProperty { + value: vec![ModFileStringProperty { value: "direct.fga".into(), line: 1, column: 11 }], + line: 1, + column: 10, + }, + } + ); +} + +/// Recursive merge aliases identify the anchor that contains itself. +#[test] +fn recursive_merge_alias() { + let errors = parse_mod_file("&root {schema: '1.2', contents: [], <<: *root}\n") + .expect_err("recursive merge"); + assert_eq!( + errors.to_string(), + "yaml: anchor 'root' value contains itself" + ); +} diff --git a/crates/openfga-language/tests/modules.rs b/crates/openfga-language/tests/modules.rs new file mode 100644 index 0000000..210928c --- /dev/null +++ b/crates/openfga-language/tests/modules.rs @@ -0,0 +1,271 @@ +//! Modular transformation conformance. +use openfga_language::{ModuleErrorKind, ModuleFile, merge_modules}; +use openfga_model::AuthorizationModel; +use serde_json::Value; +use std::{fs, path::Path}; + +/// Compares all modular fixtures after removing validation-only findings. +#[test] +fn module_corpus() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../conformance/openfga-language/tests/data/transformer-module"); + for entry in fs::read_dir(root).unwrap() { + let directory = entry.unwrap().path(); + if !directory.join("module").is_dir() || directory.join("test.skip").exists() { + continue; + } + let expected_errors = directory.join("expected_errors.json"); + let expected: Vec = if expected_errors.exists() { + serde_json::from_str::>(&fs::read_to_string(expected_errors).unwrap()) + .unwrap() + .into_iter() + .filter(|error| error["metadata"]["errorType"].is_null()) + .collect() + } else { + Vec::new() + }; + if expected.is_empty() && !directory.join("authorization-model.json").exists() { + continue; + } + let mut paths: Vec<_> = fs::read_dir(directory.join("module")) + .unwrap() + .map(|entry| entry.unwrap().path()) + .collect(); + paths.sort(); + let sources: Vec<_> = paths + .iter() + .map(|path| { + ( + path.file_name().unwrap().to_str().unwrap().to_owned(), + fs::read_to_string(path).unwrap(), + ) + }) + .collect(); + let modules: Vec<_> = sources + .iter() + .map(|(name, contents)| ModuleFile { name, contents }) + .collect(); + let result = merge_modules(&modules, "1.2"); + if expected.is_empty() { + let model: AuthorizationModel = serde_json::from_str( + &fs::read_to_string(directory.join("authorization-model.json")).unwrap(), + ) + .unwrap(); + assert_eq!(result.unwrap(), model, "{}", directory.display()); + } else { + let errors = result.unwrap_err(); + assert_eq!( + errors.errors.len(), + expected.len(), + "{}", + directory.display() + ); + assert_errors(&errors, &expected); + } + } +} + +/// Compares positions and messages while allowing parser-specific syntax wording. +fn assert_errors(errors: &openfga_language::ModuleErrors, expected: &[Value]) { + for (actual, expected) in errors.errors.iter().zip(expected) { + assert_eq!(actual.file, expected["file"].as_str().unwrap()); + assert_eq!( + actual.line.start, + usize::try_from(expected["line"]["start"].as_u64().unwrap()).unwrap() + ); + assert_eq!( + actual.line.end, + usize::try_from(expected["line"]["end"].as_u64().unwrap()).unwrap() + ); + assert_eq!( + actual.column.start, + usize::try_from(expected["column"]["start"].as_u64().unwrap()).unwrap() + ); + assert_eq!( + actual.column.end, + usize::try_from(expected["column"]["end"].as_u64().unwrap()).unwrap() + ); + if expected["type"] == "syntax" { + assert_eq!(actual.kind, ModuleErrorKind::Syntax); + } else { + assert_eq!(actual.kind, ModuleErrorKind::Transformation); + assert_eq!(actual.message, expected["msg"].as_str().unwrap()); + } + } + if expected.iter().all(|error| error["type"] != "syntax") { + let messages: Vec<_> = expected + .iter() + .map(|error| { + format!( + "transformation error at line={}, column={}: {}", + error["line"]["start"], + error["column"]["start"], + error["msg"].as_str().unwrap() + ) + }) + .collect(); + assert_eq!( + errors.to_string(), + format!( + "{} error{} occurred:\n\t* {}\n\n", + messages.len(), + if messages.len() == 1 { "" } else { "s" }, + messages.join("\n\t* ") + ) + ); + } +} + +/// Preserves the schema supplied by the caller. +#[test] +fn schema_version() { + let model = merge_modules( + &[ModuleFile { + name: "core.fga", + contents: "module core\n type user", + }], + "1.1", + ) + .unwrap(); + assert_eq!(model.schema_version, "1.1"); +} + +/// Matches declaration diagnostics observed from the modular transformer. +#[test] +fn declaration_errors() { + for (source, expected) in [ + ( + "module core\ntype user\ntype user", + "transformation error at line=1, column=5: duplicate type definition user", + ), + ( + "module core\ntype user\n relations\n define viewer: [user]\n define viewer: [user]", + "syntax error at line=4, column=11: 'viewer' is already defined in 'user'", + ), + ( + "module core\nextend type user\nextend type user", + "syntax error at line=2, column=12: 'user' is already extended in file.", + ), + ( + "module core\ntype user\ncondition test(value: bool) { value }\ncondition test(value: bool) { value }", + "syntax error at line=3, column=10: condition 'test' is already defined in the model", + ), + ] { + let errors = merge_modules( + &[ModuleFile { + name: "core.fga", + contents: source, + }], + "1.2", + ) + .unwrap_err(); + assert_eq!( + errors.to_string(), + format!("1 error occurred:\n\t* {expected}\n\n") + ); + } +} + +/// Empty input and empty extensions retain only declared model data. +#[test] +fn empty_modules_and_extensions() { + assert_eq!( + merge_modules(&[], "1.2").unwrap(), + AuthorizationModel { + schema_version: "1.2".to_owned(), + ..AuthorizationModel::default() + } + ); + let model = merge_modules( + &[ + ModuleFile { + name: "core.fga", + contents: "module core\ntype user", + }, + ModuleFile { + name: "extension.fga", + contents: "module extension\nextend type user", + }, + ], + "1.2", + ) + .unwrap(); + let expected: AuthorizationModel = serde_json::from_str(r#"{"schema_version":"1.2","type_definitions":[{"type":"user","metadata":{"module":"core","source_info":{"file":"core.fga"}}}]}"#).unwrap(); + assert_eq!(model, expected); +} + +/// Reports every missing extension in declaration order. +#[test] +fn multiple_missing_extensions() { + let errors = merge_modules( + &[ModuleFile { + name: "core.fga", + contents: "module core\nextend type user\nextend type document", + }], + "1.2", + ) + .unwrap_err(); + assert_eq!( + errors.to_string(), + "2 errors occurred:\n\t* transformation error at line=1, column=12: extended type user does not exist\n\t* transformation error at line=2, column=12: extended type document does not exist\n\n" + ); +} + +/// Nonmodular conditions retain the positioned module error. +#[test] +fn nonmodular_condition_reports_module_error_without_go_oracle() { + let errors = merge_modules( + &[ + ModuleFile { + name: "model.fga", + contents: "model\n schema 1.1\ntype user\ncondition active(value: bool) { value }", + }, + ModuleFile { + name: "core.fga", + contents: "module core\ntype user\ncondition active(value: bool) { value }", + }, + ], + "1.2", + ) + .unwrap_err(); + assert_eq!( + errors, + openfga_language::ModuleErrors { + errors: vec![openfga_language::ModuleError { + message: "file is not a module".to_owned(), + file: "model.fga".to_owned(), + line: openfga_language::PositionRange { start: 0, end: 0 }, + column: openfga_language::PositionRange { start: 0, end: 0 }, + kind: ModuleErrorKind::Transformation, + }], + } + ); +} + +/// Duplicate conditions and extension relations follow declaration order. +#[test] +fn merge_errors_follow_input_order() { + let errors = merge_modules(&[ + ModuleFile { + name: "core.fga", + contents: "module core\ntype document\n relations\n define zeta: [document]\n define alpha: [document]\ncondition zeta(value: bool) { value }\ncondition alpha(value: bool) { value }", + }, + ModuleFile { + name: "extend.fga", + contents: "module extension\nextend type document\n relations\n define zeta: [document]\n define alpha: [document]\ncondition zeta(value: bool) { value }\ncondition alpha(value: bool) { value }", + }, + ], "1.2").unwrap_err(); + assert_eq!( + errors + .errors + .iter() + .map(|error| error.message.as_str()) + .collect::>(), + [ + "duplicate condition zeta", + "duplicate condition alpha", + "relation zeta already exists on type document", + "relation alpha already exists on type document", + ] + ); +} diff --git a/crates/openfga-language/tests/writer.rs b/crates/openfga-language/tests/writer.rs index 1dc9021..f9d22a3 100644 --- a/crates/openfga-language/tests/writer.rs +++ b/crates/openfga-language/tests/writer.rs @@ -2,6 +2,138 @@ use openfga_model::AuthorizationModel; use std::{fs, path::Path}; +/// Modular fixtures retain their ordering and optional source comments. +#[test] +fn modular_transformer_corpus() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../conformance/openfga-language/tests/data/transformer-module"); + let mut count = 0; + for entry in fs::read_dir(root).expect("the module corpus is available") { + let directory = entry.unwrap().path(); + let model_path = directory.join("authorization-model.json"); + let combined_path = directory.join("combined.fga"); + if !directory.is_dir() || !model_path.is_file() || !combined_path.is_file() { + continue; + } + let model: AuthorizationModel = + serde_json::from_slice(&fs::read(model_path).unwrap()).unwrap(); + assert_eq!( + openfga_language::write(&model).unwrap().as_bytes(), + fs::read(combined_path).unwrap(), + "{}", + directory.display() + ); + let source_path = directory.join("combined-sourceinfo.fga"); + if source_path.is_file() { + assert_eq!( + openfga_language::write_with_source_information(&model) + .unwrap() + .as_bytes(), + fs::read(source_path).unwrap(), + "{}", + directory.display() + ); + } + count += 1; + } + assert_ne!(count, 0, "the module corpus holds no cases"); +} + +/// The complex module fixture matches both Go writer modes. +#[test] +fn complex_module_go_writer_output() { + let model: AuthorizationModel = serde_json::from_str(include_str!( + "../../../conformance/openfga-language/tests/data/transformer-module/06-complex-module/authorization-model.json" + )) + .unwrap(); + let expected = r"model + schema 1.2 + +type page + relations + define owner: [user] + define space: [space] + +type group + relations + define member: [user] + +type organization + relations + define admin: [user] + define member: [user] + define can_create_page: member + define can_create_project: member + +type space + relations + define can_view_pages: member from organization + define organization: [organization] + +type user + +type project + relations + define organization: [organization] + define viewer: member from organization + +type ticket + relations + define owner: [user] + define project: [project] + +condition a_check(val: int) { + val <= 10 +} +"; + let expected_source = r"model + schema 1.2 + +type page + relations + define owner: [user] + define space: [space] + +type group # module: bitbucket, file: bitbucket.fga + relations + define member: [user] + +type organization # module: bitbucket, file: bitbucket.fga + relations + define admin: [user] + define member: [user] + define can_create_page: member # extended by: module: atlassian, file: atlassian.fga + define can_create_project: member # extended by: module: jira, file: jira/projects.fga + +type space # module: confluence, file: confluence.fga + relations + define can_view_pages: member from organization + define organization: [organization] + +type user # module: core, file: core.fga + +type project # module: jira, file: jira/projects.fga + relations + define organization: [organization] + define viewer: member from organization + +type ticket # module: jira, file: jira/tickets.fga + relations + define owner: [user] + define project: [project] + +condition a_check(val: int) { + val <= 10 +} # module: org, file: org.fga +"; + assert_eq!(openfga_language::write(&model).unwrap(), expected); + assert_eq!( + openfga_language::write_with_source_information(&model).unwrap(), + expected_source + ); +} + +/// Single-file fixtures retain their canonical output. #[test] fn transformer_corpus() { let root = Path::new(env!("CARGO_MANIFEST_DIR")) @@ -38,6 +170,7 @@ struct SyntaxCase { error_message: String, } +/// Invalid rewrites retain the upstream diagnostics. #[test] fn json_syntax_corpus() { let source = include_str!( @@ -58,6 +191,7 @@ fn json_syntax_corpus() { } } +/// Collection parameters require an element type. #[test] fn collection_parameter_requires_element_type() { let mut model = AuthorizationModel::default(); @@ -85,6 +219,7 @@ fn collection_parameter_requires_element_type() { ); } +/// Condition names must match their map keys. #[test] fn condition_name_must_match_map_key() { let mut model = AuthorizationModel::default(); @@ -101,6 +236,7 @@ fn condition_name_must_match_map_key() { ); } +/// Unknown parameter types retain their numeric representation. #[test] fn unknown_parameter_types_are_written_as_numbers() { let mut model = AuthorizationModel {