diff --git a/conformance/openfga-language b/conformance/openfga-language index da7beed..bf3fdbc 160000 --- a/conformance/openfga-language +++ b/conformance/openfga-language @@ -1 +1 @@ -Subproject commit da7beeda519e8cf9fbbe552b72fc9a2a4d7590e0 +Subproject commit bf3fdbc2f00a64385fc06292a961298744bb0276 diff --git a/crates/openfga-language/README.md b/crates/openfga-language/README.md index 6a627a1..9819789 100644 --- a/crates/openfga-language/README.md +++ b/crates/openfga-language/README.md @@ -12,6 +12,7 @@ Parse [OpenFGA](https://openfga.dev) DSL into `openfga-model` types and write si ```rust let model = openfga_language::parse("model\n schema 1.1\n\ntype user")?; +openfga_language::validate(&model)?; assert_eq!(model.schema_version, "1.1"); assert_eq!(model.type_definitions[0].r#type, "user"); assert_eq!(openfga_language::parse(&openfga_language::write(&model)?)?, model); diff --git a/crates/openfga-language/src/lib.rs b/crates/openfga-language/src/lib.rs index 3718d70..5621fae 100644 --- a/crates/openfga-language/src/lib.rs +++ b/crates/openfga-language/src/lib.rs @@ -4,8 +4,13 @@ extern crate alloc; mod lowering; +mod validation; mod writer; +pub use validation::{ + DslError, ErrorType, PositionRange, ValidationError, ValidationErrors, ValidationPosition, + validate, validate_dsl, +}; pub use writer::{WriteError, write}; use alloc::string::{String, ToString}; diff --git a/crates/openfga-language/src/validation.rs b/crates/openfga-language/src/validation.rs new file mode 100644 index 0000000..406737a --- /dev/null +++ b/crates/openfga-language/src/validation.rs @@ -0,0 +1,565 @@ +mod errors; +mod graph; +mod references; +mod source; + +use alloc::{ + collections::{BTreeMap, BTreeSet}, + format, + string::{String, ToString}, + vec::Vec, +}; +pub use errors::{ + DslError, ErrorType, PositionRange, ValidationError, ValidationErrors, ValidationPosition, +}; +use openfga_model::{ + AuthorizationModel, RelationReference, TypeDefinition, Userset, + relation_reference::RelationOrWildcard, userset::Userset as Rewrite, +}; +use source::Source; + +/// Validates an authorization model. +/// +/// # Errors +/// Returns ordered semantic diagnostics for an invalid model. +pub fn validate(model: &AuthorizationModel) -> Result<(), ValidationErrors> { + Validator::new(model, None).validate() +} + +/// Parses and validates an authorization model in DSL syntax. +/// +/// # Errors +/// Returns syntax errors before checking model semantics. +pub fn validate_dsl(dsl: &str) -> Result { + let model = crate::parse(dsl)?; + Validator::new(&model, Some(Source::new(dsl))).validate()?; + Ok(model) +} + +struct Validator<'model, 'source> { + model: &'model AuthorizationModel, + types: BTreeMap<&'model str, &'model TypeDefinition>, + relations: BTreeMap<&'model str, &'model BTreeMap>, + source: Option>, + errors: Vec, +} + +impl<'model, 'source> Validator<'model, 'source> { + /// Indexes type declarations with the last declaration taking precedence. + fn new(model: &'model AuthorizationModel, source: Option>) -> Self { + Self { + model, + types: model + .type_definitions + .iter() + .map(|definition| (definition.r#type.as_str(), definition)) + .collect(), + relations: model + .type_definitions + .iter() + .filter(|definition| !definition.relations.is_empty()) + .map(|definition| (definition.r#type.as_str(), &definition.relations)) + .collect(), + source, + errors: Vec::new(), + } + } + + /// Runs validation stages in diagnostic precedence order. + fn validate(mut self) -> Result<(), ValidationErrors> { + let schema = self.model.schema_version.as_str(); + if schema.is_empty() { + self.push( + ErrorType::SchemaVersionRequired, + "", + "schema version required".into(), + None, + None, + Some(0), + ); + } else if !matches!(schema, "1.1" | "1.2") { + let line = self + .source + .as_ref() + .and_then(|source| source.schema_line(schema)); + self.push( + if schema == "1.0" { + ErrorType::SchemaVersionUnsupported + } else { + ErrorType::InvalidSchema + }, + schema, + if schema == "1.0" { + "schema version no longer supported".into() + } else { + format!("invalid schema {schema}") + }, + None, + None, + line, + ); + } + self.validate_names(); + self.validate_references(); + if self.errors.is_empty() { + self.validate_duplicates(); + } + if self.errors.is_empty() { + self.validate_entries(); + } + self.validate_modules(); + self.validate_conditions(); + if self.errors.is_empty() { + Ok(()) + } else { + Err(ValidationErrors { + errors: self.errors, + }) + } + } + + /// Appends a diagnostic with its optional source position. + fn push( + &mut self, + error_type: ErrorType, + symbol: &str, + message: String, + type_name: Option<&str>, + relation: Option<&str>, + line: Option, + ) { + let mut error = ValidationError { + message, + error_type, + symbol: symbol.into(), + type_name: type_name.map(ToString::to_string), + relation: relation.map(ToString::to_string), + condition_name: (error_type == ErrorType::ConditionNotUsed).then(|| symbol.into()), + position: None, + }; + if let Some(source) = &self.source { + source.locate(&mut error, line); + } + self.errors.push(error); + } + + /// Appends a diagnostic attached to a relation definition. + fn relation_error( + &mut self, + error_type: ErrorType, + symbol: &str, + message: String, + definition: &TypeDefinition, + relation: &str, + ) { + let line = self + .source + .as_ref() + .and_then(|source| source.relation_line(&definition.r#type, relation)); + self.push( + error_type, + symbol, + message, + Some(&definition.r#type), + Some(relation), + line, + ); + } + + /// Checks reserved names and identifier bounds. + fn validate_names(&mut self) { + for definition in &self.model.type_definitions { + let name = definition.r#type.as_str(); + if name.is_empty() { + continue; + } + let line = self + .source + .as_ref() + .and_then(|source| source.type_line(name)); + if matches!(name, "self" | "this") { + self.push( + ErrorType::ReservedTypeKeywords, + name, + "a type cannot be named 'self' or 'this'.".into(), + None, + None, + line, + ); + } + if !valid_name(name, 254) { + self.push( + ErrorType::InvalidName, + name, + format!(r"type '{name}' does not match naming rule: '^[^:#@\*\s]{{1,254}}$'."), + None, + None, + line, + ); + } + for relation in definition.relations.keys() { + let line = self + .source + .as_ref() + .and_then(|source| source.relation_line(name, relation)); + if matches!(relation.as_str(), "self" | "this") { + self.push( + ErrorType::ReservedRelationKeywords, + relation, + "a relation cannot be named 'self' or 'this'.".into(), + None, + None, + line, + ); + } + if !valid_name(relation, 50) { + self.push(ErrorType::InvalidName, relation, format!(r"relation '{relation}' of type '{name}' does not match naming rule: '^[^:#@\*\s]{{1,50}}$'."), None, None, line); + } + } + } + for name in self.model.conditions.keys() { + if !valid_condition_name(name) { + let line = self + .source + .as_ref() + .and_then(|source| source.condition_line(name)); + self.push( + ErrorType::InvalidName, + name, + format!(r"condition '{name}' does not match naming rule: '^[^\*\s]{{1,50}}$'."), + None, + None, + line, + ); + } + } + } + + /// Checks duplicate types, restrictions, and immediate rewrite children. + fn validate_duplicates(&mut self) { + let mut names = BTreeSet::new(); + for definition in &self.model.type_definitions { + let name = definition.r#type.as_str(); + if name.is_empty() { + continue; + } + if !names.insert(name) { + let line = self + .source + .as_ref() + .and_then(|source| source.type_line(name)); + self.push( + ErrorType::DuplicatedError, + name, + format!("the type `{name}` is a duplicate."), + Some(name), + None, + line, + ); + } + let Some(metadata) = &definition.metadata else { + continue; + }; + for (relation, metadata) in &metadata.relations { + let mut restrictions = BTreeSet::new(); + for restriction in &metadata.directly_related_user_types { + if restriction.r#type.is_empty() { + continue; + } + let key = ( + restriction.r#type.as_str(), + restriction_relation(restriction), + matches!( + restriction.relation_or_wildcard, + Some(RelationOrWildcard::Wildcard(_)) + ), + restriction.condition.as_str(), + ); + if !restrictions.insert(key) { + let symbol = restriction_name(restriction); + let line = self + .source + .as_ref() + .and_then(|source| source.relation_line(name, relation)); + self.push(ErrorType::DuplicatedError, &symbol, format!("the type restriction `{symbol}` is a duplicate in the relation `{relation}`."), Some(name), Some(relation), line); + } + } + let Some(rewrite) = definition + .relations + .get(relation) + .and_then(|userset| userset.userset.as_ref()) + else { + continue; + }; + match rewrite { + Rewrite::Union(children) | Rewrite::Intersection(children) => { + let mut names = BTreeSet::new(); + for child in &children.child { + if let Some(key) = rewrite_key(child) + && !names.insert(key) + { + self.duplicate_relation(&rewrite_symbol(key), definition, relation); + } + } + } + Rewrite::Difference(difference) => { + if let Some(key) = difference.base.as_deref().and_then(rewrite_key) + && difference.subtract.as_deref().and_then(rewrite_key) == Some(key) + { + self.duplicate_relation(&rewrite_symbol(key), definition, relation); + } + } + _ => {} + } + } + } + } + + /// Reports a repeated immediate rewrite child. + fn duplicate_relation(&mut self, symbol: &str, definition: &TypeDefinition, relation: &str) { + self.relation_error(ErrorType::DuplicatedError, symbol, format!("the partial relation definition `{symbol}` is a duplicate in the relation `{relation}`."), definition, relation); + } + + /// Checks condition names and references from restrictions. + fn validate_conditions(&mut self) { + let mut used: BTreeMap<&str, Vec<(&TypeDefinition, &str)>> = BTreeMap::new(); + for definition in &self.model.type_definitions { + if let Some(metadata) = &definition.metadata { + for (relation, metadata) in &metadata.relations { + for restriction in &metadata.directly_related_user_types { + if !restriction.condition.is_empty() { + used.entry(&restriction.condition) + .or_default() + .push((definition, relation)); + } + } + } + } + } + for (condition, uses) in &used { + if *condition != "$expression" && !self.model.conditions.contains_key(*condition) { + for (definition, relation) in uses { + self.relation_error( + ErrorType::ConditionNotDefined, + condition, + format!("`{condition}` is not a defined condition in the model."), + definition, + relation, + ); + } + } + } + for (name, condition) in &self.model.conditions { + if name != &condition.name { + self.push( + ErrorType::DifferentNestedConditionName, + &condition.name, + format!( + "condition key is `{name}` but nested name property is {}", + condition.name + ), + None, + None, + None, + ); + } + } + for name in self.model.conditions.keys() { + if !used.contains_key(name.as_str()) { + let line = self + .source + .as_ref() + .and_then(|source| source.condition_line(name)); + self.push( + ErrorType::ConditionNotUsed, + name, + format!("`{name}` condition is not used in the model."), + None, + None, + line, + ); + } + } + } + + /// Checks that source-file metadata names at most one module. + fn validate_modules(&mut self) { + let mut modules = Vec::new(); + for definition in &self.model.type_definitions { + if let Some(metadata) = &definition.metadata { + record_module( + &mut modules, + metadata.source_info.as_ref(), + &metadata.module, + ); + } + } + for definition in &self.model.type_definitions { + if let Some(metadata) = &definition.metadata { + for (name, relation) in &metadata.relations { + if definition.relations.contains_key(name) { + record_module( + &mut modules, + relation + .source_info + .as_ref() + .filter(|source| !source.file.is_empty()) + .or(metadata.source_info.as_ref()), + if relation.module.is_empty() { + &metadata.module + } else { + &relation.module + }, + ); + } + } + } + } + for condition in self.model.conditions.values() { + if let Some(metadata) = &condition.metadata { + record_module( + &mut modules, + metadata.source_info.as_ref(), + &metadata.module, + ); + } + } + for (file, modules) in modules { + if modules.len() > 1 { + self.push(ErrorType::MultipleModulesInFile, &file, format!("file {file} would contain multiple module definitions ({}) when transforming to DSL. Only one module can be defined per file.", modules.join(", ")), None, None, None); + } + } + } +} + +/// Records distinct modules in discovery order for each source file. +fn record_module<'model>( + modules: &mut Vec<(String, Vec<&'model str>)>, + source: Option<&'model openfga_model::SourceInfo>, + module: &'model str, +) { + if let Some(source) = source.filter(|source| !source.file.is_empty() && !module.is_empty()) { + let file = clean_file(&source.file); + if let Some((_, names)) = modules.iter_mut().find(|(name, _)| *name == file) { + if !names.contains(&module) { + names.push(module); + } + } else { + modules.push((file, alloc::vec![module])); + } + } +} + +/// Normalizes Unix source paths without accessing a filesystem. +fn clean_file(file: &str) -> String { + let absolute = file.starts_with('/'); + let mut parts = Vec::new(); + for part in file.split('/') { + match part { + "" | "." => {} + ".." if parts.last().is_some_and(|part| *part != "..") => { + parts.pop(); + } + ".." if absolute => {} + _ => parts.push(part), + } + } + let mut normalized = if absolute { + String::from("/") + } else { + String::new() + }; + normalized.push_str(&parts.join("/")); + if normalized.is_empty() { + normalized.push('.'); + } + normalized +} + +/// Checks identifier characters and Unicode scalar length. +fn valid_name(name: &str, maximum: usize) -> bool { + !name.is_empty() + && name.chars().count() <= maximum + && !name.chars().any(|character| { + matches!( + character, + ':' | '#' | '@' | '*' | ' ' | '\t' | '\n' | '\r' | '\u{c}' + ) + }) +} + +/// Checks a condition's name characters and length. +fn valid_condition_name(name: &str) -> bool { + !name.is_empty() + && name.chars().count() <= 50 + && !name + .chars() + .any(|character| matches!(character, '*' | ' ' | '\t' | '\n' | '\r' | '\u{c}')) +} + +/// Borrows the direct restrictions of a relation. +fn restrictions<'model>( + definition: &'model TypeDefinition, + relation: &str, +) -> &'model [RelationReference] { + definition + .metadata + .as_ref() + .and_then(|metadata| metadata.relations.get(relation)) + .map_or(&[], |metadata| { + metadata.directly_related_user_types.as_slice() + }) +} + +/// Borrows a nonempty relation restriction. +fn restriction_relation(restriction: &RelationReference) -> Option<&str> { + match restriction.relation_or_wildcard.as_ref() { + Some(RelationOrWildcard::Relation(relation)) if !relation.is_empty() => Some(relation), + _ => None, + } +} + +/// Renders a restriction for a diagnostic. +fn restriction_name(restriction: &RelationReference) -> String { + let mut name = restriction.r#type.clone(); + match restriction.relation_or_wildcard.as_ref() { + Some(RelationOrWildcard::Relation(relation)) if !relation.is_empty() => { + name.push('#'); + name.push_str(relation); + } + Some(RelationOrWildcard::Wildcard(_)) => name.push_str(":*"), + _ => {} + } + if !restriction.condition.is_empty() { + name.push_str(" with "); + name.push_str(&restriction.condition); + } + name +} + +/// Identifies a computed or tuple-to-userset rewrite without allocation. +fn rewrite_key(userset: &Userset) -> Option<(&str, Option<&str>)> { + match userset.userset.as_ref()? { + Rewrite::ComputedUserset(computed) if !computed.relation.is_empty() => { + Some((&computed.relation, None)) + } + Rewrite::TupleToUserset(tuple) => { + let target = tuple.computed_userset.as_ref()?.relation.as_str(); + if target.is_empty() { + return None; + } + let parent = tuple + .tupleset + .as_ref() + .map(|tupleset| tupleset.relation.as_str()) + .filter(|parent| !parent.is_empty()); + Some((target, parent)) + } + _ => None, + } +} + +/// Renders a rewrite key for a diagnostic. +fn rewrite_symbol((target, parent): (&str, Option<&str>)) -> String { + parent.map_or_else(|| target.into(), |parent| format!("{target} from {parent}")) +} diff --git a/crates/openfga-language/src/validation/errors.rs b/crates/openfga-language/src/validation/errors.rs new file mode 100644 index 0000000..46531a6 --- /dev/null +++ b/crates/openfga-language/src/validation/errors.rs @@ -0,0 +1,172 @@ +use alloc::{string::String, vec::Vec}; +use core::fmt; + +/// A semantic validation rule. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +#[non_exhaustive] +pub enum ErrorType { + /// Missing schema version. + #[error("schema-version-required")] + SchemaVersionRequired, + /// Retired schema version. + #[error("schema-version-unsupported")] + SchemaVersionUnsupported, + /// Reserved type name. + #[error("reserved-type-keywords")] + ReservedTypeKeywords, + /// Reserved relation name. + #[error("reserved-relation-keywords")] + ReservedRelationKeywords, + /// Invalid identifier. + #[error("invalid-name")] + InvalidName, + /// Missing relation definition. + #[error("missing-definition")] + MissingDefinition, + /// Undefined relation on a type. + #[error("invalid-relation-type")] + InvalidRelationType, + /// Undefined relation on tupleset targets. + #[error("invalid-relation-on-tupleset")] + InvalidRelationOnTupleset, + /// Undefined type. + #[error("invalid-type")] + InvalidType, + /// Relation without an entry point. + #[error("relation-no-entry-point")] + RelationNoEntrypoint, + /// Indirect tupleset relation. + #[error("tupleuserset-not-direct")] + TuplesetNotDirect, + /// Duplicate definition. + #[error("duplicated-error")] + DuplicatedError, + /// Invalid schema version. + #[error("invalid-schema")] + InvalidSchema, + /// Undefined condition. + #[error("condition-not-defined")] + ConditionNotDefined, + /// Unused condition. + #[error("condition-not-used")] + ConditionNotUsed, + /// Condition key differs from its nested name. + #[error("different-nested-condition-name")] + DifferentNestedConditionName, + /// Multiple modules assigned to one source file. + #[error("multiple-modules-in-file")] + MultipleModulesInFile, +} + +impl ErrorType { + /// Returns the stable diagnostic identifier. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::SchemaVersionRequired => "schema-version-required", + Self::SchemaVersionUnsupported => "schema-version-unsupported", + Self::ReservedTypeKeywords => "reserved-type-keywords", + Self::ReservedRelationKeywords => "reserved-relation-keywords", + Self::InvalidName => "invalid-name", + Self::MissingDefinition => "missing-definition", + Self::InvalidRelationType => "invalid-relation-type", + Self::InvalidRelationOnTupleset => "invalid-relation-on-tupleset", + Self::InvalidType => "invalid-type", + Self::RelationNoEntrypoint => "relation-no-entry-point", + Self::TuplesetNotDirect => "tupleuserset-not-direct", + Self::DuplicatedError => "duplicated-error", + Self::InvalidSchema => "invalid-schema", + Self::ConditionNotDefined => "condition-not-defined", + Self::ConditionNotUsed => "condition-not-used", + Self::DifferentNestedConditionName => "different-nested-condition-name", + Self::MultipleModulesInFile => "multiple-modules-in-file", + } + } +} + +/// A zero-based diagnostic range. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PositionRange { + /// Inclusive start. + pub start: usize, + /// Exclusive column end or inclusive line end. + pub end: usize, +} + +/// A diagnostic location in DSL source. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ValidationPosition { + /// Zero-based line range. + pub line: PositionRange, + /// Zero-based UTF-8 byte column range. + pub column: PositionRange, +} + +/// A semantic validation diagnostic. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +#[error("{error_type} error{location}: {message}", location = Location(.position.as_ref()))] +pub struct ValidationError { + /// Diagnostic message. + pub message: String, + /// Failed rule. + pub error_type: ErrorType, + /// Offending symbol. + pub symbol: String, + /// Associated type. + pub type_name: Option, + /// Associated relation. + pub relation: Option, + /// Associated condition. + pub condition_name: Option, + /// Source position when validating DSL. + pub position: Option, +} + +struct Location<'source>(Option<&'source ValidationPosition>); + +impl fmt::Display for Location<'_> { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + let Some(position) = self.0 else { + return Ok(()); + }; + let line = position.line.start; + let column = position.column.start; + write!(formatter, " at line={line}, column={column}") + } +} + +/// Diagnostics in rule order, then type declaration order and relation or condition name order. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +#[error("{diagnostics}", diagnostics = Diagnostics(.errors))] +pub struct ValidationErrors { + /// Diagnostics in validation order. + pub errors: Vec, +} + +struct Diagnostics<'errors>(&'errors [ValidationError]); + +impl fmt::Display for Diagnostics<'_> { + 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") + } +} + +/// A syntax or semantic DSL error. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum DslError { + /// Invalid DSL syntax. + #[error(transparent)] + Syntax(#[from] crate::ParseError), + /// Invalid model semantics. + #[error(transparent)] + Semantic(#[from] ValidationErrors), +} diff --git a/crates/openfga-language/src/validation/graph.rs b/crates/openfga-language/src/validation/graph.rs new file mode 100644 index 0000000..912b8f0 --- /dev/null +++ b/crates/openfga-language/src/validation/graph.rs @@ -0,0 +1,192 @@ +use super::{ErrorType, Rewrite, Validator, restriction_relation, restrictions}; +use alloc::{collections::BTreeMap, format, vec::Vec}; +use openfga_model::{TypeDefinition, Userset}; + +#[derive(Clone, Copy, Default)] +struct Entry { + reachable: bool, + cycle: bool, +} + +impl Validator<'_, '_> { + /// Reports relations without a reachable direct assignment. + pub(super) fn validate_entries(&mut self) { + let mut visited = Vec::new(); + for definition in &self.model.type_definitions { + for (relation, rewrite) in &definition.relations { + let entry = entrypoint(&self.types, definition, relation, rewrite, &mut visited); + if !entry.reachable { + let reason = if entry.cycle { + "potential loop" + } else { + "no entrypoint" + }; + self.relation_error( + ErrorType::RelationNoEntrypoint, + relation, + format!( + "`{relation}` is an impossible relation for `{}` ({reason}).", + definition.r#type + ), + definition, + relation, + ); + } + } + } + } +} + +/// Traverses a relation while retaining only the current dependency path. +fn entrypoint<'model>( + types: &BTreeMap<&'model str, &'model TypeDefinition>, + definition: &'model TypeDefinition, + relation: &'model str, + rewrite: &'model Userset, + visited: &mut Vec<(&'model str, &'model str)>, +) -> Entry { + if relation.is_empty() { + return Entry::default(); + } + let depth = visited.len(); + visited.push((&definition.r#type, relation)); + let result = inspect(types, definition, relation, rewrite, visited); + visited.truncate(depth); + result +} + +/// Evaluates the entry-point requirements of a rewrite. +fn inspect<'model>( + types: &BTreeMap<&'model str, &'model TypeDefinition>, + definition: &'model TypeDefinition, + relation: &'model str, + rewrite: &'model Userset, + visited: &mut Vec<(&'model str, &'model str)>, +) -> Entry { + let type_name = definition.r#type.as_str(); + match rewrite.userset.as_ref() { + Some(Rewrite::This(_)) => direct_entry(types, definition, relation, visited), + Some(Rewrite::ComputedUserset(computed)) => { + let target_relation = computed.relation.as_str(); + if target_relation.is_empty() { + return Entry::default(); + } + let Some(target) = definition.relations.get(target_relation) else { + return Entry::default(); + }; + if visited.contains(&(type_name, target_relation)) { + Entry { + reachable: false, + cycle: true, + } + } else { + entrypoint(types, definition, target_relation, target, visited) + } + } + Some(Rewrite::TupleToUserset(tuple)) => { + let Some((parent, target)) = + tuple.tupleset.as_ref().zip(tuple.computed_userset.as_ref()) + else { + return Entry::default(); + }; + if parent.relation.is_empty() + || target.relation.is_empty() + || !definition.relations.contains_key(&parent.relation) + { + return Entry::default(); + } + for restriction in restrictions(definition, &parent.relation) { + let target_type = restriction.r#type.as_str(); + let target_relation = target.relation.as_str(); + if let Some(target_definition) = types.get(target_type).copied() + && let Some(rewrite) = target_definition.relations.get(target_relation) + && !visited.contains(&(target_type, target_relation)) + && entrypoint(types, target_definition, target_relation, rewrite, visited) + .reachable + { + return Entry { + reachable: true, + cycle: false, + }; + } + } + Entry::default() + } + Some(Rewrite::Union(children)) => { + let mut cycle = false; + for child in &children.child { + let result = entrypoint(types, definition, relation, child, visited); + if result.reachable { + return Entry { + reachable: true, + cycle: false, + }; + } + cycle |= result.cycle; + } + Entry { + reachable: false, + cycle, + } + } + Some(Rewrite::Intersection(children)) => { + for child in &children.child { + let result = entrypoint(types, definition, relation, child, visited); + if !result.reachable { + return result; + } + } + Entry { + reachable: true, + cycle: false, + } + } + Some(Rewrite::Difference(difference)) => { + let Some(base) = difference.base.as_deref() else { + return Entry::default(); + }; + let base = entrypoint(types, definition, relation, base, visited); + if !base.reachable { + return base; + } + let Some(subtract) = difference.subtract.as_deref() else { + return Entry::default(); + }; + entrypoint(types, definition, relation, subtract, visited) + } + _ => Entry::default(), + } +} + +/// Follows userset restrictions until a concrete user type is reachable. +fn direct_entry<'model>( + types: &BTreeMap<&'model str, &'model TypeDefinition>, + definition: &'model TypeDefinition, + relation: &str, + visited: &mut Vec<(&'model str, &'model str)>, +) -> Entry { + for restriction in restrictions(definition, relation) { + let Some(target_relation) = restriction_relation(restriction) else { + return Entry { + reachable: true, + cycle: false, + }; + }; + let target_type = restriction.r#type.as_str(); + let Some(target_definition) = types.get(target_type).copied() else { + return Entry::default(); + }; + let Some(target) = target_definition.relations.get(target_relation) else { + return Entry::default(); + }; + if !visited.contains(&(target_type, target_relation)) + && entrypoint(types, target_definition, target_relation, target, visited).reachable + { + return Entry { + reachable: true, + cycle: false, + }; + } + } + Entry::default() +} diff --git a/crates/openfga-language/src/validation/references.rs b/crates/openfga-language/src/validation/references.rs new file mode 100644 index 0000000..1cf37e1 --- /dev/null +++ b/crates/openfga-language/src/validation/references.rs @@ -0,0 +1,172 @@ +use super::{ + ErrorType, RelationOrWildcard, Rewrite, Validator, restriction_relation, restrictions, +}; +use alloc::format; +use openfga_model::{TupleToUserset, TypeDefinition, Userset}; + +impl Validator<'_, '_> { + /// Checks restrictions before rewrites in type and relation-name order. + pub(super) fn validate_references(&mut self) { + for definition in &self.model.type_definitions { + if !core::ptr::eq(self.types[definition.r#type.as_str()], definition) { + continue; + } + if let Some(metadata) = &definition.metadata { + for relation in metadata.relations.keys() { + self.validate_direct(definition, relation); + } + } + for (relation, rewrite) in &definition.relations { + self.validate_rewrite(definition, relation, rewrite); + } + } + } + + /// Checks each leaf of a relation rewrite in depth-first order. + fn validate_rewrite(&mut self, definition: &TypeDefinition, relation: &str, rewrite: &Userset) { + match rewrite.userset.as_ref() { + Some(Rewrite::Union(children) | Rewrite::Intersection(children)) => { + for child in &children.child { + self.validate_rewrite(definition, relation, child); + } + } + Some(Rewrite::Difference(difference)) => { + for child in [difference.base.as_deref(), difference.subtract.as_deref()] + .into_iter() + .flatten() + { + self.validate_rewrite(definition, relation, child); + } + } + Some(Rewrite::ComputedUserset(computed)) if !computed.relation.is_empty() => { + if !self.relations[definition.r#type.as_str()].contains_key(&computed.relation) { + self.relation_error( + ErrorType::MissingDefinition, + &computed.relation, + format!("the relation `{}` does not exist.", computed.relation), + definition, + relation, + ); + } + } + Some(Rewrite::TupleToUserset(tuple)) => { + self.validate_tuple(definition, relation, tuple); + } + _ => {} + } + } + + /// Checks referenced types and their relation restrictions. + fn validate_direct(&mut self, definition: &TypeDefinition, relation: &str) { + for restriction in restrictions(definition, relation) { + if restriction.r#type.is_empty() { + continue; + } + if !self.types.contains_key(restriction.r#type.as_str()) { + self.relation_error( + ErrorType::InvalidType, + &restriction.r#type, + format!("`{}` is not a valid type.", restriction.r#type), + definition, + relation, + ); + continue; + } + if let Some(target_relation) = restriction_relation(restriction) + && !self + .relations + .get(restriction.r#type.as_str()) + .is_some_and(|relations| relations.contains_key(target_relation)) + { + let symbol = format!("{}#{target_relation}", restriction.r#type); + let line = self + .source + .as_ref() + .and_then(|source| source.relation_line(&definition.r#type, relation)); + self.push( + ErrorType::InvalidRelationType, + &symbol, + format!( + "`{target_relation}` is not a valid relation for `{}`.", + restriction.r#type + ), + Some(&restriction.r#type), + Some(relation), + line, + ); + } + } + } + + /// Checks that a tupleset is direct and exposes the computed relation. + fn validate_tuple( + &mut self, + definition: &TypeDefinition, + relation: &str, + tuple: &TupleToUserset, + ) { + let target = tuple + .computed_userset + .as_ref() + .map_or("", |computed| computed.relation.as_str()); + let parent = tuple + .tupleset + .as_ref() + .map_or("", |tupleset| tupleset.relation.as_str()); + if parent.is_empty() || target.is_empty() { + return; + } + let symbol = format!("{target} from {parent}"); + let Some(parent_rewrite) = self.relations[definition.r#type.as_str()].get(parent) else { + self.relation_error( + ErrorType::InvalidRelationType, + &symbol, + format!( + "`{parent}` is not a valid relation for `{}`.", + definition.r#type + ), + definition, + relation, + ); + return; + }; + let allowed = restrictions(definition, parent); + if !matches!(parent_rewrite.userset, Some(Rewrite::This(_))) || allowed.is_empty() { + self.indirect_tuple(definition, relation, parent); + return; + } + let mut invalid_targets = 0; + for restriction in allowed { + if restriction_relation(restriction).is_some() + || matches!( + restriction.relation_or_wildcard, + Some(RelationOrWildcard::Wildcard(_)) + ) + { + self.indirect_tuple(definition, relation, parent); + } else if !self + .relations + .get(restriction.r#type.as_str()) + .is_some_and(|relations| relations.contains_key(target)) + { + invalid_targets += 1; + } + } + if invalid_targets == allowed.len() { + for restriction in allowed { + self.relation_error(ErrorType::InvalidRelationOnTupleset, &symbol, format!("the `{target}` relation definition on type `{}` is not valid: `{target}` does not exist on `{parent}`, which is of type `{}`.", definition.r#type, restriction.r#type), definition, relation); + } + } + } + + /// Reports a tupleset that cannot contain only direct objects. + fn indirect_tuple(&mut self, definition: &TypeDefinition, relation: &str, parent: &str) { + self.relation_error( + ErrorType::TuplesetNotDirect, + parent, + format!("`{parent}` relation used inside from allows only direct relation."), + definition, + relation, + ); + } +} diff --git a/crates/openfga-language/src/validation/source.rs b/crates/openfga-language/src/validation/source.rs new file mode 100644 index 0000000..02d1383 --- /dev/null +++ b/crates/openfga-language/src/validation/source.rs @@ -0,0 +1,155 @@ +use super::{ErrorType, PositionRange, ValidationError, ValidationPosition}; +use alloc::{borrow::Cow, format, string::String, vec::Vec}; + +pub(super) struct Source<'source> { + lines: Vec<&'source str>, +} + +impl<'source> Source<'source> { + /// Retains source lines for diagnostic lookup. + pub(super) fn new(source: &'source str) -> Self { + Self { + lines: source.split('\n').collect(), + } + } + + /// Finds a type declaration by its complete name. + pub(super) fn type_line(&self, name: &str) -> Option { + let prefix = format!("type {name}"); + self.lines + .iter() + .position(|line| declaration_matches(line, &prefix)) + } + + /// Finds a relation declaration after its enclosing type. + pub(super) fn relation_line(&self, type_name: &str, relation: &str) -> Option { + let start = self.type_line(type_name).unwrap_or_default(); + let prefix = format!("define {relation}"); + self.lines + .iter() + .enumerate() + .skip(start) + .find_map(|(index, line)| declaration_matches(line, &prefix).then_some(index)) + } + + /// Finds a condition declaration by its complete name. + pub(super) fn condition_line(&self, name: &str) -> Option { + let prefix = format!("condition {name}"); + self.lines + .iter() + .position(|line| declaration_matches(line, &prefix)) + } + + /// Finds a schema declaration with an optional trailing comment. + pub(super) fn schema_line(&self, schema: &str) -> Option { + let prefix = format!("schema {schema}"); + self.lines.iter().position(|line| { + normalize_spaces(line) + .strip_prefix(&prefix) + .is_some_and(trailing_comment) + }) + } + + /// Attaches a zero-based source span to a diagnostic. + pub(super) fn locate(&self, error: &mut ValidationError, line: Option) { + let Some((line, raw_line)) = + line.and_then(|index| self.lines.get(index).map(|text| (index, *text))) + else { + return; + }; + let symbol = error.symbol.as_str(); + let offset = match error.error_type { + ErrorType::InvalidType => raw_line.find(':').map_or(0, |separator| { + separator + 1 + word_offset(&raw_line[separator + 1..], symbol) + }), + ErrorType::TuplesetNotDirect => raw_line.find("from").map_or(0, |offset| { + let start = offset + 4; + start + raw_line[start..].find(symbol).unwrap_or_default() + }), + _ => word_offset(raw_line, symbol), + }; + error.position = Some(ValidationPosition { + line: PositionRange { + start: line, + end: line, + }, + column: PositionRange { + start: offset, + end: offset + symbol.len(), + }, + }); + } +} + +/// Recognizes an empty suffix or a whitespace-separated comment. +fn trailing_comment(suffix: &str) -> bool { + suffix.is_empty() + || (suffix.starts_with(char::is_whitespace) && suffix.trim_start().starts_with('#')) +} + +/// Matches a declaration prefix without accepting a longer identifier. +fn declaration_matches(line: &str, prefix: &str) -> bool { + normalize_spaces(line) + .strip_prefix(prefix) + .is_some_and(|suffix| { + suffix.as_bytes().first().is_none_or(|byte| { + !byte.is_ascii_alphanumeric() && !matches!(byte, b'_' | b'-' | b'/' | b'.') + }) + }) +} + +/// Collapses inline lexer whitespace without copying normalized lines. +fn normalize_spaces(line: &str) -> Cow<'_, str> { + let line = line.trim(); + if !line.contains(['\t', '\u{c}']) && !line.contains(" ") { + return Cow::Borrowed(line); + } + let mut normalized = String::with_capacity(line.len()); + let mut previous_space = false; + for character in line.chars() { + let space = matches!(character, ' ' | '\t' | '\u{c}'); + if !space { + normalized.push(character); + } else if !previous_space { + normalized.push(' '); + } + previous_space = space; + } + Cow::Owned(normalized) +} + +/// Prefers ASCII word boundaries, then the first literal occurrence. +fn word_offset(line: &str, symbol: &str) -> usize { + if symbol.is_empty() { + return 0; + } + if symbol + .as_bytes() + .first() + .copied() + .is_some_and(word_character) + && symbol + .as_bytes() + .last() + .copied() + .is_some_and(word_character) + { + for (offset, _) in line.match_indices(symbol) { + let before = offset + .checked_sub(1) + .and_then(|index| line.as_bytes().get(index)); + let after = line.as_bytes().get(offset + symbol.len()); + if !before.copied().is_some_and(word_character) + && !after.copied().is_some_and(word_character) + { + return offset; + } + } + } + line.find(symbol).unwrap_or_default() +} + +/// Recognizes ASCII word characters used by source lookup. +fn word_character(character: u8) -> bool { + character.is_ascii_alphanumeric() || character == b'_' +} diff --git a/crates/openfga-language/tests/validation.rs b/crates/openfga-language/tests/validation.rs new file mode 100644 index 0000000..6cdf594 --- /dev/null +++ b/crates/openfga-language/tests/validation.rs @@ -0,0 +1,504 @@ +//! Semantic validation conformance. +use openfga_language::{DslError, ValidationErrors, parse, validate, validate_dsl}; +use openfga_model::AuthorizationModel; +use serde::Deserialize; +use serde_json::{Value, json}; + +#[derive(Deserialize)] +struct Case { + name: String, + #[serde(default)] + dsl: String, + #[serde(default)] + json: String, + #[serde(default)] + skip: bool, + expected_errors: Option>, +} + +/// Checks diagnostic rendering and every metadata field supplied by the corpus. +fn check_errors(case: &Case, result: Result<(), ValidationErrors>, positions: bool) { + let expected = case.expected_errors.as_deref().unwrap_or_default(); + assert_eq!( + result.is_err(), + !expected.is_empty(), + "{} {result:?}", + case.name + ); + let Err(errors) = result else { return }; + let descriptions: Vec = expected + .iter() + .map(|error| { + let kind = error["metadata"]["errorType"] + .as_str() + .unwrap_or("validation"); + let message = error["msg"].as_str().unwrap(); + if positions { + format!( + "{kind} error at line={}, column={}: {message}", + error["line"]["start"], error["column"]["start"] + ) + } else { + format!("{kind} error: {message}") + } + }) + .collect(); + assert_eq!( + errors.to_string(), + format!( + "{} error{} occurred:\n\t* {}\n\n", + expected.len(), + if expected.len() == 1 { "" } else { "s" }, + descriptions.join("\n\t* ") + ), + "{}", + case.name + ); + assert_eq!(errors.errors.len(), expected.len(), "{}", case.name); + for (actual, expected) in errors.errors.iter().zip(expected) { + assert_eq!( + actual.message, + expected["msg"].as_str().unwrap(), + "{}", + case.name + ); + let metadata = json!({ + "errorType": actual.error_type.as_str(), + "symbol": actual.symbol, + "typeName": actual.type_name, + "relation": actual.relation, + "conditionName": actual.condition_name, + }); + if let Some(expected_metadata) = expected["metadata"].as_object() { + for (key, value) in expected_metadata { + assert_eq!(&metadata[key], value, "{} metadata {key}", case.name); + } + } + if positions { + let position = actual.position.as_ref().expect("DSL diagnostic position"); + assert_eq!( + json!({"start": position.line.start, "end": position.line.end}), + expected["line"], + "{}", + case.name + ); + assert_eq!( + json!({"start": position.column.start, "end": position.column.end}), + expected["column"], + "{}", + case.name + ); + } + } +} + +/// Checks both validation entry points against semantic DSL cases. +#[test] +fn dsl_semantic_corpus() { + let cases: Vec = serde_norway::from_str(include_str!( + "../../../conformance/openfga-language/tests/data/dsl-semantic-validation-cases.yaml" + )) + .unwrap(); + assert!(!cases.is_empty()); + for case in cases.iter().filter(|case| !case.skip) { + let result = match validate_dsl(&case.dsl) { + Ok(_) => Ok(()), + Err(DslError::Semantic(errors)) => Err(errors), + Err(DslError::Syntax(error)) => panic!("{} syntax error {error}", case.name), + }; + check_errors(case, result, true); + let model = parse(&case.dsl).unwrap_or_else(|error| panic!("{} {error}", case.name)); + check_errors(case, validate(&model), false); + } +} + +/// Checks validation of deserialized authorization models. +#[test] +fn json_semantic_corpus() { + let cases: Vec = serde_norway::from_str(include_str!( + "../../../conformance/openfga-language/tests/data/json-validation-cases.yaml" + )) + .unwrap(); + assert!(!cases.is_empty()); + for case in cases.iter().filter(|case| !case.skip) { + let model: AuthorizationModel = serde_json::from_str(&case.json).unwrap_or_else(|error| { + panic!( + "{} cannot deserialize into AuthorizationModel {error}", + case.name + ) + }); + check_errors(case, validate(&model), false); + } +} + +/// Checks the reference validator result for metadata without a matching relation. +#[test] +fn orphan_relation_metadata() { + let model: AuthorizationModel = serde_json::from_value(json!({ + "schema_version": "1.1", + "type_definitions": [ + {"type": "user"}, + { + "type": "document", + "relations": {}, + "metadata": { + "relations": { + "orphan": { + "directly_related_user_types": [{"type": "user"}] + } + } + } + } + ] + })) + .unwrap(); + assert_eq!(validate(&model), Ok(())); +} + +/// Checks the complete DSL diagnostic text and source spans. +fn assert_dsl_diagnostics( + source: &str, + message: &str, + positions: &[Option<(usize, usize, usize)>], +) { + let Err(DslError::Semantic(errors)) = validate_dsl(source) else { + panic!("expected semantic diagnostics"); + }; + assert_eq!(errors.to_string(), message); + let actual: Vec<_> = errors + .errors + .iter() + .map(|error| { + error.position.map(|position| { + assert_eq!(position.line.start, position.line.end); + ( + position.line.start, + position.column.start, + position.column.end, + ) + }) + }) + .collect(); + assert_eq!(actual, positions); +} + +/// Checks the complete model diagnostic text and absence of source positions. +fn assert_json_diagnostics(model: Value, message: &str) { + let model: AuthorizationModel = serde_json::from_value(model).unwrap(); + let errors = validate(&model).unwrap_err(); + assert_eq!(errors.to_string(), message); + assert!(errors.errors.iter().all(|error| error.position.is_none())); +} + +/// Checks duplicate restrictions that include a named condition. +#[test] +fn duplicate_conditional_restriction() { + assert_dsl_diagnostics( + "model\n schema 1.1\ntype user\ntype document\n relations\n define viewer: [user with allowed, user with allowed]\ncondition allowed(value: int) {\n value > 0\n}\n", + "1 error occurred:\n\t* duplicated-error error at line=5, column=20: the type restriction `user with allowed` is a duplicate in the relation `viewer`.\n\n", + &[Some((5, 20, 37))], + ); +} + +/// Checks a duplicate whose restriction type occurs after the relation declaration. +#[test] +fn duplicate_before_restriction_type_declaration() { + assert_dsl_diagnostics( + "model\n schema 1.1\ntype document\n relations\n define viewer: [user, user]\ntype user\n", + "1 error occurred:\n\t* duplicated-error error at line=4, column=20: the type restriction `user` is a duplicate in the relation `viewer`.\n\n", + &[Some((4, 20, 24))], + ); +} + +/// Checks that reachable tuplesets and intersections do not hide a cyclic union. +#[test] +fn entrypoints_across_rewrite_operators() { + assert_dsl_diagnostics( + "model\n schema 1.1\ntype user\ntype folder\n relations\n define member: [user]\ntype document\n relations\n define parent: [folder]\n define reader: member from parent\n define writer: [user]\n define combined: reader and writer\n define cycle: cycle or cycle2\n define cycle2: cycle\n", + "2 errors occurred:\n\t* relation-no-entry-point error at line=12, column=11: `cycle` is an impossible relation for `document` (potential loop).\n\t* relation-no-entry-point error at line=13, column=11: `cycle2` is an impossible relation for `document` (potential loop).\n\n", + &[Some((12, 11, 16)), Some((13, 11, 17))], + ); +} + +/// Checks direct assignments without allowed types. +#[test] +fn direct_relation_without_restrictions() { + assert_json_diagnostics( + json!({"schema_version": "1.1", "type_definitions": [{ + "type": "document", "relations": {"viewer": {"this": {}}} + }]}), + "1 error occurred:\n\t* relation-no-entry-point error: `viewer` is an impossible relation for `document` (no entrypoint).\n\n", + ); +} + +/// Checks partially populated tuple-to-userset references. +#[test] +fn incomplete_tuple_references() { + for rewrite in [ + json!({"tupleset": {}, "computedUserset": {}}), + json!({"tupleset": {}, "computedUserset": {"relation": "missing"}}), + json!({"tupleset": {"relation": "parent"}, "computedUserset": {}}), + ] { + assert_json_diagnostics( + json!({"schema_version": "1.1", "type_definitions": [{ + "type": "document", "relations": {"viewer": {"tupleToUserset": rewrite}} + }]}), + "1 error occurred:\n\t* relation-no-entry-point error: `viewer` is an impossible relation for `document` (no entrypoint).\n\n", + ); + } +} + +/// Checks that metadata alone cannot supply a rewrite entry point. +#[test] +fn empty_rewrites_with_restrictions() { + for rewrite in [json!({}), json!({"computedUserset": {}})] { + assert_json_diagnostics( + json!({"schema_version": "1.1", "type_definitions": [ + {"type": "user"}, + { + "type": "document", + "relations": {"viewer": rewrite}, + "metadata": {"relations": {"viewer": { + "directly_related_user_types": [{"type": "user"}] + }}} + } + ]}), + "1 error occurred:\n\t* relation-no-entry-point error: `viewer` is an impossible relation for `document` (no entrypoint).\n\n", + ); + } +} + +/// Checks that one source file can contain several types in the same module. +#[test] +fn shared_module_source() { + let model: AuthorizationModel = serde_json::from_value(json!({ + "schema_version": "1.1", + "type_definitions": [ + {"type": "user", "metadata": { + "module": "shared", "source_info": {"file": "shared.fga"} + }}, + {"type": "document", "metadata": { + "module": "shared", "source_info": {"file": "shared.fga"} + }} + ] + })) + .unwrap(); + assert_eq!(validate(&model), Ok(())); +} + +/// Checks a tuple-to-userset rewrite without its tupleset component. +#[test] +fn missing_tupleset_component() { + assert_json_diagnostics( + json!({"schema_version": "1.1", "type_definitions": [ + {"type": "user"}, + { + "type": "document", + "relations": {"viewer": {"tupleToUserset": {"computedUserset": {}}}}, + "metadata": {"relations": {"viewer": { + "directly_related_user_types": [{"type": "user"}] + }}} + } + ]}), + "1 error occurred:\n\t* relation-no-entry-point error: `viewer` is an impossible relation for `document` (no entrypoint).\n\n", + ); +} + +/// Checks a difference rewrite without its subtract operand. +#[test] +fn missing_difference_operand() { + assert_json_diagnostics( + json!({"schema_version": "1.1", "type_definitions": [ + {"type": "user"}, + { + "type": "document", + "relations": {"viewer": {"difference": {"base": {"this": {}}}}}, + "metadata": {"relations": {"viewer": { + "directly_related_user_types": [{"type": "user"}] + }}} + } + ]}), + "1 error occurred:\n\t* relation-no-entry-point error: `viewer` is an impossible relation for `document` (no entrypoint).\n\n", + ); +} + +#[test] +fn retired_schema() { + assert_json_diagnostics( + json!({"schema_version": "1.0"}), + "1 error occurred:\n\t* schema-version-unsupported error: schema version no longer supported\n\n", + ); +} + +#[test] +fn empty_type_and_restriction_names() { + let empty_types = serde_json::from_value(json!({ + "schema_version": "1.1", + "type_definitions": [{"type": ""}, {"type": ""}] + })) + .unwrap(); + assert_eq!(validate(&empty_types), Ok(())); + assert_json_diagnostics( + json!({"schema_version": "1.1", "type_definitions": [{ + "type": "", "relations": {"": {"this": {}}} + }]}), + "1 error occurred:\n\t* relation-no-entry-point error: `` is an impossible relation for `` (no entrypoint).\n\n", + ); + for empty_type in [false, true] { + let mut definitions = vec![json!({ + "type": "document", + "relations": {"viewer": {"this": {}}}, + "metadata": {"relations": {"viewer": { + "directly_related_user_types": [ + {"type": "", "relation": "missing"}, + {"type": "", "relation": "missing"} + ] + }}} + })]; + if empty_type { + definitions.push(json!({"type": ""})); + } + assert_json_diagnostics( + json!({"schema_version": "1.1", "type_definitions": definitions}), + "1 error occurred:\n\t* relation-no-entry-point error: `viewer` is an impossible relation for `document` (no entrypoint).\n\n", + ); + } + let empty_restrictions = serde_json::from_value(json!({ + "schema_version": "1.1", "type_definitions": [{ + "type": "document", + "relations": {"viewer": {"this": {}}}, + "metadata": {"relations": {"viewer": { + "directly_related_user_types": [{"type": ""}, {"type": ""}] + }}} + }] + })) + .unwrap(); + assert_eq!(validate(&empty_restrictions), Ok(())); +} + +#[test] +fn condition_name_rules() { + for name in ["*bad".to_owned(), "a".repeat(51)] { + assert_json_diagnostics( + json!({"schema_version": "1.1", "conditions": {&name: {"name": name}}}), + &format!( + "2 errors occurred:\n\t* invalid-name error: condition '{name}' does not match naming rule: '^[^\\*\\s]{{1,50}}$'.\n\t* condition-not-used error: `{name}` condition is not used in the model.\n\n" + ), + ); + } + for name in [ + "é".repeat(50), + "\u{b}".to_owned(), + "\u{a0}".to_owned(), + "@:#".to_owned(), + ] { + assert_json_diagnostics( + json!({"schema_version": "1.1", "conditions": {&name: {"name": name}}}), + &format!( + "1 error occurred:\n\t* condition-not-used error: `{name}` condition is not used in the model.\n\n" + ), + ); + } +} + +#[test] +fn normalized_module_paths() { + for (first, second) in [ + ("./folder/../shared.fga", "shared.fga"), + ("/../../shared.fga", "/shared.fga"), + ("a/..", "."), + ("../a/../shared.fga", "../shared.fga"), + ] { + assert_json_diagnostics( + json!({"schema_version": "1.1", "type_definitions": [ + {"type": "first", "metadata": {"module": "first", "source_info": {"file": first}}}, + {"type": "second", "metadata": {"module": "second", "source_info": {"file": second}}} + ]}), + &format!( + "1 error occurred:\n\t* multiple-modules-in-file error: file {second} would contain multiple module definitions (first, second) when transforming to DSL. Only one module can be defined per file.\n\n" + ), + ); + } +} + +#[test] +fn incomplete_difference_entrypoints() { + for (difference, reason) in [ + (json!({"subtract": {"this": {}}}), "no entrypoint"), + ( + json!({"base": {"computedUserset": {"relation": "viewer"}}}), + "potential loop", + ), + ] { + assert_json_diagnostics( + json!({"schema_version": "1.1", "type_definitions": [{ + "type": "document", "relations": {"viewer": {"difference": difference}} + }]}), + &format!( + "1 error occurred:\n\t* relation-no-entry-point error: `viewer` is an impossible relation for `document` ({reason}).\n\n" + ), + ); + } +} + +#[test] +fn diagnostics_follow_relation_name_order() { + assert_dsl_diagnostics( + "model\n schema 1.1\ntype document\n relations\n define zebra: missing_zebra\n define alpha: missing_alpha\n", + "2 errors occurred:\n\t* missing-definition error at line=5, column=18: the relation `missing_alpha` does not exist.\n\t* missing-definition error at line=4, column=18: the relation `missing_zebra` does not exist.\n\n", + &[Some((5, 18, 31)), Some((4, 18, 31))], + ); +} + +#[test] +fn condition_name_length_dsl() { + let name = "a".repeat(51); + assert_dsl_diagnostics( + &format!( + "model\n schema 1.1\ntype user\ncondition {name}(value: int) {{\n value > 0\n}}\n" + ), + &format!( + "2 errors occurred:\n\t* invalid-name error at line=3, column=10: condition '{name}' does not match naming rule: '^[^\\*\\s]{{1,50}}$'.\n\t* condition-not-used error at line=3, column=10: `{name}` condition is not used in the model.\n\n" + ), + &[Some((3, 10, 61)), Some((3, 10, 61))], + ); +} + +#[test] +fn extended_reserved_type_without_declaration_position() { + assert_dsl_diagnostics( + "module core\nextend type self\n relations\n define viewer: [self]\n", + "2 errors occurred:\n\t* schema-version-required error at line=0, column=0: schema version required\n\t* reserved-type-keywords error: a type cannot be named 'self' or 'this'.\n\n", + &[Some((0, 0, 0)), None], + ); +} + +#[test] +fn empty_tuple_operand_in_union() { + assert_json_diagnostics( + json!({"schema_version": "1.1", "type_definitions": [ + {"type": "user"}, + { + "type": "document", + "relations": {"viewer": {"union": {"child": [ + {"tupleToUserset": {"computedUserset": {}}} + ]}}}, + "metadata": {"relations": {"viewer": { + "directly_related_user_types": [{"type": "user"}] + }}} + } + ]}), + "1 error occurred:\n\t* relation-no-entry-point error: `viewer` is an impossible relation for `document` (no entrypoint).\n\n", + ); +} + +#[test] +fn shadowed_empty_type_with_missing_computed_relation() { + assert_json_diagnostics( + json!({"schema_version": "1.1", "type_definitions": [ + {"type": "", "relations": {"viewer": {"computedUserset": {"relation": "missing"}}}}, + {"type": ""} + ]}), + "1 error occurred:\n\t* relation-no-entry-point error: `viewer` is an impossible relation for `` (no entrypoint).\n\n", + ); +}