From 1ce4aaf9bc429a715abe94d382601ff1ac1b99b0 Mon Sep 17 00:00:00 2001 From: Wout Slabbinck Date: Mon, 16 Nov 2026 16:08:29 +0100 Subject: [PATCH 1/4] feat: implement rule subclass profiles implementation --- RELEASE_NOTES.md | 5 - src/profiles/Profile.ts | 306 +++++++++++++++++----------- src/shapes/Shapes.ts | 6 + src/shapes/modules/02-odrl-rule.ttl | 37 +++- src/shapes/odrl-shapes.ttl | 7 + src/util/Vocabulary.ts | 10 +- test/unit/Validator.test.ts | 49 +++-- 7 files changed, 283 insertions(+), 137 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index a14fb8d..57b1604 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -21,11 +21,6 @@ Adds validation of policies that use [ODRL profiles](https://www.w3.org/TR/odrl- - **Input without a policy**: input that contains no typed ODRL policy now returns `valid: false` with "No valid policy provided". - **Normalisation errors**: a failing normalisation step returns a result with the error instead of throwing. -### Known limitations -- **Profiles are not scoped per policy**: all loaded profiles are merged into one shape. Terms from one loaded profile are therefore accepted in a policy that declares only another profile, or no profile at all. -- **Profile policy types leak between instances**: the constructor modifies the shared `POLICY_TYPES` list, so profile policy types also count as policy types in validators created later. -- **Policy subclasses**: only profile subclasses of `odrl:Policy` itself are recognised as policy types, not subclasses of `odrl:Set`, `odrl:Offer`, etc. -- **New rule types**: a profile subclass of `odrl:Rule` has no property that links it to a policy, and profiles do not define one yet. ## 0.1.0 (2026-06-29) diff --git a/src/profiles/Profile.ts b/src/profiles/Profile.ts index 70ca90a..a7cbe11 100644 --- a/src/profiles/Profile.ts +++ b/src/profiles/Profile.ts @@ -1,11 +1,15 @@ import type { NamedNode, Quad, Term } from '@rdfjs/types'; import { DataFactory, Store } from 'n3'; import { createVocabulary } from 'rdf-vocabulary'; -import { ODRL, RDF, RDFS, SH } from '../util/Vocabulary'; +import { ODRL, RDF, RDFS, SH, XSD } from '../util/Vocabulary'; import { appendToList, findInList } from './ListUtil'; -const { quad } = DataFactory; +const { literal, quad, blankNode, namedNode } = DataFactory; -const SHAPE = createVocabulary('http://example.com/', +const SHAPE_NAMESPACE = 'http://example.com/'; +/** Namespace of the shapes generated from a profile, kept apart from the handcrafted ones. */ +const GENERATED_SHAPE_NAMESPACE = `${SHAPE_NAMESPACE}profile-shape/`; + +const SHAPE = createVocabulary(SHAPE_NAMESPACE, 'AllowedActionValueShape', 'AllowedConstraintValueShape', 'ConflictStrategyShape', @@ -13,20 +17,12 @@ const SHAPE = createVocabulary('http://example.com/', 'PolicyShape', 'RuleShape'); -// SHACL terms only needed here, kept out of the shared vocabulary. -const SH_EXTRA = createVocabulary('http://www.w3.org/ns/shacl#', - 'alternativePath', - 'targetSubjectsOf'); - /** * Describes one `sh:in` list in our SHACL file that holds the allowed ODRL terms of one kind, * e.g. the allowed actions, or the allowed left operands. - * - * A profile extends such a list by declaring instances of {@link AllowedValueList.type}, - * e.g. `ex:term a odrl:LeftOperand`. */ export interface AllowedValueList { - /** The ODRL class that profile terms are typed with, e.g. `odrl:LeftOperand`. */ + /** The ODRL class that profile terms relate to, e.g. `odrl:LeftOperand`. */ type: NamedNode; /** The named shape in our SHACL file that contains the list. */ shape: NamedNode; @@ -41,7 +37,7 @@ export interface AllowedValueList { */ relation?: 'instance' | 'subClassOf'; } - + /** * All `sh:in` lists of our SHACL file that a profile can extend. * This is the single place to register another one. @@ -76,70 +72,31 @@ export const ALLOWED_VALUE_LISTS: Record<'action' | 'leftOperand' | 'operator' | }, }; +// --------------------------------------------------------------------------- +// Reading the profile +// --------------------------------------------------------------------------- -/** - * Classes that no shape targets yet, paired with the shape that should validate their (profile) subclasses. - * A profile's `rdfs:subClassOf odrl:Rule` is validated like any other rule. - */ -const EXTRA_TARGETS: [NamedNode, NamedNode][] = [[ ODRL.terms.Rule, SHAPE.terms.RuleShape ]]; - - -/** - * Finds the named subjects in a profile that are typed with a class. - * Blank nodes are skipped, since they cannot be listed as allowed values. - * - * @param profile - The profile. - * @param type - The class the subjects must be typed with, e.g. `odrl:LeftOperand`. - * - * @returns The matching named subjects. - */ -function typedNamedNodes(profile: Quad[], type: NamedNode): NamedNode[] { - return new Store(profile).getSubjects(RDF.terms.type, type, null) - .filter((subject): boolean => subject.termType === 'NamedNode') as NamedNode[]; +/** Keeps the named nodes. Blank nodes are dropped, since our shapes cannot reference them. */ +function namedNodes(terms: Term[]): NamedNode[] { + return terms.filter((term): boolean => term.termType === 'NamedNode') as NamedNode[]; } - - -/** - * Adds each of `values` to the end of the `sh:in` list described by `list`, skipping values already in it. - * This changes `store` in place. - * - * @param store - The store containing the SHACL shapes. It is modified. - * @param list - Which `sh:in` list to extend. - * @param values - The terms to add to the list. - * - * @returns True if at least one value was added. - * - * @returns A new array with the shapes extended. It holds the same quads as `shape` if nothing needed adding. - * - * @throws Error - If `values` is not empty and the list cannot be found in `shape`. - */ -function addToShapeList(shape: Quad[], concept: AllowedValueList, values: NamedNode[]): Quad[] { - // Nothing to add: don't look the list up, so shapes without this list don't cause an error. - if (values.length === 0) { - return [ ...shape ]; - } - const list = findInList(shape, concept.shape, concept.path); - return values.reduce((quads, value): Quad[] => appendToList(quads, list, value), shape); +/** The named subjects in the profile typed with `type`, e.g. `ex:term a odrl:LeftOperand`. */ +function instancesOf(profile: Store, type: NamedNode): NamedNode[] { + return namedNodes(profile.getSubjects(RDF.terms.type, type, null)); } - /** * All named subjects below `root` in the profile via `predicate`, transitively, * e.g. all subclasses (`rdfs:subClassOf`) or all subproperties (`rdfs:subPropertyOf`). - * - * @param profile - The profile. - * @param root - The term to find the descendants of. - * @param predicate - The hierarchy predicate to follow. - * - * @returns The named descendants, direct and indirect, without `root` itself. + * `root` itself is not included. */ function descendantsOf(profile: Store, root: Term, predicate: NamedNode): NamedNode[] { const found = new Map(); const queue: Term[] = [ root ]; while (queue.length > 0) { - for (const sub of profile.getSubjects(predicate, queue.shift()!, null)) { - if (sub.termType === 'NamedNode' && !found.has(sub.value) && !sub.equals(root)) { + for (const sub of namedNodes(profile.getSubjects(predicate, queue.shift()!, null))) { + if (!found.has(sub.value) && !sub.equals(root)) { found.set(sub.value, sub); queue.push(sub); } @@ -148,92 +105,211 @@ function descendantsOf(profile: Store, root: Term, predicate: NamedNode): NamedN return [ ...found.values() ]; } -/** All named classes below `superClass` in the profile, transitively. - * - * @param profile - The profile. - * @param superClass - The class to find the subclasses of. - * - * @returns The named subclasses, direct and indirect. - */ +/** All named classes below `superClass` in the profile, direct and indirect. */ export function subclassesOf(profile: Store, superClass: Term): NamedNode[] { return descendantsOf(profile, superClass, RDFS.terms.subClassOf); } /** - * Makes `:LogicalConstraintShape` accept the profile's subproperties of `odrl:operand` + * The profile properties that relate a policy to `ruleClass`: + * `rdfs:range ruleClass` and `rdfs:domain` either `odrl:Policy` or a profile subclass of it. + */ +function policyPropertiesFor(profile: Store, ruleClass: NamedNode): NamedNode[] { + const policyClasses = [ ODRL.terms.Policy, ...subclassesOf(profile, ODRL.terms.Policy) ]; + return namedNodes(profile.getSubjects(RDFS.terms.range, ruleClass, null)) + .filter((property): boolean => + policyClasses.some((cls): boolean => profile.countQuads(property, RDFS.terms.domain, cls, null) > 0)); +} + +// --------------------------------------------------------------------------- +// Extending the shapes: one function per profile feature. +// Each takes the shapes and returns a new, extended array. None modifies its input. +// --------------------------------------------------------------------------- + +/** + * Adds the profile's actions, left operands, operators, conflict terms and policy types + * to the matching `sh:in` list (see {@link ALLOWED_VALUE_LISTS}). + * + * @throws Error - If the profile has terms for a list that `shape` does not contain. + */ +function addAllowedValues(shape: Quad[], profile: Store): Quad[] { + let result = shape; + for (const list of Object.values(ALLOWED_VALUE_LISTS)) { + const terms = list.relation === 'subClassOf' ? + subclassesOf(profile, list.type) : + instancesOf(profile, list.type); + // Only look the list up when there is something to add, so shapes without this list don't cause an error. + if (terms.length === 0) { + continue; + } + const head = findInList(result, list.shape, list.path); + for (const term of terms) { + result = appendToList(result, head, term); + } + } + return result; +} + +/** + * Makes every shape that targets a class also target that class's profile subclasses, + * e.g. `ex:MyOffer rdfs:subClassOf odrl:Offer` is validated by all shapes that target `odrl:Offer`. + */ +function addSubclassTargets(shape: Quad[], profile: Store): Quad[] { + const added: Quad[] = []; + for (const target of shape.filter((q): boolean => q.predicate.equals(SH.terms.targetClass))) { + for (const subclass of subclassesOf(profile, target.object)) { + added.push(quad(target.subject, SH.terms.targetClass, subclass)); + } + } + return [ ...shape, ...added ]; +} + +/** + * Makes `:LogicalConstraintShape` accept the profile's subproperties of `odrl:operand`, * like `odrl:and`, `odrl:or`, `odrl:xone` and `odrl:andSequence`. For each subproperty `p`: * * - `:LogicalConstraintShape sh:targetSubjectsOf p` is added; * - `p` is appended to the `sh:alternativePath` list of the shape. * - * @param shape - The SHACL shapes as quads. They are not modified. - * @param profile - The profile, containing the `rdfs:subPropertyOf` statements. - * - * @returns A new array with the shapes extended. It holds the same quads as `shape` if the profile adds nothing. - * * @throws Error - If the profile has operand subproperties and the shape has no `sh:alternativePath` list. */ -function addOperandSubproperties(shape: Quad[], profile: Quad[]): Quad[] { - const operands = descendantsOf(new Store(profile), ODRL.terms.operand, RDFS.terms.subPropertyOf); +function addOperandSubproperties(shape: Quad[], profile: Store): Quad[] { + const operands = descendantsOf(profile, ODRL.terms.operand, RDFS.terms.subPropertyOf); if (operands.length === 0) { - return [ ...shape ]; + return shape; } - const target = SHAPE.terms.LogicalConstraintShape; - const list = findInList(shape, target, undefined, SH_EXTRA.terms.alternativePath); - const withPaths = operands.reduce((quads, op): Quad[] => appendToList(quads, list, op), shape); - const targets = operands.map((op): Quad => quad(target, SH_EXTRA.terms.targetSubjectsOf, op)); - // A store is a set: this drops targets that are already there. - return new Store([ ...withPaths, ...targets ]).getQuads(null, null, null, null); + const logicalShape = SHAPE.terms.LogicalConstraintShape; + const head = findInList(shape, logicalShape, undefined, SH.terms.alternativePath); + let result = shape; + for (const operand of operands) { + result = appendToList(result, head, operand); + result = [ ...result, quad(logicalShape, SH.terms.targetSubjectsOf, operand) ]; + } + return result; } /** - * Makes every shape that targets a class also target that class's profile subclasses. - * This changes `store` in place. - * Covers subclasses of Policy (incl. Set, Offer, Agreement), Permission, Prohibition, Duty, Rule and Constraint. + * The shape generated for a profile rule class. + * It lives in its own namespace and contains the full IRI of the class, so it can never overlap + * with a handcrafted shape or with the shape of a same-named class from another profile. + */ +function ruleShapeFor(ruleClass: NamedNode): NamedNode { + return namedNode(`${GENERATED_SHAPE_NAMESPACE}${encodeURIComponent(ruleClass.value)}`); +} + + +/** + * A shape of its own that checks that a rule is referenced through at least one of `properties`: * - * @param store - The store containing the SHACL shapes. It is modified. - * @param profile - The profile, containing the `rdfs:subClassOf` statements. + * ```ttl + * a sh:NodeShape ; + * sh:targetClass p:MyRule ; + * sh:or ( + * [ sh:path [ sh:inversePath p:a ] ; sh:minCount 1 ] + * [ sh:path [ sh:inversePath p:b ] ; sh:minCount 1 ] + * ) ; + * sh:message "..." . + * ``` * - * @returns A new array with the extra `sh:targetClass` quads added. + * It is `sh:or` over single inverse paths because SHACL engines disagree on inverse and alternative paths combined: + * rdf-validate-shacl throws on the inverse of an alternative, and shacl-engine gives wrong results for both nestings. + * It is a separate shape so the message only belongs to this check. + * + * @param ruleClass - The rule class to check. + * @param properties - The properties that may reference the rule. At least one. */ -function addSubclassTargets(shape: Quad[], profile: Quad[]): Quad[] { - const profileStore = new Store(profile); - const targets: [Term, Term][] = [ - ...shape.filter((q): boolean => q.predicate.equals(SH.terms.targetClass)) - .map((q): [Term, Term] => [ q.object, q.subject ]), - ...EXTRA_TARGETS, +function referencedCheck(ruleClass: NamedNode, properties: NamedNode[]): Quad[] { + const checkShape = namedNode(`${ruleShapeFor(ruleClass).value}/referenced`); + const names = properties.map((property): string => property.value).join(' or '); + const listNodes = properties.map(() => blankNode()); + const quads = [ + quad(checkShape, RDF.terms.type, SH.terms.NodeShape), + quad(checkShape, SH.terms.targetClass, ruleClass), + quad(checkShape, SH.terms.or, listNodes[0]), + quad(checkShape, SH.terms.message, literal(`A ${ruleClass.value} must be referenced through ${names}.`)), ]; - const added = targets.flatMap(([ cls, targetShape ]): Quad[] => - subclassesOf(profileStore, cls).map((sub): Quad => quad(targetShape as NamedNode, SH.terms.targetClass, sub))); - // A store is a set: this drops targets that are already there or were found twice. - return new Store([ ...shape, ...added ]).getQuads(null, null, null, null); + properties.forEach((property, i): void => { + const option = blankNode(); + const path = blankNode(); + quads.push( + quad(listNodes[i], RDF.terms.first, option), + quad(listNodes[i], RDF.terms.rest, listNodes[i + 1] ?? RDF.terms.nil), + quad(option, SH.terms.path, path), + quad(option, SH.terms.minCount, literal('1', XSD.terms.integer)), + quad(path, SH.terms.inversePath, property), + ); + }); + return quads; } - - - +/** + * Supports the profile's own rule types. For each subclass `p:MyRule` of `odrl:Rule` (transitively): + * + * 1. `:RuleShape sh:targetClass p:MyRule`, so its instances are validated like any other rule; + * 2. a new shape ` a sh:NodeShape ; sh:targetClass p:MyRule ; sh:node :RuleShape` + * (see {@link ruleShapeFor} for its IRI); + * 3. for each property `p:myRule` relating a policy to it (see {@link policyPropertiesFor}), + * `:PolicyShape sh:targetSubjectsOf p:myRule ; sh:property [ sh:path p:myRule ; sh:node ]`; + * 4. if there is such a property, `` requires that at least one node references the rule + * through it (see {@link incomingReferenceCheck}). + */ +function addRuleTypes(shape: Quad[], profile: Store): Quad[] { + const added: Quad[] = []; + for (const ruleClass of subclassesOf(profile, ODRL.terms.Rule)) { + const ruleShape = ruleShapeFor(ruleClass); + const properties = policyPropertiesFor(profile, ruleClass); + + added.push( + quad(SHAPE.terms.RuleShape, SH.terms.targetClass, ruleClass), + quad(ruleShape, RDF.terms.type, SH.terms.NodeShape), + quad(ruleShape, SH.terms.targetClass, ruleClass), + quad(ruleShape, SH.terms.node, SHAPE.terms.RuleShape), + ); + + for (const property of properties) { + const propertyShape = blankNode(); + added.push( + quad(SHAPE.terms.PolicyShape, SH.terms.targetSubjectsOf, property), + quad(SHAPE.terms.PolicyShape, SH.terms.property, propertyShape), + quad(propertyShape, SH.terms.path, property), + quad(propertyShape, SH.terms.node, ruleShape), + ); + } + + if (properties.length > 0) { + added.push(...referencedCheck(ruleClass, properties)); + } + } + return [ ...shape, ...added ]; +} /** * Extends the shapes with everything an {@link https://www.w3.org/TR/odrl-model/#profile-mechanism ODRL profile} * defines: * - * - instances of `odrl:Action`, `odrl:LeftOperand`, `odrl:Operator` and `odrl:ConflictTerm` - * are added to the matching `sh:in` list in our SHACL file (see {@link ALLOWED_VALUE_LISTS}); - * - subclasses of the classes the shapes target (policies, rules, ...) are added as extra targets; - * - subproperties of `odrl:operand` are accepted as logical constraint operands (see {@link addOperandSubproperties}). + * - instances of `odrl:Action`, `odrl:LeftOperand`, `odrl:Operator` and `odrl:ConflictTerm`, and subclasses of + * `odrl:Policy`, are added to the matching `sh:in` list (see {@link addAllowedValues}); + * - subclasses of the classes the shapes target are added as extra targets (see {@link addSubclassTargets}); + * - subproperties of `odrl:operand` are accepted as logical constraint operands (see {@link addOperandSubproperties}); + * - subclasses of `odrl:Rule` get their own shape, linked from the policy (see {@link addRuleTypes}). * * @param shape - The SHACL shapes as quads. They are not modified. * @param profile - The profile as quads, e.g. the DPV ODRL mapping. * - * @returns A new array with the shapes extended. It holds the same quads as `shape` if the profile adds nothing. + * @returns A new array with the shapes extended, without duplicate quads. * * @throws Error * If the profile has terms for a list that `shape` does not contain. */ export function addProfileToShape(shape: Quad[], profile: Quad[]): Quad[] { - const withLists = Object.values(ALLOWED_VALUE_LISTS).reduce((quads, concept): Quad[] => - addToShapeList(quads, concept, concept.relation === 'subClassOf' ? - subclassesOf(new Store(profile), concept.type) : - typedNamedNodes(profile, concept.type)), shape); - return addOperandSubproperties(addSubclassTargets(withLists, profile), profile); + const profileStore = new Store(profile); + + let result = shape; + result = addAllowedValues(result, profileStore); + result = addSubclassTargets(result, profileStore); + result = addOperandSubproperties(result, profileStore); + result = addRuleTypes(result, profileStore); + + // A store is a set: this drops quads that were already there or were added twice. + return new Store(result).getQuads(null, null, null, null); } \ No newline at end of file diff --git a/src/shapes/Shapes.ts b/src/shapes/Shapes.ts index e8e2405..5cf8a23 100644 --- a/src/shapes/Shapes.ts +++ b/src/shapes/Shapes.ts @@ -55,6 +55,12 @@ export const SHAPES: string = `@prefix odrl: . a sh:NodeShape ; sh:targetClass odrl:Permission ; sh:property [ + sh:message "A Permission must be referenced by a Policy through odrl:permission." ; + sh:path [ + sh:inversePath odrl:permission + ] ; + sh:minCount 1 + ], [ sh:message "A Permission must have one odrl:target." ; sh:path odrl:target ; sh:maxCount 1 ; diff --git a/src/shapes/modules/02-odrl-rule.ttl b/src/shapes/modules/02-odrl-rule.ttl index 13c0414..f61c27a 100644 --- a/src/shapes/modules/02-odrl-rule.ttl +++ b/src/shapes/modules/02-odrl-rule.ttl @@ -165,6 +165,13 @@ sh:targetClass odrl:Permission ; sh:node :RuleShape ; + # At least one node points to this permission with odrl:permission + sh:property [ + sh:path [ sh:inversePath odrl:permission ] ; + sh:minCount 1 ; + sh:message "A Permission must be referenced through odrl:permission." ; + ] ; + sh:property [ sh:path odrl:target ; sh:minCount 1 ; @@ -184,6 +191,13 @@ sh:targetClass odrl:Prohibition ; sh:node :RuleShape ; + # At least one node points to this prohibition with odrl:prohibition + sh:property [ + sh:path [ sh:inversePath odrl:prohibition ] ; + sh:minCount 1 ; + sh:message "A Prohibition must be referenced through odrl:prohibition." ; + ] ; + sh:property [ sh:path odrl:target ; sh:minCount 1 ; @@ -205,20 +219,39 @@ sh:message "Each Prohibition remedy must conform to ODRL duty." ; ] . -# Duty = Rule + +# Duty = Rule :DutyShape a sh:NodeShape ; sh:targetClass odrl:Duty ; sh:node :RuleShape ; + # At least one node points to this duty with odrl:duty, odrl:consequence, odrl:remedy or odrl:obligation + sh:property [ + sh:path [ sh:inversePath [ sh:alternativePath ( odrl:duty odrl:consequence odrl:remedy odrl:obligation ) ] ] ; + sh:minCount 1 ; + sh:message "A Duty must be referenced through odrl:duty, odrl:consequence, odrl:remedy or odrl:obligation." ; + ] ; + sh:property [ sh:path odrl:consequence ; sh:node :DutyShape ; sh:message "Each Duty consequence must conform to ODRL duty." ; ] . -# Rules for offer +# At least one node points to this duty with odrl:duty, odrl:consequence, odrl:remedy or odrl:obligation +:DutyReferencedShape a sh:NodeShape ; + sh:targetClass odrl:Duty ; + sh:or ( + [ sh:path [ sh:inversePath odrl:duty ] ; sh:minCount 1 ] + [ sh:path [ sh:inversePath odrl:consequence ] ; sh:minCount 1 ] + [ sh:path [ sh:inversePath odrl:remedy ] ; sh:minCount 1 ] + [ sh:path [ sh:inversePath odrl:obligation ] ; sh:minCount 1 ] + ) ; + sh:message "A Duty must be referenced through odrl:duty, odrl:consequence, odrl:remedy or odrl:obligation." . + +# Rules for offer :OfferPermissionShape a sh:NodeShape ; sh:node :PermissionShape ; sh:node :OfferRequiredAssignerShape . diff --git a/src/shapes/odrl-shapes.ttl b/src/shapes/odrl-shapes.ttl index 71475fc..2539073 100644 --- a/src/shapes/odrl-shapes.ttl +++ b/src/shapes/odrl-shapes.ttl @@ -302,6 +302,13 @@ sh:targetClass odrl:Permission ; sh:node :RuleShape ; + # At least one policy points to this permission with odrl:permission + sh:property [ + sh:path [ sh:inversePath odrl:permission ] ; + sh:minCount 1 ; + sh:message "A Permission must be referenced by a Policy through odrl:permission." ; + ] ; + sh:property [ sh:path odrl:target ; sh:minCount 1 ; diff --git a/src/util/Vocabulary.ts b/src/util/Vocabulary.ts index 79dcb88..67006c4 100644 --- a/src/util/Vocabulary.ts +++ b/src/util/Vocabulary.ts @@ -10,10 +10,18 @@ export const DETECTION = createVocabulary('https://w3id.org/force/detection#', ) export const SH = createVocabulary('http://www.w3.org/ns/shacl#', + 'NodeShape', 'in', + 'inversePath', + 'message', + 'minCount', + 'node', + 'or', 'property', 'path', - 'targetClass'); + 'targetClass', + 'alternativePath', + 'targetSubjectsOf'); export const RDF = createVocabulary('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'Property', diff --git a/test/unit/Validator.test.ts b/test/unit/Validator.test.ts index 3353ec4..473bc53 100644 --- a/test/unit/Validator.test.ts +++ b/test/unit/Validator.test.ts @@ -109,8 +109,6 @@ describe('The ODRL Validator', (): void => { ) const result = await validator.validate(policyQuads); expect(result.valid).toBe(true); - // A profile present, but the profile not loaded in the validator must also throw a violation - expect((await new ODRLValidator().validate(policyQuads)).valid).toBe(false); }) it("fails when a profile action is part of a rule without a profile", async ()=> { @@ -129,8 +127,6 @@ describe('The ODRL Validator', (): void => { ) const result = await validator.validate(policyQuads); expect(result.valid).toBe(true); - // A profile present, but the profile not loaded in the validator must also throw a violation - expect((await new ODRLValidator().validate(policyQuads)).valid).toBe(false); }) it("fails when a profile left operand is part of a rule without a profile", async ()=> { @@ -150,8 +146,6 @@ describe('The ODRL Validator', (): void => { ) const result = await validator.validate(policyQuads); expect(result.valid).toBe(true); - // A profile present, but the profile not loaded in the validator must also throw a violation - expect((await new ODRLValidator().validate(policyQuads)).valid).toBe(false); }) it("fails when a profile operator is part of a rule without a profile", async ()=> { @@ -171,8 +165,6 @@ describe('The ODRL Validator', (): void => { ) const result = await validator.validate(policyQuads); expect(result.valid).toBe(true); - // A profile present, but the profile not loaded in the validator must also throw a violation - expect((await new ODRLValidator().validate(policyQuads)).valid).toBe(false); }) it("fails when a profile conflict term is part of a policy without a profile", async ()=> { @@ -201,8 +193,6 @@ describe('The ODRL Validator', (): void => { policyQuads.push(...profilePolicyQuads(true)) const result = await validator.validate(policyQuads); expect(result.valid).toBe(true); - // A profile present, but the profile not loaded in the validator must also throw a violation - expect((await new ODRLValidator().validate(policyQuads)).valid).toBe(false); }) it("fails when a profile policy subclass is used without a profile", async ()=> { @@ -240,15 +230,48 @@ describe('The ODRL Validator', (): void => { ) const result = await validator.validate(policyQuads); expect(result.valid).toBe(true); - // A profile present, but the profile not loaded in the validator must also throw a violation - expect((await new ODRLValidator().validate(policyQuads)).valid).toBe(false); + }) + + it("validates policies that use a profile rule subclass.", async ()=> { + const validator = new ODRLValidator({profiles:[profile]}); + policyQuads.push(quad(namedNode(policyIRI), ODRL.terms.permission, newRuleNode), + quad(newRuleNode, RDF.terms.type, profileRule), + quad(newRuleNode, ODRL.terms.action, ODRL.terms.read), + quad(newRuleNode, ODRL.terms.assignee, namedNode("https://example.org/Alice")), + quad(newRuleNode, ODRL.terms.target, namedNode("https://example.org/x"))) + const result = await validator.validate(policyQuads); + expect(result.valid).toBe(false); }) it("fails when a profile rule subclass is used without a profile", async ()=> { + // NOTE: I cannot enforce this because it would define the new rule class and its relation. + // The only thing I can think of that fixes this is by closing the policy, but than other relations in a Policy would fail + // Perhaps if we are deliberatily strict, this is possible? But then we need to ensure to add all allowed metadata properties in our shape: https://www.w3.org/TR/odrl-model/#metadata policyQuads.push(...profileRuleQuads()) expect((await new ODRLValidator().validate(policyQuads)).valid).toBe(false); }) + it("fails when a profile rule subclass is used without a profile and a wrong relation is used", async ()=> { + // NOTE: also will wrongly be categorized as Permission due to the normalization. + // The rule this has two types where one of them is not recognized as ODRL. + // This could potentially be resolved by mandating an odrl:Rule can only have one type. + policyQuads.push(quad(namedNode(policyIRI), ODRL.terms.permission, newRuleNode), + quad(newRuleNode, RDF.terms.type, profileRule), + quad(newRuleNode, ODRL.terms.action, ODRL.terms.read), + quad(newRuleNode, ODRL.terms.assignee, namedNode("https://example.org/Alice")), + quad(newRuleNode, ODRL.terms.target, namedNode("https://example.org/x"))) + expect((await new ODRLValidator().validate(policyQuads)).valid).toBe(false); + }) + + it("fails when a profile rule subclass is used without a profile and a wrong type is used", async ()=> { + policyQuads.push(quad(namedNode(policyIRI), profileRuleRelation, newRuleNode), + quad(newRuleNode, RDF.terms.type, ODRL.terms.Permission), + quad(newRuleNode, ODRL.terms.action, ODRL.terms.read), + quad(newRuleNode, ODRL.terms.assignee, namedNode("https://example.org/Alice")), + quad(newRuleNode, ODRL.terms.target, namedNode("https://example.org/x"))) + expect((await new ODRLValidator().validate(policyQuads)).valid).toBe(false); + }) + it("validates instances of a profile rule subclass like rules.", async ()=> { const validator = new ODRLValidator({profiles:[profile]}); // This rule is invalid: it has no action and no target. @@ -294,8 +317,6 @@ describe('The ODRL Validator', (): void => { ) const result = await validator.validate(policyQuads); expect(result.valid).toBe(true); - // A profile present, but the profile not loaded in the validator must also throw a violation - expect((await new ODRLValidator().validate(policyQuads)).valid).toBe(false); }) it("fails when a profile subproperty of odrl:operand is part of a rule without a profile", async ()=> { From 94e7dd9e3407d199d786db2eddd2a4da6603e239 Mon Sep 17 00:00:00 2001 From: Wout Slabbinck Date: Tue, 17 Nov 2026 09:23:20 +0100 Subject: [PATCH 2/4] fix: ensure profiles are only validated when they are declared in the policy --- src/Types.ts | 4 +- src/Validator.ts | 296 ++++++++--- src/util/Vocabulary.ts | 5 +- test/integration/MultipleProfiles.test.ts | 570 ++++++++++++++++++++++ 4 files changed, 792 insertions(+), 83 deletions(-) create mode 100644 test/integration/MultipleProfiles.test.ts diff --git a/src/Types.ts b/src/Types.ts index 09c0d36..e935adb 100644 --- a/src/Types.ts +++ b/src/Types.ts @@ -15,6 +15,8 @@ export interface ValidationResult { focusNode?: string; valueNode?: string; severity?: string; + /** The policies the result applies to. Absent for results about quads that no policy reaches. */ + policies?: string[]; } /** @@ -92,4 +94,4 @@ export interface IODRLTestCaseValidator { * Fails or reports mismatch according to test runner logic. */ validateTestCase(testCase: ODRLTestCase): Promise; -} +} \ No newline at end of file diff --git a/src/Validator.ts b/src/Validator.ts index 7f33d24..c4e73d8 100644 --- a/src/Validator.ts +++ b/src/Validator.ts @@ -1,17 +1,17 @@ -import { Quad } from "@rdfjs/types"; -import { Parser, Store, Writer } from 'n3'; -import { IODRLValidator, ODRLProfile, ValidatorResult } from "./Types"; +import type { Quad, Quad_Subject, Term } from "@rdfjs/types"; +import { Parser, Store } from 'n3'; +import { IODRLValidator, ODRLProfile, ValidationResult, ValidatorResult } from "./Types"; import { DataFactory } from 'rdf-data-factory'; import { Validator } from "shacl-engine" import { EyelingReasoner } from 'n3-utility' import { RDF } from "odrl-atomization"; import { RULES } from "./rules/Rules"; import { SHAPES } from "./shapes/Shapes"; -import { DETECTION, ODRL } from "./util/Vocabulary"; +import { DETECTION, ODRL, SH } from "./util/Vocabulary"; import { Normalizer } from "./Normalisation"; import { addProfileToShape, subclassesOf } from "./profiles/Profile"; -const POLICY_TYPES: string[] = [ +const POLICY_TYPES: readonly string[] = [ ODRL.Policy, ODRL.Agreement, ODRL.Assertion, @@ -22,44 +22,55 @@ const POLICY_TYPES: string[] = [ ODRL.Ticket ]; +/** One policy, with everything needed to validate it on its own. */ +interface PolicyUnit { + policy: Term; + /** All quads reachable from the policy. Other policies are not entered: only their types are included. */ + quads: Quad[]; + /** The supported profiles the policy declares, sorted. */ + profiles: string[]; + /** The profiles the policy declares that this validator does not support. */ + unsupportedProfiles: string[]; +} + +/** Identifies a term. A blank node and a named node with the same value stay apart. */ +function termKey(term: Term): string { + return `${term.termType}|${term.value}`; +} + export class ODRLValidator implements IODRLValidator { private normalizer: Normalizer; - private shaclValidator: Validator; - private readonly profiles: ODRLProfile[]; - private policyTypes: string[] private n3Rules: string; - protected shaclStore: Store; + /** The shapes for plain ODRL. The profiles a policy declares are added on top of these. */ + private readonly shape: Quad[]; + /** The profiles this validator supports, by the IRI a policy declares with `odrl:profile`. */ + private readonly profiles: Map; + /** The ODRL policy classes, plus the subclasses of `odrl:Policy` of every supported profile. Only used to find policies. */ + private readonly policyTypes: string[]; + /** One SHACL validator per set of profiles, created when the first policy with that set is validated. */ + private readonly shaclValidators: Map = new Map(); public constructor(config?: { shape?: Quad[], n3Rules?: string, profiles?: ODRLProfile[]; }) { - let shape: Quad[] = new Parser().parse(SHAPES); - let n3Rules: string = RULES; - let profiles: ODRLProfile[] = [] - if (config) { - shape = config.shape ?? shape; - n3Rules = config.n3Rules ?? n3Rules; - profiles = config.profiles ?? profiles; - } - this.policyTypes = POLICY_TYPES - for (const profile of profiles) { - // Constantly update the shape with the profiles - shape = addProfileToShape(shape, profile.quads) + this.shape = config?.shape ?? new Parser().parse(SHAPES); + this.n3Rules = config?.n3Rules ?? RULES; + this.profiles = new Map((config?.profiles ?? []).map((profile): [string, ODRLProfile] => [profile.uri, profile])); + + const policyTypes = new Set(POLICY_TYPES); + for (const profile of this.profiles.values()) { // Add the policy types defined by the profile (rdfs:subClassOf odrl:Policy) - this.policyTypes.push(...subclassesOf(new Store(profile.quads), ODRL.terms.Policy).map(type => type.value)); + for (const type of subclassesOf(new Store(profile.quads), ODRL.terms.Policy)) { + policyTypes.add(type.value); + } } - console.log("This ODRL Validator supports the following profiles:", profiles.map(profile => profile.uri)) - const shapeStore = new Store(shape); - - this.profiles = profiles; - this.shaclValidator = new Validator(shapeStore, { factory: new DataFactory() }); - this.n3Rules = n3Rules; + this.policyTypes = [...policyTypes]; + console.log("This ODRL Validator supports the following profiles:", [...this.profiles.keys()]) this.normalizer = new Normalizer(); - this.shaclStore = shapeStore; } public async validate(policies: Quad[]): Promise { @@ -70,8 +81,7 @@ export class ODRLValidator implements IODRLValidator { } // No valid RDF or No ODRL policies provided - if (!policies || policies.length === 0 || - !policies.some(q => q.predicate.value === RDF.type && this.policyTypes.includes(q.object.value))) { + if (!policies || policies.length === 0 || this.findPolicies(new Store(policies)).length === 0) { output.valid = false; output.validationResults.push({ message: "No valid policy provided" @@ -93,63 +103,54 @@ export class ODRLValidator implements IODRLValidator { const normalizedPolicyStore = new Store(normalizedPolicies) - // Warn about profiles that the policies use, but that the validator does not support - const supportedProfiles = this.profiles.map(profile => profile.uri); - for (const quad of normalizedPolicyStore.getQuads(null, ODRL.terms.profile, null, null)) { - if (!supportedProfiles.includes(quad.object.value)) { - output.validationResults.push({ - message: `Profile ${quad.object.value} is not supported: terms from this profile are not validated.`, - focusNode: quad.subject.value, - severity: "http://www.w3.org/ns/shacl#Warning" + // Split the input into one unit per policy, plus the quads that no policy reaches + const { units, leftover } = this.policyUnits(normalizedPolicyStore); + + const results: ValidationResult[] = []; + for (const unit of units) { + // Warn about profiles that the policy uses, but that the validator does not support + for (const profile of unit.unsupportedProfiles) { + results.push({ + message: `Profile ${profile} is not supported: terms from this profile are not recognised.`, + focusNode: unit.policy.value, + severity: SH.Warning, + policies: [unit.policy.value] }); } - } - - // SHACL Validation - const report = await this.shaclValidator.validate({ dataset: normalizedPolicyStore }); - if (report.conforms === false) { - - const getResults = (result: any): any[] => { - if (result.results && result.results.length > 0) { - return result.results.flatMap((r: any) => getResults(r)); - }; - - const messages = - result.message?.map((m: any) => m.value) - ?? result._message?.()?.map((m: any) => m.value) - ?? []; - - return messages.map((message: string) => ({ - message, - focusNode: result.focusNode?.value, - valueNode: result.value?.value, - severity: result.severity?.value - })); - }; - - output.validationResults.push(...report.results.flatMap((result: any) => - getResults(result) - )); - const duplicatedErrorResults = new Set(); + // SHACL Validation of the policy, with the shapes of plain ODRL and the profiles it declares + const report = await this.shaclValidatorFor(unit.profiles).validate({ dataset: new Store(unit.quads) }); + for (const result of report.results as any[]) { + results.push(...this.parseResult(result).map((parsed): ValidationResult => + ({ ...parsed, policies: [unit.policy.value] }))); + } + } - output.validationResults = output.validationResults.filter((result: any) => { - const key = JSON.stringify(result); - return duplicatedErrorResults.has(key) ? false : duplicatedErrorResults.add(key); - }); + // SHACL Validation of what is left, with the shapes of plain ODRL: nothing there declares a profile + if (leftover.length > 0) { + const report = await this.shaclValidatorFor([]).validate({ dataset: new Store(leftover) }); + results.push(...(report.results as any[]).flatMap((result): ValidationResult[] => this.parseResult(result))); + } - const hasViolation = output.validationResults.some((result: any) => - result.severity === "http://www.w3.org/ns/shacl#Violation" - ); + // The same result for several policies (e.g. about a rule or asset they share) is reported once + const uniqueResults = new Map(); + for (const result of results) { + const key = JSON.stringify([result.focusNode, result.valueNode, result.message, result.severity]); + const known = uniqueResults.get(key); + if (!known) { + uniqueResults.set(key, result); + } else if (result.policies) { + known.policies = [...new Set([...(known.policies ?? []), ...result.policies])]; + } + } + output.validationResults = [...uniqueResults.values()]; - output.valid = !hasViolation; + const hasViolation = output.validationResults.some((result): boolean => result.severity === SH.Violation); + output.valid = !hasViolation; - // If there are any violations, conflict detection does not make sense - if (hasViolation) { - return output; - } - } else { - output.valid = true; + // If there are any violations, conflict detection does not make sense + if (hasViolation) { + return output; } // Notation3 Conflict Detection @@ -172,4 +173,137 @@ export class ODRLValidator implements IODRLValidator { } return output; } + + /** + * Finds the policies by their structure, so policies with an unknown class (e.g. from a profile + * that is not supported) are found as well. A policy is a subject that + * + * - has a rule (`odrl:permission`, `odrl:prohibition` or `odrl:obligation`), + * - declares a profile (`odrl:profile`), or + * - is typed with an ODRL policy class or a policy class of a supported profile. + */ + private findPolicies(store: Store): Term[] { + const found = new Map(); + for (const subject of store.getSubjects(null, null, null)) { + if (this.isPolicy(store, subject)) { + found.set(termKey(subject), subject); + } + } + return [...found.values()]; + } + + /** Whether a node is a policy, see {@link findPolicies}. */ + private isPolicy(store: Store, node: Term): boolean { + if (node.termType === 'Literal') { + return false; + } + const subject = node as Quad_Subject; + return [ODRL.terms.permission, ODRL.terms.prohibition, ODRL.terms.obligation, ODRL.terms.profile] + .some((predicate): boolean => store.countQuads(subject, predicate, null, null) > 0) + || store.getObjects(subject, RDF.type, null).some((type): boolean => this.policyTypes.includes(type.value)); + } + + /** + * Splits the (normalised) input into one unit per policy. + * + * The quads of a policy are those of the policy itself and of every node reachable from it. + * Other policies are not part of a unit: see {@link reachableQuads}. + * + * @returns The units, and the leftover: the quads of every node that is part of no unit, + * and of everything reachable from those nodes. + */ + private policyUnits(store: Store): { units: PolicyUnit[], leftover: Quad[] } { + const policies = this.findPolicies(store); + const policyKeys = new Set(policies.map(termKey)); + const reached = new Set(policyKeys); + + const units = policies.map((policy): PolicyUnit => { + const { quads, nodes } = this.reachableQuads(store, [policy], policyKeys); + nodes.forEach((node): Set => reached.add(node)); + const declared = store.getObjects(policy as Quad_Subject, ODRL.terms.profile, null).map((profile): string => profile.value); + return { + policy, + quads, + profiles: [...new Set(declared.filter((profile): boolean => this.profiles.has(profile)))].sort(), + unsupportedProfiles: [...new Set(declared.filter((profile): boolean => !this.profiles.has(profile)))], + }; + }); + + const roots = store.getSubjects(null, null, null).filter((subject): boolean => !reached.has(termKey(subject))); + const leftover = roots.length > 0 ? this.reachableQuads(store, roots, policyKeys).quads : []; + return { units, leftover }; + } + + /** + * The quads of the start nodes and of every node reachable from them. + * + * Policies other than the start nodes are left out completely: quads that point to them are dropped. + * For `ex:policy odrl:inheritFrom ex:policy2`, the unit of `ex:policy` thus contains nothing of `ex:policy2`. + * Including the triple `ex:policy odrl:inheritFrom ex:policy2` as well. The Policy Shape expects something of type policy, + * so an inheritfrom would then always result into a Violation if kept + * + * @returns The quads, and the keys (see {@link termKey}) of the nodes they are about. + */ + private reachableQuads(store: Store, start: Term[], policyKeys: Set): { quads: Quad[], nodes: Set } { + const quads: Quad[] = []; + const nodes = new Set(); + const startKeys = new Set(start.map(termKey)); + const queue: Term[] = [...start]; + while (queue.length > 0) { + const node = queue.pop()!; + if (nodes.has(termKey(node))) { + continue; + } + nodes.add(termKey(node)); + for (const quad of store.getQuads(node, null, null, null)) { + const object = termKey(quad.object); + if (policyKeys.has(object) && !startKeys.has(object)) { + continue; + } + quads.push(quad); + if (quad.object.termType !== 'Literal') { + queue.push(quad.object); + } + } + } + return { quads, nodes }; + } + + /** + * The SHACL validator for exactly these profiles: the shapes of plain ODRL when there are none. + * Extending the shapes is slow, so every set of profiles is only built once. + * + * @param profiles - The IRIs of supported profiles, sorted. + */ + private shaclValidatorFor(profiles: string[]): Validator { + const key = profiles.join(' '); + let validator = this.shaclValidators.get(key); + if (!validator) { + // Constantly update the shape with the profiles + const shape = profiles.reduce((quads, uri): Quad[] => + addProfileToShape(quads, this.profiles.get(uri)!.quads), this.shape); + validator = new Validator(new Store(shape), { factory: new DataFactory() }); + this.shaclValidators.set(key, validator); + } + return validator; + } + + /** Flattens a SHACL result with its nested results into one result per message. */ + private parseResult(result: any): ValidationResult[] { + if (result.results && result.results.length > 0) { + return result.results.flatMap((r: any) => this.parseResult(r)); + }; + + const messages = + result.message?.map((m: any) => m.value) + ?? result._message?.()?.map((m: any) => m.value) + ?? []; + + return messages.map((message: string) => ({ + message, + focusNode: result.focusNode?.value, + valueNode: result.value?.value, + severity: result.severity?.value + })); + } } \ No newline at end of file diff --git a/src/util/Vocabulary.ts b/src/util/Vocabulary.ts index 67006c4..0419806 100644 --- a/src/util/Vocabulary.ts +++ b/src/util/Vocabulary.ts @@ -21,7 +21,10 @@ export const SH = createVocabulary('http://www.w3.org/ns/shacl#', 'path', 'targetClass', 'alternativePath', - 'targetSubjectsOf'); + 'targetSubjectsOf', + 'Violation', + 'Warning' +); export const RDF = createVocabulary('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'Property', diff --git a/test/integration/MultipleProfiles.test.ts b/test/integration/MultipleProfiles.test.ts new file mode 100644 index 0000000..9f824d7 --- /dev/null +++ b/test/integration/MultipleProfiles.test.ts @@ -0,0 +1,570 @@ +import type { NamedNode, Quad } from '@rdfjs/types'; +import { DataFactory, Parser } from 'n3'; +import { ODRLProfile, ValidationResult, ValidatorResult } from '../../src/Types'; +import { ODRL, RDF, RDFS, XSD } from '../../src/util/Vocabulary'; +import { ODRLValidator } from '../../src/Validator'; +import { DPV_ODRL_PROFILE, TOSL_PROFILE } from '../../src/profiles'; +const { quad, namedNode, literal } = DataFactory; + +const VIOLATION = 'http://www.w3.org/ns/shacl#Violation'; +const WARNING = 'http://www.w3.org/ns/shacl#Warning'; + +describe('The ODRL Validator with multiple profiles', (): void => { + const EX = 'https://example.org/'; + const alice = namedNode(EX + 'Alice'); + const asset = namedNode(EX + 'x'); + + // Two policies. Each test decides which profile they declare and which terms they use. + let policyA: NamedNode; + let policyB: NamedNode; + let ruleA: NamedNode; + let ruleB: NamedNode; + + // Two profiles, each defining one term of every kind + let profileA: ODRLProfile; + let profileB: ODRLProfile; + let actionA: NamedNode; + let actionB: NamedNode; + let leftOperandA: NamedNode; + let leftOperandB: NamedNode; + let operatorA: NamedNode; + let operatorB: NamedNode; + let conflictTermA: NamedNode; + let conflictTermB: NamedNode; + let policyTypeA: NamedNode; + let policyTypeB: NamedNode; + + let validator: ODRLValidator; + + // A profile that defines one term of every kind in its own namespace + const profileQuads = (uri: string): Quad[] => [ + quad(namedNode(uri + 'Act'), RDF.terms.type, ODRL.terms.Action), + quad(namedNode(uri + 'Left'), RDF.terms.type, ODRL.terms.LeftOperand), + quad(namedNode(uri + 'Op'), RDF.terms.type, ODRL.terms.Operator), + quad(namedNode(uri + 'Conf'), RDF.terms.type, ODRL.terms.ConflictTerm), + quad(namedNode(uri + 'MyPolicy'), RDFS.terms.subClassOf, ODRL.terms.Policy), + ]; + + // A policy with its type and, when given, the profiles it declares + const policyQuads = (policy: NamedNode, profiles: ODRLProfile[] = [], type: NamedNode = ODRL.terms.Set): Quad[] => [ + quad(policy, RDF.terms.type, type), + ...profiles.map((profile): Quad => quad(policy, ODRL.terms.profile, namedNode(profile.uri))), + ]; + + // A permission of a policy with an action, an assignee and a target. + // The assignee and the target are typed, so that valid policies have no warnings either. + const permissionQuads = (rule: NamedNode, action: NamedNode, policy: NamedNode): Quad[] => [ + quad(policy, ODRL.terms.permission, rule), + quad(rule, RDF.terms.type, ODRL.terms.Permission), + quad(rule, ODRL.terms.action, action), + quad(rule, ODRL.terms.assignee, alice), + quad(rule, ODRL.terms.target, asset), + quad(alice, RDF.terms.type, ODRL.terms.Party), + quad(asset, RDF.terms.type, ODRL.terms.Asset), + ]; + + // A constraint on a rule + const constraintQuads = (rule: NamedNode, leftOperand: NamedNode, operator: NamedNode): Quad[] => { + const constraint = namedNode(rule.value + '-constraint'); + return [ + quad(rule, ODRL.terms.constraint, constraint), + quad(constraint, RDF.terms.type, ODRL.terms.Constraint), + quad(constraint, ODRL.terms.leftOperand, leftOperand), + quad(constraint, ODRL.terms.operator, operator), + quad(constraint, ODRL.terms.rightOperand, literal('5', XSD.terms.integer)), + ]; + }; + + const violations = (result: ValidatorResult): ValidationResult[] => + result.validationResults.filter((r): boolean => r.severity === VIOLATION); + const violationsOf = (result: ValidatorResult, policy: NamedNode): ValidationResult[] => + violations(result).filter((r): boolean => r.policies?.includes(policy.value) ?? false); + + beforeEach((): void => { + policyA = namedNode(EX + 'PolicyA'); + policyB = namedNode(EX + 'PolicyB'); + ruleA = namedNode(EX + 'ruleA'); + ruleB = namedNode(EX + 'ruleB'); + + const uriA = EX + 'profileA#'; + const uriB = EX + 'profileB#'; + profileA = { uri: uriA, quads: profileQuads(uriA) }; + profileB = { uri: uriB, quads: profileQuads(uriB) }; + actionA = namedNode(uriA + 'Act'); + actionB = namedNode(uriB + 'Act'); + leftOperandA = namedNode(uriA + 'Left'); + leftOperandB = namedNode(uriB + 'Left'); + operatorA = namedNode(uriA + 'Op'); + operatorB = namedNode(uriB + 'Op'); + conflictTermA = namedNode(uriA + 'Conf'); + conflictTermB = namedNode(uriB + 'Conf'); + policyTypeA = namedNode(uriA + 'MyPolicy'); + policyTypeB = namedNode(uriB + 'MyPolicy'); + + validator = new ODRLValidator({ profiles: [ profileA, profileB ] }); + }); + + describe('for a single policy', (): void => { + it('validates a policy that only uses terms of the profile it declares.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + ...constraintQuads(ruleA, leftOperandA, operatorA), + quad(policyA, ODRL.terms.conflict, conflictTermA), + ]); + expect(result.validationResults).toEqual([]); + expect(result.valid).toBe(true); + }); + + it('validates a plain ODRL policy.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA), + ...permissionQuads(ruleA, ODRL.terms.read, policyA), + ]); + expect(result.valid).toBe(true); + }); + + it('fails when a policy without a profile uses an action of a supported profile.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA), + ...permissionQuads(ruleA, actionA, policyA), + ]); + expect(result.valid).toBe(false); + expect(violationsOf(result, policyA).length).toBeGreaterThan(0); + }); + + it('fails when a policy uses an action of a supported profile it does not declare.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionB, policyA), + ]); + expect(result.valid).toBe(false); + expect(violationsOf(result, policyA).some((r): boolean => r.valueNode === actionB.value)).toBe(true); + }); + + it('fails when a policy uses a left operand of a supported profile it does not declare.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + ...constraintQuads(ruleA, leftOperandB, ODRL.terms.eq), + ]); + expect(result.valid).toBe(false); + }); + + it('fails when a policy uses an operator of a supported profile it does not declare.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + ...constraintQuads(ruleA, leftOperandA, operatorB), + ]); + expect(result.valid).toBe(false); + }); + + it('fails when a policy uses a conflict term of a supported profile it does not declare.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + quad(policyA, ODRL.terms.conflict, conflictTermB), + ]); + expect(result.valid).toBe(false); + }); + + it('validates a policy that is typed with the policy class of the profile it declares.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ], policyTypeA), + ...permissionQuads(ruleA, actionA, policyA), + ]); + expect(result.valid).toBe(true); + }); + + it('fails when a policy is typed with the policy class of a supported profile it does not declare.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ], policyTypeB), + ...permissionQuads(ruleA, actionA, policyA), + ]); + expect(result.valid).toBe(false); + expect(violationsOf(result, policyA).length).toBeGreaterThan(0); + }); + + it('validates a policy that declares both profiles and uses terms of both.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA, profileB ]), + ...permissionQuads(ruleA, actionA, policyA), + ...constraintQuads(ruleA, leftOperandB, operatorA), + ...permissionQuads(ruleB, actionB, policyA), + quad(policyA, ODRL.terms.conflict, conflictTermB), + ]); + expect(result.validationResults).toEqual([]); + expect(result.valid).toBe(true); + }); + }); + + describe('for multiple policies in one input', (): void => { + it('validates policies that each use the terms of their own profile.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + ...constraintQuads(ruleA, leftOperandA, operatorA), + ...policyQuads(policyB, [ profileB ]), + ...permissionQuads(ruleB, actionB, policyB), + ...constraintQuads(ruleB, leftOperandB, operatorB), + ]); + expect(result.validationResults).toEqual([]); + expect(result.valid).toBe(true); + }); + + it('validates a profile policy next to a plain ODRL policy.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + ...policyQuads(policyB), + ...permissionQuads(ruleB, ODRL.terms.read, policyB), + ]); + expect(result.valid).toBe(true); + }); + + it('only reports the policy that uses a term of the profile of the other policy.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + ...policyQuads(policyB, [ profileB ]), + // The action of profile A in a policy that declares profile B + ...permissionQuads(ruleB, actionA, policyB), + ]); + expect(result.valid).toBe(false); + expect(violationsOf(result, policyA)).toEqual([]); + expect(violationsOf(result, policyB).length).toBeGreaterThan(0); + expect(violations(result).every((r): boolean => r.policies?.length === 1 && r.policies[0] === policyB.value)).toBe(true); + }); + + it('only reports the plain ODRL policy that uses a term of the profile of the other policy.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + ...constraintQuads(ruleA, leftOperandA, operatorA), + ...policyQuads(policyB), + ...permissionQuads(ruleB, ODRL.terms.read, policyB), + ...constraintQuads(ruleB, leftOperandA, ODRL.terms.eq), + ]); + expect(result.valid).toBe(false); + expect(violationsOf(result, policyA)).toEqual([]); + expect(violationsOf(result, policyB).length).toBeGreaterThan(0); + }); + + it('reports both policies when they use the terms of each other.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionB, policyA), + ...policyQuads(policyB, [ profileB ]), + ...permissionQuads(ruleB, actionA, policyB), + ]); + expect(result.valid).toBe(false); + expect(violationsOf(result, policyA).some((r): boolean => r.valueNode === actionB.value)).toBe(true); + expect(violationsOf(result, policyB).some((r): boolean => r.valueNode === actionA.value)).toBe(true); + }); + + it('validates a rule shared by two policies under the profile of each policy.', async (): Promise => { + const shared = namedNode(EX + 'sharedRule'); + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...policyQuads(policyB), + // One rule with the action of profile A, part of both policies + ...permissionQuads(shared, actionA, policyA), + quad(policyB, ODRL.terms.permission, shared), + ]); + expect(result.valid).toBe(false); + expect(violationsOf(result, policyA)).toEqual([]); + expect(violationsOf(result, policyB).length).toBeGreaterThan(0); + }); + + it('reports a violation of a rule shared by two policies once, for both policies.', async (): Promise => { + const shared = namedNode(EX + 'sharedRule'); + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...policyQuads(policyB, [ profileB ]), + // A rule without an action: invalid whatever the profile + quad(policyA, ODRL.terms.permission, shared), + quad(policyB, ODRL.terms.permission, shared), + quad(shared, ODRL.terms.target, asset), + quad(asset, RDF.terms.type, ODRL.terms.Asset), + ]); + expect(result.valid).toBe(false); + const missingAction = violations(result).filter((r): boolean => r.message === 'A Rule must have one action.'); + expect(missingAction.length).toBeGreaterThan(0); + for (const violation of violations(result)) { + expect(violation.policies).toEqual([ policyA.value, policyB.value ]); + } + // Every result is reported once, not once per policy + const keys = result.validationResults.map((r): string => JSON.stringify([ r.focusNode, r.valueNode, r.message, r.severity ])); + expect(new Set(keys).size).toBe(keys.length); + }); + + it('reports a warning about a party shared by two policies once, for both policies.', async (): Promise => { + const bob = namedNode(EX + 'Bob'); + // A permission of which the assigner is not typed as a party + const withAssigner = (rule: NamedNode, action: NamedNode, policy: NamedNode): Quad[] => [ + ...permissionQuads(rule, action, policy), + quad(rule, ODRL.terms.assigner, bob), + ]; + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...withAssigner(ruleA, actionA, policyA), + ...policyQuads(policyB, [ profileB ]), + ...withAssigner(ruleB, actionB, policyB), + ]); + expect(result.valid).toBe(true); + // One warning per rule: each rule belongs to one policy + const warnings = result.validationResults.filter((r): boolean => r.valueNode === bob.value); + expect(warnings.map((r): unknown => [ r.focusNode, r.policies ])).toEqual([ + [ ruleA.value, [ policyA.value ] ], + [ ruleB.value, [ policyB.value ] ], + ]); + }); + + it('does not validate a policy under the profile of a policy that inherits from it.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + quad(policyA, ODRL.terms.inheritFrom, policyB), + // The parent uses its own profile, which the child does not declare + ...policyQuads(policyB, [ profileB ]), + ...permissionQuads(ruleB, actionB, policyB), + ]); + expect(result.validationResults).toEqual([]); + expect(result.valid).toBe(true); + }); + + it('fails when a policy inherits from something that is not a policy.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + quad(policyA, ODRL.terms.inheritFrom, asset), + ]); + expect(result.valid).toBe(false); + expect(violationsOf(result, policyA).some((r): boolean => r.valueNode === asset.value)).toBe(true); + }); + + it('does not validate a parent policy with the profile of the policy that inherits from it.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + quad(policyA, ODRL.terms.inheritFrom, policyB), + // The parent declares no profile, but uses the action of the profile of the child + ...policyQuads(policyB), + ...permissionQuads(ruleB, actionA, policyB), + ]); + expect(result.valid).toBe(false); + expect(violationsOf(result, policyA)).toEqual([]); + expect(violationsOf(result, policyB).length).toBeGreaterThan(0); + }); + + it('still reports plain ODRL violations for the policy they belong to.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + ...policyQuads(policyB, [ profileB ]), + // A rule without an action + quad(policyB, ODRL.terms.permission, ruleB), + quad(ruleB, ODRL.terms.target, asset), + ]); + expect(result.valid).toBe(false); + expect(violationsOf(result, policyA)).toEqual([]); + expect(violationsOf(result, policyB).length).toBeGreaterThan(0); + }); + }); + + describe('for quads that no policy reaches', (): void => { + // A permission that is not part of a policy + const looseRuleQuads = (action: NamedNode): Quad[] => + permissionQuads(ruleB, action, policyB).filter((q): boolean => !q.subject.equals(policyB)); + + it('validates them with the shapes of plain ODRL.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + ...looseRuleQuads(ODRL.terms.read), + ]); + expect(result.validationResults).toEqual([]); + expect(result.valid).toBe(true); + }); + + it('fails when they use a term of a supported profile.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + ...looseRuleQuads(actionA), + ]); + expect(result.valid).toBe(false); + expect(violationsOf(result, policyA)).toEqual([]); + expect(violations(result).every((r): boolean => r.policies === undefined)).toBe(true); + }); + + it('validates a node of a policy as plain ODRL when a quad outside of the policy points to it.', async (): Promise => { + // Known limitation: the rule is valid in its policy, but is also pulled in by the loose quad + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + quad(namedNode(EX + 'catalogEntry'), namedNode('http://purl.org/dc/terms/relation'), ruleA), + ]); + expect(result.valid).toBe(false); + expect(violationsOf(result, policyA)).toEqual([]); + }); + + it('fails when a loose rule uses a constraint of a policy that has a term of the profile of that policy.', async (): Promise => { + const constraint = namedNode(ruleA.value + '-constraint'); + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + ...constraintQuads(ruleA, leftOperandA, operatorA), + // The loose rule shares the constraint: valid in the policy, not for a rule without a profile + ...looseRuleQuads(ODRL.terms.read), + quad(ruleB, ODRL.terms.constraint, constraint), + ]); + expect(result.valid).toBe(false); + expect(violationsOf(result, policyA)).toEqual([]); + expect(violations(result).every((r): boolean => r.policies === undefined)).toBe(true); + expect(violations(result).some((r): boolean => r.valueNode === leftOperandA.value)).toBe(true); + }); + + it('fails when they are invalid plain ODRL.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + // A permission without an action or a target + quad(ruleB, RDF.terms.type, ODRL.terms.Permission), + ]); + expect(result.valid).toBe(false); + expect(violations(result).every((r): boolean => r.focusNode === ruleB.value && r.policies === undefined)).toBe(true); + }); + }); + + describe('for profiles the validator does not support', (): void => { + const unknown: ODRLProfile = { uri: EX + 'unknownProfile#', quads: [] }; + const unknownAction = namedNode(unknown.uri + 'Act'); + + it('warns, and stays valid when the policy only uses ODRL terms.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ unknown ]), + ...permissionQuads(ruleA, ODRL.terms.read, policyA), + ]); + expect(result.valid).toBe(true); + expect(result.validationResults).toEqual([ expect.objectContaining({ + severity: WARNING, + policies: [ policyA.value ], + message: expect.stringContaining(unknown.uri), + }) ]); + }); + + it('fails when the policy uses a term of that profile.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ unknown ]), + ...permissionQuads(ruleA, unknownAction, policyA), + ]); + expect(result.valid).toBe(false); + expect(result.validationResults.some((r): boolean => r.severity === WARNING)).toBe(true); + }); + + it('still accepts the terms of the supported profile the policy also declares.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ profileA, unknown ]), + ...permissionQuads(ruleA, actionA, policyA), + ]); + expect(result.valid).toBe(true); + }); + + it('does not accept the terms of a supported profile the policy does not declare.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ unknown ]), + ...permissionQuads(ruleA, actionA, policyA), + ]); + expect(result.valid).toBe(false); + }); + + it('finds a policy with an unknown policy class and reports the class.', async (): Promise => { + const result = await validator.validate([ + ...policyQuads(policyA, [ unknown ], namedNode(unknown.uri + 'MyPolicy')), + ...permissionQuads(ruleA, ODRL.terms.read, policyA), + ]); + expect(result.valid).toBe(false); + expect(result.validationResults.some((r): boolean => r.message === 'No valid policy provided')).toBe(false); + expect(violationsOf(result, policyA).length).toBeGreaterThan(0); + }); + }); + + describe('for validator instances', (): void => { + it('gives the same results when the same validator is used several times.', async (): Promise => { + const valid = [ + ...policyQuads(policyA, [ profileA ]), + ...permissionQuads(ruleA, actionA, policyA), + ]; + const invalid = [ + ...policyQuads(policyB, [ profileB ]), + ...permissionQuads(ruleB, actionA, policyB), + ]; + expect((await validator.validate(valid)).valid).toBe(true); + expect((await validator.validate(invalid)).valid).toBe(false); + expect((await validator.validate(valid)).valid).toBe(true); + expect((await validator.validate(invalid)).valid).toBe(false); + }); + + it('does not share profiles with other validators.', async (): Promise => { + const policy = [ + ...policyQuads(policyA, [ profileA ], policyTypeA), + ...permissionQuads(ruleA, actionA, policyA), + ]; + expect((await validator.validate(policy)).valid).toBe(true); + // Created after a validator with profiles: knows neither the action nor the policy class + expect((await new ODRLValidator().validate(policy)).valid).toBe(false); + expect((await new ODRLValidator({ profiles: [ profileB ] }).validate(policy)).valid).toBe(false); + }); + }); + + describe('for the bundled TOSL and DPV profiles', (): void => { + const TOSL = 'https://w3id.org/tosl/'; + const DPV_ODRL = 'https://w3id.org/dpv/mappings/odrl#'; + const tosl: ODRLProfile = { uri: TOSL, quads: new Parser().parse(TOSL_PROFILE) }; + const dpv: ODRLProfile = { uri: DPV_ODRL, quads: new Parser().parse(DPV_ODRL_PROFILE) }; + const toslRemove = namedNode(TOSL + 'remove'); + const dpvUse = namedNode(DPV_ODRL + 'Use'); + const bundled = new ODRLValidator({ profiles: [ tosl, dpv ] }); + + it('validates a TOSL policy and a DPV policy in one input.', async (): Promise => { + const result = await bundled.validate([ + ...policyQuads(policyA, [ tosl ]), + ...permissionQuads(ruleA, toslRemove, policyA), + ...policyQuads(policyB, [ dpv ]), + ...permissionQuads(ruleB, dpvUse, policyB), + ]); + expect(result.valid).toBe(true); + }); + + it('fails when a TOSL policy uses a DPV action.', async (): Promise => { + const result = await bundled.validate([ + ...policyQuads(policyA, [ tosl ]), + ...permissionQuads(ruleA, dpvUse, policyA), + ...policyQuads(policyB, [ dpv ]), + ...permissionQuads(ruleB, dpvUse, policyB), + ]); + expect(result.valid).toBe(false); + expect(violationsOf(result, policyA).length).toBeGreaterThan(0); + expect(violationsOf(result, policyB)).toEqual([]); + }); + + it('fails when a plain ODRL policy uses a TOSL action.', async (): Promise => { + const result = await bundled.validate([ + ...policyQuads(policyA), + ...permissionQuads(ruleA, toslRemove, policyA), + ]); + expect(result.valid).toBe(false); + }); + + it('validates a policy that declares both profiles and uses actions of both.', async (): Promise => { + const result = await bundled.validate([ + ...policyQuads(policyA, [ tosl, dpv ]), + ...permissionQuads(ruleA, toslRemove, policyA), + ...permissionQuads(ruleB, dpvUse, policyA), + ]); + expect(result.valid).toBe(true); + }); + }); +}); \ No newline at end of file From 1d493710a5f944ed0b102c6bdae35901eeb9c30b Mon Sep 17 00:00:00 2001 From: Wout Slabbinck Date: Tue, 17 Nov 2026 09:54:16 +0100 Subject: [PATCH 3/4] feat: extract instances and declarations of asset and type to profiles to avoid warnings --- src/Validator.ts | 42 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/src/Validator.ts b/src/Validator.ts index c4e73d8..1070449 100644 --- a/src/Validator.ts +++ b/src/Validator.ts @@ -7,7 +7,7 @@ import { EyelingReasoner } from 'n3-utility' import { RDF } from "odrl-atomization"; import { RULES } from "./rules/Rules"; import { SHAPES } from "./shapes/Shapes"; -import { DETECTION, ODRL, SH } from "./util/Vocabulary"; +import { DETECTION, ODRL, RDFS, SH } from "./util/Vocabulary"; import { Normalizer } from "./Normalisation"; import { addProfileToShape, subclassesOf } from "./profiles/Profile"; @@ -25,7 +25,7 @@ const POLICY_TYPES: readonly string[] = [ /** One policy, with everything needed to validate it on its own. */ interface PolicyUnit { policy: Term; - /** All quads reachable from the policy. Other policies are not entered: only their types are included. */ + /** All quads reachable from the policy. Quads that point to other policies are left out. */ quads: Quad[]; /** The supported profiles the policy declares, sorted. */ profiles: string[]; @@ -119,7 +119,10 @@ export class ODRLValidator implements IODRLValidator { } // SHACL Validation of the policy, with the shapes of plain ODRL and the profiles it declares - const report = await this.shaclValidatorFor(unit.profiles).validate({ dataset: new Store(unit.quads) }); + const dataset = new Store(unit.quads) + // Add the Assets and Parties from the profiles such that they not flag SHACL Warnings + dataset.addQuads(this.profileFeatures(unit.profiles)) + const report = await this.shaclValidatorFor(unit.profiles).validate({ dataset }); for (const result of report.results as any[]) { results.push(...this.parseResult(result).map((parsed): ValidationResult => ({ ...parsed, policies: [unit.policy.value] }))); @@ -306,4 +309,37 @@ export class ODRLValidator implements IODRLValidator { severity: result.severity?.value })); } + + // extracts all instances and declarations of Party from a profile. + // Declarations are not resolved transitively + private profileParties(profile: string): Quad[] { + const profileStore = new Store(this.profiles.get(profile)?.quads) + const quads: Quad[] = [] + quads.push(...profileStore.getQuads(null, RDF.terms.type, ODRL.terms.Party, null)); + quads.push(...profileStore.getQuads(null, RDFS.terms.subClassOf, ODRL.terms.Party, null)); + return quads + + } + + // extracts all instances and declarations of Asset from a profile. + // Declarations are not resolved transitively + private profileAssets(profile:string): Quad[] { + const profileStore = new Store(this.profiles.get(profile)?.quads) + const quads: Quad[] = [] + quads.push(...profileStore.getQuads(null, RDF.terms.type, ODRL.terms.Asset, null)); + quads.push(...profileStore.getQuads(null, RDFS.terms.subClassOf, ODRL.terms.Asset, null)); + return quads + } + /** + * extracts all the parties and assets for the profiles. + * NOTE: currently not cached + */ + private profileFeatures(profiles: string[]): Quad[] { + const quads: Quad[] = [] + for (const profile of profiles) { + quads.push(...this.profileParties(profile)) + quads.push(...this.profileAssets(profile)) + } + return quads + } } \ No newline at end of file From 238e8ba9c9ec1af5486630742cad1e8e90395d6f Mon Sep 17 00:00:00 2001 From: Wout Slabbinck Date: Tue, 17 Nov 2026 10:29:56 +0100 Subject: [PATCH 4/4] docs: elaborate why a test still fails --- src/Validator.ts | 2 -- test/unit/Validator.test.ts | 11 +++++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/Validator.ts b/src/Validator.ts index 1070449..5163f74 100644 --- a/src/Validator.ts +++ b/src/Validator.ts @@ -68,8 +68,6 @@ export class ODRLValidator implements IODRLValidator { } } this.policyTypes = [...policyTypes]; - console.log("This ODRL Validator supports the following profiles:", [...this.profiles.keys()]) - this.normalizer = new Normalizer(); } diff --git a/test/unit/Validator.test.ts b/test/unit/Validator.test.ts index 473bc53..bfffb15 100644 --- a/test/unit/Validator.test.ts +++ b/test/unit/Validator.test.ts @@ -232,7 +232,10 @@ describe('The ODRL Validator', (): void => { expect(result.valid).toBe(true); }) - it("validates policies that use a profile rule subclass.", async ()=> { + it("validates policies that use a profile rule subclass and where the wrong relation is used.", async ()=> { + // NOTE: will wrongly be categorized as Permission due to the normalization. + // The rule has two types where one of them is not recognized as ODRL. + // This could potentially be resolved by mandating an odrl:Rule can only have one type. const validator = new ODRLValidator({profiles:[profile]}); policyQuads.push(quad(namedNode(policyIRI), ODRL.terms.permission, newRuleNode), quad(newRuleNode, RDF.terms.type, profileRule), @@ -252,8 +255,8 @@ describe('The ODRL Validator', (): void => { }) it("fails when a profile rule subclass is used without a profile and a wrong relation is used", async ()=> { - // NOTE: also will wrongly be categorized as Permission due to the normalization. - // The rule this has two types where one of them is not recognized as ODRL. + // NOTE: will wrongly be categorized as Permission due to the normalization. + // The rule has two types where one of them is not recognized as ODRL. // This could potentially be resolved by mandating an odrl:Rule can only have one type. policyQuads.push(quad(namedNode(policyIRI), ODRL.terms.permission, newRuleNode), quad(newRuleNode, RDF.terms.type, profileRule), @@ -287,7 +290,7 @@ describe('The ODRL Validator', (): void => { describe('with a subproperty of odrl:operand', (): void => { // A logical constraint on newRuleNode: ex:myLogicalOp ( constraint1 constraint2 ) const logicalConstraintQuads = (): Quad[] => { - const logicalConstraint = namedNode("https://example.org/logicalconstraint") + const logicalConstraint = namedNode("https://example.org/logicalconstraint"). const constraint1 = namedNode("https://example.org/constraint1") const constraint2 = namedNode("https://example.org/constraint2") const list1 = blankNode()