Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2dc478f5a3 | |||
| 88f10f9db4 |
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@arbiter/evidence-dsl",
|
"name": "@arbiter/evidence-dsl",
|
||||||
"version": "1.1.0",
|
"version": "1.3.0",
|
||||||
"description": "Evidence DSL v2 compiler: translates the natural Evidence DSL (ADR-000) into @arbiter/core relation configurations.",
|
"description": "Evidence DSL v2 compiler: translates the natural Evidence DSL (ADR-000) into @arbiter/core relation configurations.",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|||||||
+175
-38
@@ -10,6 +10,7 @@ export class RuleGenerator {
|
|||||||
this.generatedRules = new Map();
|
this.generatedRules = new Map();
|
||||||
this.errors = [];
|
this.errors = [];
|
||||||
this.dependencyIndex = new Map();
|
this.dependencyIndex = new Map();
|
||||||
|
this.evidenceNames = new Set();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -38,6 +39,14 @@ export class RuleGenerator {
|
|||||||
this.generateFactConfig(fact);
|
this.generateFactConfig(fact);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Resolve evidence composition: a rule that references another derived
|
||||||
|
// evidence (WHEN can_read(user, doc) where can_read is an evidence) is
|
||||||
|
// lowered in place to that evidence's own config — compile-time inlining
|
||||||
|
// (a linker pass), so the engine evaluates a fully-resolved config tree
|
||||||
|
// and never needs a sub-query traversal mechanism. Forward references are
|
||||||
|
// handled because every evidence config is built before this pass runs.
|
||||||
|
this.resolveEvidenceReferences();
|
||||||
|
|
||||||
// Apply generated rules to arbiter
|
// Apply generated rules to arbiter
|
||||||
this.applyRulesToArbiter();
|
this.applyRulesToArbiter();
|
||||||
|
|
||||||
@@ -62,6 +71,7 @@ export class RuleGenerator {
|
|||||||
*/
|
*/
|
||||||
generateEvidenceRules(evidence) {
|
generateEvidenceRules(evidence) {
|
||||||
const relationName = evidence.name;
|
const relationName = evidence.name;
|
||||||
|
this.evidenceNames.add(relationName);
|
||||||
const ruleConfig = this.buildRuleConfig(evidence);
|
const ruleConfig = this.buildRuleConfig(evidence);
|
||||||
|
|
||||||
if (ruleConfig) {
|
if (ruleConfig) {
|
||||||
@@ -162,6 +172,7 @@ export class RuleGenerator {
|
|||||||
for (const child of ruleList) collect(child, targetSet);
|
for (const child of ruleList) collect(child, targetSet);
|
||||||
}
|
}
|
||||||
if (node?.rule) collect(node.rule, targetSet);
|
if (node?.rule) collect(node.rule, targetSet);
|
||||||
|
if (node?.direct) collect(node.direct, targetSet);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -274,7 +285,7 @@ export class RuleGenerator {
|
|||||||
buildSingleStatementRule(statement, evidence) {
|
buildSingleStatementRule(statement, evidence) {
|
||||||
switch (statement.type) {
|
switch (statement.type) {
|
||||||
case 'DirectEvidence':
|
case 'DirectEvidence':
|
||||||
return this.buildDirectRule(statement);
|
return this.buildDirectRule(statement, evidence);
|
||||||
case 'PatternMatch':
|
case 'PatternMatch':
|
||||||
return this.buildPatternMatchRule(statement, evidence);
|
return this.buildPatternMatchRule(statement, evidence);
|
||||||
case 'DefeasibleLogic':
|
case 'DefeasibleLogic':
|
||||||
@@ -282,7 +293,7 @@ export class RuleGenerator {
|
|||||||
case 'Fusion':
|
case 'Fusion':
|
||||||
return this.buildFusionRule(statement);
|
return this.buildFusionRule(statement);
|
||||||
case 'PredicateCall':
|
case 'PredicateCall':
|
||||||
return this.buildPredicateRule(statement);
|
return this.buildPredicateRule(statement, evidence);
|
||||||
case 'UnaryExpression':
|
case 'UnaryExpression':
|
||||||
return this.buildUnaryRule(statement);
|
return this.buildUnaryRule(statement);
|
||||||
case 'BinaryExpression':
|
case 'BinaryExpression':
|
||||||
@@ -291,7 +302,7 @@ export class RuleGenerator {
|
|||||||
case 'Expression':
|
case 'Expression':
|
||||||
// Handle expressions that might be predicate calls
|
// Handle expressions that might be predicate calls
|
||||||
if (statement.type === 'PredicateCall') {
|
if (statement.type === 'PredicateCall') {
|
||||||
return this.buildPredicateRule(statement);
|
return this.buildPredicateRule(statement, evidence);
|
||||||
}
|
}
|
||||||
return this.buildRuleFromExpressionNode(statement, evidence);
|
return this.buildRuleFromExpressionNode(statement, evidence);
|
||||||
default:
|
default:
|
||||||
@@ -459,7 +470,7 @@ export class RuleGenerator {
|
|||||||
* @param {DirectEvidenceNode} directEvidence - Direct evidence statement
|
* @param {DirectEvidenceNode} directEvidence - Direct evidence statement
|
||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildDirectRule(directEvidence) {
|
buildDirectRule(directEvidence, evidence) {
|
||||||
if (!directEvidence.predicate) {
|
if (!directEvidence.predicate) {
|
||||||
this.errors.push('Direct evidence must have a predicate');
|
this.errors.push('Direct evidence must have a predicate');
|
||||||
return null;
|
return null;
|
||||||
@@ -468,11 +479,23 @@ export class RuleGenerator {
|
|||||||
const predicate = directEvidence.predicate;
|
const predicate = directEvidence.predicate;
|
||||||
const relation = predicate.name;
|
const relation = predicate.name;
|
||||||
|
|
||||||
return {
|
const rule = {
|
||||||
type: 'direct',
|
type: 'direct',
|
||||||
relation: relation,
|
relation: relation,
|
||||||
reverse: false
|
reverse: false
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Subject-scoped (unary) call: the predicate call's args omit the
|
||||||
|
// evidence's object parameter (user_risk(user, 1) inside a binary
|
||||||
|
// evidence) → check the relation on the subject itself.
|
||||||
|
const evidenceParams = (evidence && evidence.params) || [];
|
||||||
|
const objectVar = evidenceParams[1] && evidenceParams[1].name;
|
||||||
|
const argName = a => a && (a.name !== undefined ? a.name : a.value);
|
||||||
|
if (objectVar !== undefined && !(predicate.arguments || []).some(a => argName(a) === objectVar)) {
|
||||||
|
rule._subjectAsObject = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return rule;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -925,9 +948,6 @@ export class RuleGenerator {
|
|||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildDirectRuleFromPredicate(predicate, evidence) {
|
buildDirectRuleFromPredicate(predicate, evidence) {
|
||||||
const expanded = this._expandPredicate(predicate.name);
|
|
||||||
if (expanded) return expanded;
|
|
||||||
|
|
||||||
const rule = {
|
const rule = {
|
||||||
type: 'direct',
|
type: 'direct',
|
||||||
relation: predicate.name,
|
relation: predicate.name,
|
||||||
@@ -944,36 +964,158 @@ export class RuleGenerator {
|
|||||||
return rule;
|
return rule;
|
||||||
}
|
}
|
||||||
|
|
||||||
_expandPredicate(predicateName) {
|
_expandPredicate() {
|
||||||
const existingConfig = this.generatedRules.get(predicateName) || this.arbiter?.relationConfigs?.get(predicateName);
|
// Replaced by resolveEvidenceReferences() (the compile-time evidence
|
||||||
if (!existingConfig) return null;
|
// composition pass). Predicate references are now emitted as direct rules
|
||||||
if (!existingConfig.union && !existingConfig.intersection && !existingConfig.exclusion) return null;
|
// and inlined during resolution, which also handles forward references and
|
||||||
|
// preserves the correct _subjectAsObject scoping.
|
||||||
|
}
|
||||||
|
|
||||||
const logicalKey = existingConfig.union ? 'union' : existingConfig.intersection ? 'intersection' : 'exclusion';
|
/**
|
||||||
const subRules = Array.isArray(existingConfig[logicalKey]?.rules)
|
* Evidence composition pass. Every rule that references a DERIVED evidence
|
||||||
? existingConfig[logicalKey].rules
|
* (e.g. `WHEN can_read(user, doc)` where can_read is itself an evidence) is
|
||||||
: Array.isArray(existingConfig[logicalKey]) ? existingConfig[logicalKey] : [];
|
* rewritten to inline that evidence's own config. This runs after all
|
||||||
|
* evidence configs are generated, so forward references resolve; cycles are
|
||||||
|
* detected and reported. The engine therefore evaluates a fully-resolved,
|
||||||
|
* acyclic config tree — no runtime sub-query traversal is needed.
|
||||||
|
*/
|
||||||
|
resolveEvidenceReferences() {
|
||||||
|
for (const name of this.evidenceNames) {
|
||||||
|
if (!this.generatedRules.has(name)) continue;
|
||||||
|
const stack = new Set([name]);
|
||||||
|
const resolved = this._resolveRule(this.generatedRules.get(name), stack);
|
||||||
|
this.generatedRules.set(name, resolved);
|
||||||
|
this._annotateDependencies(name, resolved);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (subRules.length === 0) return null;
|
/**
|
||||||
|
* Recursively rewrite a rule tree, inlining references to derived evidence
|
||||||
|
* configs. `stack` holds the evidence names currently being expanded so a
|
||||||
|
* cyclic reference (A → B → A) is detected and reported.
|
||||||
|
*/
|
||||||
|
_resolveRule(rule, stack) {
|
||||||
|
if (!rule || typeof rule !== 'object') return rule;
|
||||||
|
if (Array.isArray(rule)) return rule.map(r => this._resolveRule(r, stack));
|
||||||
|
|
||||||
const expandedRules = subRules.map(r => {
|
// Direct rule referencing a derived evidence → inline its resolved config.
|
||||||
if (r && r.type === 'direct') return { type: 'direct', relation: r.relation, reverse: !!r.reverse };
|
if (rule.type === 'direct' && rule.relation) {
|
||||||
if (typeof r === 'string') return { type: 'direct', relation: r, reverse: false };
|
const ref = rule.relation;
|
||||||
return null;
|
if (this.evidenceNames.has(ref)) {
|
||||||
}).filter(Boolean);
|
const referencedConfig = this.generatedRules.get(ref);
|
||||||
|
if (referencedConfig) {
|
||||||
|
if (stack.has(ref)) {
|
||||||
|
this.errors.push(`Cyclic evidence reference involving '${ref}'. Evidence composition must be acyclic.`);
|
||||||
|
return rule;
|
||||||
|
}
|
||||||
|
const refStack = new Set(stack);
|
||||||
|
refStack.add(ref);
|
||||||
|
const resolvedRef = this._resolveRule(referencedConfig, refStack);
|
||||||
|
if (resolvedRef) {
|
||||||
|
const clone = this._deepCloneRule(resolvedRef);
|
||||||
|
if (rule._subjectAsObject) clone._subjectAsObject = true;
|
||||||
|
return clone;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rule;
|
||||||
|
}
|
||||||
|
|
||||||
if (expandedRules.length === 0) return null;
|
// Recurse into logical / defeasible / nested containers: rule-lists
|
||||||
|
// (union/intersection/exclusion/never/requires/when/unless .rules) and
|
||||||
|
// single nested rules (always.direct, comparator operands).
|
||||||
|
const out = { ...rule };
|
||||||
|
for (const key of ['union', 'intersection', 'exclusion', 'never', 'always', 'requires', 'when', 'unless', 'direct', 'rule']) {
|
||||||
|
const node = out[key];
|
||||||
|
if (!node || typeof node !== 'object') continue;
|
||||||
|
if (Array.isArray(node)) {
|
||||||
|
out[key] = node.map(r => this._resolveRule(r, stack));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const next = { ...node };
|
||||||
|
if (Array.isArray(next.rules)) {
|
||||||
|
next.rules = next.rules.map(r => this._resolveRule(r, stack));
|
||||||
|
}
|
||||||
|
if (next.union && Array.isArray(next.union.rules)) {
|
||||||
|
next.union = { ...next.union, rules: next.union.rules.map(r => this._resolveRule(r, stack)) };
|
||||||
|
}
|
||||||
|
if (next.intersection && Array.isArray(next.intersection.rules)) {
|
||||||
|
next.intersection = { ...next.intersection, rules: next.intersection.rules.map(r => this._resolveRule(r, stack)) };
|
||||||
|
}
|
||||||
|
if (next.direct && typeof next.direct === 'object') {
|
||||||
|
next.direct = this._resolveRule(next.direct, stack);
|
||||||
|
}
|
||||||
|
if (next.rule && typeof next.rule === 'object') {
|
||||||
|
next.rule = this._resolveRule(next.rule, stack);
|
||||||
|
}
|
||||||
|
out[key] = next;
|
||||||
|
}
|
||||||
|
if (out.type === 'relational_comparator') {
|
||||||
|
if (out.left?.rule) out.left = { ...out.left, rule: this._resolveRule(out.left.rule, stack) };
|
||||||
|
if (out.right?.rule) out.right = { ...out.right, rule: this._resolveRule(out.right.rule, stack) };
|
||||||
|
}
|
||||||
|
// Chain steps may reference a derived evidence; expand those steps
|
||||||
|
// (direct evidence → underlying relation, chain evidence → spliced steps).
|
||||||
|
if (rule.type === 'chain' && Array.isArray(out.steps)) {
|
||||||
|
out.steps = this._expandChainSteps(out.steps, stack);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
/**
|
||||||
type: 'logical',
|
* Expand chain steps that reference a derived evidence:
|
||||||
[logicalKey]: {
|
* - direct evidence → rename the step to the underlying relation
|
||||||
rules: expandedRules,
|
* (member_of(user,*g){ group_read(g,doc) } where group_read = can_view
|
||||||
aggregator: existingConfig[logicalKey]?.aggregator || 'min'
|
* becomes step 'can_view');
|
||||||
},
|
* - chain evidence → splice its steps into this chain (flattening)
|
||||||
// Flag to tell the evaluator: this expanded sub-predicate is unary —
|
* (a step that is itself a sub-path becomes its steps, preserving the
|
||||||
// use the subject as the object instead of inheriting the parent's object.
|
* linear source→…→object traversal);
|
||||||
_subjectAsObject: true
|
* - anything else (defeasible/logical/comparator) → compile error: such a
|
||||||
};
|
* step is a condition, not an edge traversal, and cannot lower to a flat
|
||||||
|
* chain step.
|
||||||
|
*/
|
||||||
|
_expandChainSteps(steps, stack) {
|
||||||
|
const out = [];
|
||||||
|
for (const step of steps) {
|
||||||
|
const stepName = typeof step === 'string' ? step : step.relation;
|
||||||
|
if (stepName && this.evidenceNames.has(stepName)) {
|
||||||
|
if (stack.has(stepName)) {
|
||||||
|
this.errors.push(`Cyclic evidence reference involving '${stepName}'. Evidence composition must be acyclic.`);
|
||||||
|
out.push(step);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const referencedConfig = this.generatedRules.get(stepName);
|
||||||
|
if (referencedConfig) {
|
||||||
|
const refStack = new Set(stack);
|
||||||
|
refStack.add(stepName);
|
||||||
|
const resolved = this._resolveRule(referencedConfig, refStack);
|
||||||
|
if (resolved.type === 'direct' && resolved.relation && resolved.relation !== stepName) {
|
||||||
|
out.push(typeof step === 'string'
|
||||||
|
? resolved.relation
|
||||||
|
: { ...step, relation: resolved.relation });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (resolved.type === 'chain' && Array.isArray(resolved.steps)) {
|
||||||
|
out.push(...this._expandChainSteps(resolved.steps, refStack));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
this.errors.push(`Chain step '${stepName}' references an evidence with type '${resolved.type || 'logical'}'. ` +
|
||||||
|
'Chain steps can only reference facts, direct evidence, or chain evidence.');
|
||||||
|
out.push(step);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push(step);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
_deepCloneRule(rule) {
|
||||||
|
try {
|
||||||
|
return structuredClone(rule);
|
||||||
|
} catch {
|
||||||
|
return JSON.parse(JSON.stringify(rule));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1120,11 +1262,6 @@ export class RuleGenerator {
|
|||||||
return this.buildChallengeRule(expression, null);
|
return this.buildChallengeRule(expression, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Expand composite (logical) predicate references into their direct
|
|
||||||
// leaf components so the optimizer can flatten to a correct direct_list.
|
|
||||||
const expanded = this._expandPredicate(predicateName);
|
|
||||||
if (expanded) return expanded;
|
|
||||||
|
|
||||||
const rule = {
|
const rule = {
|
||||||
type: 'direct',
|
type: 'direct',
|
||||||
relation: predicateName,
|
relation: predicateName,
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ export function validateDslText(dslText, options = {}) {
|
|||||||
validateSources(program, tables, errors, warnings, dslText);
|
validateSources(program, tables, errors, warnings, dslText);
|
||||||
validateMeasures(program, tables, errors, warnings, dslText);
|
validateMeasures(program, tables, errors, warnings, dslText);
|
||||||
validateEvidence(program, tables, errors, warnings, dslText);
|
validateEvidence(program, tables, errors, warnings, dslText);
|
||||||
|
validateCrossKindRelationNames(program, errors, warnings, dslText);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: errors.length === 0,
|
success: errors.length === 0,
|
||||||
@@ -335,6 +336,37 @@ function validateEvidence(program, tables, errors, warnings, source) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Relation names must be unique across facts, sources, evidence, and measures.
|
||||||
|
* A fact and an evidence sharing a name would silently overwrite each other's
|
||||||
|
* relation config during generation (and read as a false cyclic reference).
|
||||||
|
*/
|
||||||
|
function validateCrossKindRelationNames(program, errors, warnings, source) {
|
||||||
|
const seen = new Map();
|
||||||
|
const kinds = [
|
||||||
|
['fact', program.facts],
|
||||||
|
['source', program.sources],
|
||||||
|
['evidence', program.evidence],
|
||||||
|
['measure', program.measures]
|
||||||
|
];
|
||||||
|
for (const [kind, items] of kinds) {
|
||||||
|
for (const item of items || []) {
|
||||||
|
const prev = seen.get(item.name);
|
||||||
|
if (prev) {
|
||||||
|
errors.push(createError({
|
||||||
|
message: `Name '${item.name}' is already used by a ${prev} declaration.`,
|
||||||
|
rule: 'Relation names must be unique across facts, sources, evidence, and measures.',
|
||||||
|
fix: `Rename the ${kind} or the ${prev} to a unique name.`,
|
||||||
|
location: findLocation(source, `${kind} ${item.name}`),
|
||||||
|
context: formatContext(source, findLocation(source, item.name))
|
||||||
|
}));
|
||||||
|
} else {
|
||||||
|
seen.set(item.name, kind);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function validateEvidenceBody(body, scope, tables, errors, warnings, source, parent) {
|
function validateEvidenceBody(body, scope, tables, errors, warnings, source, parent) {
|
||||||
for (const stmt of body.statements || []) {
|
for (const stmt of body.statements || []) {
|
||||||
switch (stmt.type) {
|
switch (stmt.type) {
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
/**
|
||||||
|
* tests/ChainStepComposition.test.js — evidence composition inside CHAIN
|
||||||
|
* steps. A chain step that references a derived evidence is expanded at
|
||||||
|
* compile time:
|
||||||
|
* - a DIRECT evidence step → renamed to its underlying relation
|
||||||
|
* (member_of(user,*g){ group_read(g,doc) } where group_read = can_view
|
||||||
|
* becomes step 'can_view');
|
||||||
|
* - a CHAIN evidence step → its steps are spliced into the parent chain
|
||||||
|
* (a sub-path flattens into the linear source→…→object traversal);
|
||||||
|
* - a DEFEASIBLE / LOGICAL / COMPARATOR evidence step is not an edge
|
||||||
|
* traversal and is rejected at compile time;
|
||||||
|
* - cycles and self-references through chain steps are compile errors.
|
||||||
|
*/
|
||||||
|
import { describe, it } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { Arbiter } from '@arbiter/core';
|
||||||
|
import { DSLCompiler } from '../src/DSLCompiler.js';
|
||||||
|
|
||||||
|
const DEFS = `
|
||||||
|
definition Employee { id: string }
|
||||||
|
definition Group { id: string }
|
||||||
|
definition Doc { id: string }
|
||||||
|
fact member_of(user: Employee, group: Group)
|
||||||
|
fact group_has(group: Group, sub: Group)
|
||||||
|
fact can_view(group: Group, doc: Doc)
|
||||||
|
fact can_access(group: Group, doc: Doc)
|
||||||
|
fact banned(group: Group)
|
||||||
|
`;
|
||||||
|
|
||||||
|
function compile(dsl, name = 'chain-compose') {
|
||||||
|
const arb = new Arbiter();
|
||||||
|
const compiler = new DSLCompiler(arb);
|
||||||
|
const result = compiler.compile(dsl, name);
|
||||||
|
return { arb, result };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Chain step composition', () => {
|
||||||
|
it('renames a direct-evidence chain step to its underlying relation', () => {
|
||||||
|
const { arb, result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
evidence group_read(group: Group, doc: Doc) { can_view(group, doc) }
|
||||||
|
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { group_read(g, doc) } }
|
||||||
|
`);
|
||||||
|
assert.ok(result.success, JSON.stringify(result.errors));
|
||||||
|
// step 'group_read' → 'can_view'
|
||||||
|
assert.deepEqual(arb.relationConfigs.get('can_via').steps, ['member_of', 'can_view']);
|
||||||
|
arb.addNode('u:1', 'Employee'); arb.addNode('g:1', 'Group'); arb.addNode('doc:9', 'Doc');
|
||||||
|
arb.addRelation('u:1', 'member_of', 'g:1', { possibility: 1.0 });
|
||||||
|
arb.addRelation('g:1', 'can_view', 'doc:9', { possibility: 0.7 });
|
||||||
|
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0.7);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('splices a chain-evidence step into the parent chain', () => {
|
||||||
|
const { arb, result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
evidence group_enter(group: Group, doc: Doc) { group_has(group, *s) { can_access(s, doc) } }
|
||||||
|
evidence can_deep(user: Employee, doc: Doc) { member_of(user, *g) { group_enter(g, doc) } }
|
||||||
|
`);
|
||||||
|
assert.ok(result.success, JSON.stringify(result.errors));
|
||||||
|
// step 'group_enter' → its steps [group_has, can_access]
|
||||||
|
assert.deepEqual(arb.relationConfigs.get('can_deep').steps, ['member_of', 'group_has', 'can_access']);
|
||||||
|
arb.addNode('u:1', 'Employee'); arb.addNode('g:1', 'Group'); arb.addNode('g2:2', 'Group'); arb.addNode('doc:9', 'Doc');
|
||||||
|
arb.addRelation('u:1', 'member_of', 'g:1', { possibility: 1.0 });
|
||||||
|
arb.addRelation('g:1', 'group_has', 'g2:2', { possibility: 0.9 });
|
||||||
|
arb.addRelation('g2:2', 'can_access', 'doc:9', { possibility: 0.8 });
|
||||||
|
assert.equal(arb.check('u:1', 'can_deep', 'doc:9').possibility, 0.8);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('expands a chain step whose direct evidence is itself composed', () => {
|
||||||
|
const { arb, result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
evidence group_view(group: Group, doc: Doc) { can_view(group, doc) }
|
||||||
|
evidence group_read(group: Group, doc: Doc) { group_view(group, doc) }
|
||||||
|
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { group_read(g, doc) } }
|
||||||
|
`);
|
||||||
|
assert.ok(result.success, JSON.stringify(result.errors));
|
||||||
|
assert.deepEqual(arb.relationConfigs.get('can_via').steps, ['member_of', 'can_view']);
|
||||||
|
arb.addNode('u:1', 'Employee'); arb.addNode('g:1', 'Group'); arb.addNode('doc:9', 'Doc');
|
||||||
|
arb.addRelation('u:1', 'member_of', 'g:1', { possibility: 1.0 });
|
||||||
|
arb.addRelation('g:1', 'can_view', 'doc:9', { possibility: 0.6 });
|
||||||
|
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0.6);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a defeasible/logical evidence as a chain step', () => {
|
||||||
|
const { result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
evidence gated(group: Group, doc: Doc) { WHEN can_view(group, doc) UNLESS banned(group) }
|
||||||
|
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }
|
||||||
|
`);
|
||||||
|
assert.equal(result.success, false);
|
||||||
|
assert.ok(result.errors.some(e => /Chain step 'gated'/.test(e)), JSON.stringify(result.errors));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a mutual cycle through chain steps', () => {
|
||||||
|
const { result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
evidence cyc_a(group: Group, doc: Doc) { group_has(group, *g) { cyc_b(g, doc) } }
|
||||||
|
evidence cyc_b(group: Group, doc: Doc) { cyc_a(group, doc) }
|
||||||
|
`);
|
||||||
|
assert.equal(result.success, false);
|
||||||
|
assert.ok(result.errors.some(e => /[Cc]yclic/.test(e)), JSON.stringify(result.errors));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a self-reference through its own chain step', () => {
|
||||||
|
const { result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
evidence cyc_c(group: Group, doc: Doc) { group_has(group, *g) { cyc_c(g, doc) } }
|
||||||
|
`);
|
||||||
|
assert.equal(result.success, false);
|
||||||
|
assert.ok(result.errors.some(e => /[Cc]yclic/.test(e)), JSON.stringify(result.errors));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('re-derives transitive dependencies through expanded chain steps', () => {
|
||||||
|
const { arb, result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
evidence group_read(group: Group, doc: Doc) { can_view(group, doc) }
|
||||||
|
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { group_read(g, doc) } }
|
||||||
|
`);
|
||||||
|
assert.ok(result.success, JSON.stringify(result.errors));
|
||||||
|
// dependsOn reflects the expanded step, not the evidence reference
|
||||||
|
assert.deepEqual(arb.relationConfigs.get('can_via').dependsOn, ['member_of', 'can_view']);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -161,4 +161,31 @@ describe('DSLRuntime', () => {
|
|||||||
rt.addNode('doc:9', 'Doc', {});
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
await assert.rejects(() => rt.check('u:1', 'does_not_exist', 'doc:9'), /unknown relation/);
|
await assert.rejects(() => rt.check('u:1', 'does_not_exist', 'doc:9'), /unknown relation/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('derives transitive required facts through evidence composition', async () => {
|
||||||
|
const dsl = `
|
||||||
|
definition Employee { id: string }
|
||||||
|
definition Doc { id: string }
|
||||||
|
fact *owns(user: Employee, doc: Doc)
|
||||||
|
fact *banned(user: Employee)
|
||||||
|
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
|
evidence can_open(user: Employee, doc: Doc) { WHEN can_read(user, doc) UNLESS banned(user) }
|
||||||
|
`;
|
||||||
|
const rt = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-comp');
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
// can_open composes can_read, so its requirements reach through to owns.
|
||||||
|
assert.deepEqual(rt.requiredFacts('can_open'), ['owns', 'banned']);
|
||||||
|
const granted = await rt.check('u:1', 'can_open', 'doc:9', {
|
||||||
|
factProviders: { owns: async () => 0.9, banned: async () => 0 }
|
||||||
|
});
|
||||||
|
assert.equal(granted.possibility, 0.9);
|
||||||
|
assert.equal(granted.reason, 'allow_rule_matched');
|
||||||
|
assert.deepEqual(granted.providedFacts, ['owns', 'banned']);
|
||||||
|
const denied = await rt.check('u:1', 'can_open', 'doc:9', {
|
||||||
|
factProviders: { owns: async () => 0.9, banned: async () => 1 }
|
||||||
|
});
|
||||||
|
assert.equal(denied.possibility, 0);
|
||||||
|
assert.equal(denied.reason, 'defeated_by_unless');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
/**
|
||||||
|
* tests/EvidenceComposition.test.js — referencing a derived evidence as a
|
||||||
|
* sub-rule of another evidence (WHEN can_read(user, doc) where can_read is
|
||||||
|
* itself an evidence).
|
||||||
|
*
|
||||||
|
* Composition is resolved at COMPILE time: the generator inlines each
|
||||||
|
* evidence reference with the referenced evidence's own config (a linker
|
||||||
|
* pass that handles forward references and rejects cycles), so the engine
|
||||||
|
* evaluates a fully-resolved, acyclic config tree.
|
||||||
|
*/
|
||||||
|
import { describe, it } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { Arbiter } from '@arbiter/core';
|
||||||
|
import { DSLCompiler } from '../src/DSLCompiler.js';
|
||||||
|
|
||||||
|
const DEFS = `
|
||||||
|
definition Employee { id: string }
|
||||||
|
definition Group { id: string }
|
||||||
|
definition Doc { id: string }
|
||||||
|
fact owns(user: Employee, doc: Doc)
|
||||||
|
fact *trusted(user: Employee)
|
||||||
|
fact member_of(user: Employee, group: Group)
|
||||||
|
fact can_access(group: Group, doc: Doc)
|
||||||
|
`;
|
||||||
|
|
||||||
|
function compile(dsl, name = 'compose') {
|
||||||
|
const arb = new Arbiter();
|
||||||
|
const compiler = new DSLCompiler(arb);
|
||||||
|
const result = compiler.compile(dsl, name);
|
||||||
|
return { arb, result };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Evidence composition', () => {
|
||||||
|
it('composes a direct evidence into another evidence', () => {
|
||||||
|
const { arb, result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
|
evidence can_browse(user: Employee, doc: Doc) { can_read(user, doc) }
|
||||||
|
`);
|
||||||
|
assert.ok(result.success, JSON.stringify(result.errors));
|
||||||
|
arb.addNode('u:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||||
|
arb.addRelation('u:1', 'owns', 'doc:9', { possibility: 0.8 });
|
||||||
|
const res = arb.check('u:1', 'can_browse', 'doc:9');
|
||||||
|
assert.equal(res.possibility, 0.8);
|
||||||
|
// The reference is inlined to the underlying fact config.
|
||||||
|
assert.equal(arb.relationConfigs.get('can_browse').type, 'direct');
|
||||||
|
assert.equal(arb.relationConfigs.get('can_browse').relation, 'owns');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('composes an evidence inside a defeasible WHEN/UNLESS', () => {
|
||||||
|
const { arb, result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
|
evidence can_open(user: Employee, doc: Doc) { WHEN can_read(user, doc) UNLESS trusted(user) }
|
||||||
|
`);
|
||||||
|
assert.ok(result.success, JSON.stringify(result.errors));
|
||||||
|
arb.addNode('u:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||||
|
arb.addRelation('u:1', 'owns', 'doc:9', { possibility: 0.9 });
|
||||||
|
assert.equal(arb.check('u:1', 'can_open', 'doc:9').possibility, 0.9);
|
||||||
|
arb.addRelation('u:1', 'trusted', 'u:1', { possibility: 1.0 });
|
||||||
|
const denied = arb.check('u:1', 'can_open', 'doc:9');
|
||||||
|
assert.equal(denied.possibility, 0);
|
||||||
|
assert.equal(denied.reason, 'defeated_by_unless');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('composes a chain evidence into another evidence', () => {
|
||||||
|
const { arb, result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
evidence can_enter(user: Employee, doc: Doc) { member_of(user, *g) { can_access(g, doc) } }
|
||||||
|
evidence can_work(user: Employee, doc: Doc) { can_enter(user, doc) }
|
||||||
|
`);
|
||||||
|
assert.ok(result.success, JSON.stringify(result.errors));
|
||||||
|
arb.addNode('u:1', 'Employee'); arb.addNode('g:1', 'Group'); arb.addNode('doc:9', 'Doc');
|
||||||
|
arb.addRelation('u:1', 'member_of', 'g:1', { possibility: 1.0 });
|
||||||
|
arb.addRelation('g:1', 'can_access', 'doc:9', { possibility: 0.7 });
|
||||||
|
const res = arb.check('u:1', 'can_work', 'doc:9');
|
||||||
|
assert.equal(res.possibility, 0.7);
|
||||||
|
assert.equal(arb.relationConfigs.get('can_work').type, 'chain');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('composes transitively (A → B → fact) and re-derives dependencies', () => {
|
||||||
|
const { arb, result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
|
evidence can_browse(user: Employee, doc: Doc) { can_read(user, doc) }
|
||||||
|
evidence can_open(user: Employee, doc: Doc) { can_browse(user, doc) }
|
||||||
|
`);
|
||||||
|
assert.ok(result.success, JSON.stringify(result.errors));
|
||||||
|
arb.addNode('u:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||||
|
arb.addRelation('u:1', 'owns', 'doc:9', { possibility: 0.6 });
|
||||||
|
assert.equal(arb.check('u:1', 'can_open', 'doc:9').possibility, 0.6);
|
||||||
|
assert.deepEqual(arb.relationConfigs.get('can_open').dependsOn, ['owns']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('composes a value-carrying evidence and preserves subject-as-object scope', () => {
|
||||||
|
const { arb, result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
fact *user_risk(user: Employee, value: number)
|
||||||
|
evidence risk_ok(user: Employee, doc: Doc) { user_risk(user, 1) }
|
||||||
|
evidence can_proceed(user: Employee, doc: Doc) { risk_ok(user, doc) }
|
||||||
|
`);
|
||||||
|
assert.ok(result.success, JSON.stringify(result.errors));
|
||||||
|
arb.addNode('u:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||||
|
arb.addRelation('u:1', 'user_risk', 'u:1', { possibility: 1.0, value: 1 });
|
||||||
|
const res = arb.check('u:1', 'can_proceed', 'doc:9');
|
||||||
|
assert.equal(res.possibility, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('composes evidence inside a comparator operand', () => {
|
||||||
|
const { arb, result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
fact *user_risk(user: Employee, value: number)
|
||||||
|
fact *risk_limit(doc: Doc, value: number)
|
||||||
|
evidence user_risk_ok(user: Employee, doc: Doc) { user_risk(user, 1) }
|
||||||
|
evidence can_proceed(user: Employee, doc: Doc) { user_risk_ok(user, doc) }
|
||||||
|
`);
|
||||||
|
assert.ok(result.success, JSON.stringify(result.errors));
|
||||||
|
arb.addNode('u:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||||
|
arb.addRelation('u:1', 'user_risk', 'u:1', { possibility: 1.0, value: 1 });
|
||||||
|
assert.equal(arb.check('u:1', 'can_proceed', 'doc:9').possibility, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects cyclic evidence references at compile time', () => {
|
||||||
|
const { result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
evidence a(user: Employee, doc: Doc) { b(user, doc) }
|
||||||
|
evidence b(user: Employee, doc: Doc) { a(user, doc) }
|
||||||
|
`);
|
||||||
|
assert.equal(result.success, false);
|
||||||
|
assert.ok(result.errors.some(e => /[Cc]yclic/.test(e)), JSON.stringify(result.errors));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects self-referencing evidence at compile time', () => {
|
||||||
|
const { result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
evidence a(user: Employee, doc: Doc) { a(user, doc) }
|
||||||
|
`);
|
||||||
|
assert.equal(result.success, false);
|
||||||
|
assert.ok(result.errors.some(e => /[Cc]yclic/.test(e)), JSON.stringify(result.errors));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the referenced evidence checkable in its own right', () => {
|
||||||
|
const { arb, result } = compile(`
|
||||||
|
${DEFS}
|
||||||
|
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
|
evidence can_browse(user: Employee, doc: Doc) { can_read(user, doc) }
|
||||||
|
`);
|
||||||
|
assert.ok(result.success);
|
||||||
|
arb.addNode('u:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||||
|
arb.addRelation('u:1', 'owns', 'doc:9', { possibility: 0.5 });
|
||||||
|
assert.equal(arb.check('u:1', 'can_read', 'doc:9').possibility, 0.5);
|
||||||
|
assert.equal(arb.check('u:1', 'can_browse', 'doc:9').possibility, 0.5);
|
||||||
|
});
|
||||||
|
});
|
||||||
+14
-13
@@ -45,6 +45,7 @@ const DSL_SUPPORT = `
|
|||||||
fact isMember(user: any, group: any)
|
fact isMember(user: any, group: any)
|
||||||
fact isFriend(user: any, friend: any)
|
fact isFriend(user: any, friend: any)
|
||||||
fact similar(a: any, b: any)
|
fact similar(a: any, b: any)
|
||||||
|
fact reachable(user: any, doc: any)
|
||||||
fact parentOf(user: any, parent: any)
|
fact parentOf(user: any, parent: any)
|
||||||
fact isEditable(doc: any)
|
fact isEditable(doc: any)
|
||||||
fact isPublic(doc: any)
|
fact isPublic(doc: any)
|
||||||
@@ -159,7 +160,7 @@ describe('Evidence Rules', () => {
|
|||||||
{
|
{
|
||||||
input: `evidence canRead(user: Employee, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canRead(group, doc)
|
reachable(group, doc)
|
||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
description: 'Basic pattern matching with wildcard'
|
description: 'Basic pattern matching with wildcard'
|
||||||
@@ -167,7 +168,7 @@ describe('Evidence Rules', () => {
|
|||||||
{
|
{
|
||||||
input: `evidence canRead(user: Employee, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canRead(group, doc)
|
reachable(group, doc)
|
||||||
} limit 5
|
} limit 5
|
||||||
}`,
|
}`,
|
||||||
description: 'Pattern matching with limit'
|
description: 'Pattern matching with limit'
|
||||||
@@ -175,7 +176,7 @@ describe('Evidence Rules', () => {
|
|||||||
{
|
{
|
||||||
input: `evidence canRead(user: Employee, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
similar(doc, *similar) |similarity| {
|
similar(doc, *similar) |similarity| {
|
||||||
canRead(user, similar)
|
reachable(user, similar)
|
||||||
} with similarity > 0.7
|
} with similarity > 0.7
|
||||||
}`,
|
}`,
|
||||||
description: 'Pattern matching with binding and condition'
|
description: 'Pattern matching with binding and condition'
|
||||||
@@ -183,7 +184,7 @@ describe('Evidence Rules', () => {
|
|||||||
{
|
{
|
||||||
input: `evidence canRead(user: Employee, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
similar(doc, *similar) |similarity| {
|
similar(doc, *similar) |similarity| {
|
||||||
canRead(user, similar)
|
reachable(user, similar)
|
||||||
} limit 5 with similarity > 0.7
|
} limit 5 with similarity > 0.7
|
||||||
}`,
|
}`,
|
||||||
description: 'Pattern matching with binding, condition, and limit'
|
description: 'Pattern matching with binding, condition, and limit'
|
||||||
@@ -192,7 +193,7 @@ describe('Evidence Rules', () => {
|
|||||||
input: `evidence canRead(user: Employee, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
isMember(group, *parentGroup) {
|
isMember(group, *parentGroup) {
|
||||||
canRead(parentGroup, doc)
|
reachable(parentGroup, doc)
|
||||||
} limit 2
|
} limit 2
|
||||||
} limit 3
|
} limit 3
|
||||||
}`,
|
}`,
|
||||||
@@ -202,7 +203,7 @@ describe('Evidence Rules', () => {
|
|||||||
input: `evidence canRead(user: Employee, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
isFriend(user, *friend) {
|
isFriend(user, *friend) {
|
||||||
isMember(friend, *group) {
|
isMember(friend, *group) {
|
||||||
canRead(group, doc)
|
reachable(group, doc)
|
||||||
} limit 1
|
} limit 1
|
||||||
} limit 5
|
} limit 5
|
||||||
}`,
|
}`,
|
||||||
@@ -291,15 +292,15 @@ describe('Evidence Rules', () => {
|
|||||||
owns(user, doc)
|
owns(user, doc)
|
||||||
|
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canRead(group, doc)
|
reachable(group, doc)
|
||||||
} limit 5
|
} limit 5
|
||||||
|
|
||||||
parentOf(user, *parent) {
|
parentOf(user, *parent) {
|
||||||
canRead(parent, doc)
|
reachable(parent, doc)
|
||||||
} limit 3
|
} limit 3
|
||||||
|
|
||||||
similar(doc, *similar) |similarity| {
|
similar(doc, *similar) |similarity| {
|
||||||
canRead(user, similar)
|
reachable(user, similar)
|
||||||
} limit 5 with similarity > 0.7
|
} limit 5 with similarity > 0.7
|
||||||
|
|
||||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||||
@@ -337,11 +338,11 @@ describe('Evidence Rules', () => {
|
|||||||
owns(user, doc)
|
owns(user, doc)
|
||||||
|
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canModify(group, doc)
|
reachable(group, doc)
|
||||||
} limit 3
|
} limit 3
|
||||||
|
|
||||||
similar(doc, *similar) |similarity| {
|
similar(doc, *similar) |similarity| {
|
||||||
canModify(user, similar)
|
reachable(user, similar)
|
||||||
isEditable(similar)
|
isEditable(similar)
|
||||||
} limit 2 with similarity > 0.8
|
} limit 2 with similarity > 0.8
|
||||||
|
|
||||||
@@ -385,7 +386,7 @@ describe('Evidence Rules', () => {
|
|||||||
{
|
{
|
||||||
input: `evidence canRead(user: Employee, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canRead(group, doc)
|
reachable(group, doc)
|
||||||
} with
|
} with
|
||||||
}`,
|
}`,
|
||||||
description: 'Incomplete with clause should fail'
|
description: 'Incomplete with clause should fail'
|
||||||
@@ -393,7 +394,7 @@ describe('Evidence Rules', () => {
|
|||||||
{
|
{
|
||||||
input: `evidence canRead(user: Employee, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canRead(group, doc)
|
reachable(group, doc)
|
||||||
} limit
|
} limit
|
||||||
}`,
|
}`,
|
||||||
description: 'Incomplete limit should fail'
|
description: 'Incomplete limit should fail'
|
||||||
|
|||||||
+16
-12
@@ -105,6 +105,7 @@ describe('Integration Tests', () => {
|
|||||||
fact hasAccess(user: Employee, resource: Resource, level: string) CACHE lazy
|
fact hasAccess(user: Employee, resource: Resource, level: string) CACHE lazy
|
||||||
fact isColleague(user: any, colleague: any) symmetrical CACHE lazy limit 50
|
fact isColleague(user: any, colleague: any) symmetrical CACHE lazy limit 50
|
||||||
fact isParentOf(parent: Employee, child: Employee) transitive CACHE eager limit 3
|
fact isParentOf(parent: Employee, child: Employee) transitive CACHE eager limit 3
|
||||||
|
fact reachable(user: any, doc: any) CACHE lazy
|
||||||
fact hasClearance(user: Employee, level: string) CACHE eager
|
fact hasClearance(user: Employee, level: string) CACHE eager
|
||||||
fact parentOf(user: any, parent: any) CACHE eager
|
fact parentOf(user: any, parent: any) CACHE eager
|
||||||
fact similar(a: any, b: any) CACHE lazy
|
fact similar(a: any, b: any) CACHE lazy
|
||||||
@@ -119,15 +120,15 @@ describe('Integration Tests', () => {
|
|||||||
owns(user, doc)
|
owns(user, doc)
|
||||||
|
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canRead(group, doc)
|
reachable(group, doc)
|
||||||
} limit 5
|
} limit 5
|
||||||
|
|
||||||
parentOf(user, *parent) {
|
parentOf(user, *parent) {
|
||||||
canRead(parent, doc)
|
reachable(parent, doc)
|
||||||
} limit 3
|
} limit 3
|
||||||
|
|
||||||
similar(doc, *similar) |similarity| {
|
similar(doc, *similar) |similarity| {
|
||||||
canRead(user, similar)
|
reachable(user, similar)
|
||||||
} limit 5 with similarity > 0.7
|
} limit 5 with similarity > 0.7
|
||||||
|
|
||||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||||
@@ -137,7 +138,7 @@ describe('Integration Tests', () => {
|
|||||||
owns(user, doc)
|
owns(user, doc)
|
||||||
|
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canWrite(group, doc)
|
reachable(group, doc)
|
||||||
} limit 3
|
} limit 3
|
||||||
|
|
||||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||||
@@ -330,6 +331,7 @@ describe('Integration Tests', () => {
|
|||||||
|
|
||||||
fact isMember(user: any, org: any) transitive CACHE lazy limit 5
|
fact isMember(user: any, org: any) transitive CACHE lazy limit 5
|
||||||
fact isParentOf(parent: Organization, child: Organization) transitive CACHE eager limit 3
|
fact isParentOf(parent: Organization, child: Organization) transitive CACHE eager limit 3
|
||||||
|
fact reachable(user: any, doc: any) CACHE lazy
|
||||||
fact hasRole(user: Employee, role: string) CACHE eager
|
fact hasRole(user: Employee, role: string) CACHE eager
|
||||||
fact hasClearance(user: Employee, level: string) CACHE eager
|
fact hasClearance(user: Employee, level: string) CACHE eager
|
||||||
fact isSuspended(user: any) CACHE lazy
|
fact isSuspended(user: any) CACHE lazy
|
||||||
@@ -339,7 +341,7 @@ describe('Integration Tests', () => {
|
|||||||
isMember(user, org)
|
isMember(user, org)
|
||||||
|
|
||||||
isParentOf(org, *parentOrg) {
|
isParentOf(org, *parentOrg) {
|
||||||
canAccessOrg(user, parentOrg)
|
reachable(user, parentOrg)
|
||||||
} limit 3
|
} limit 3
|
||||||
|
|
||||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||||
@@ -347,11 +349,11 @@ describe('Integration Tests', () => {
|
|||||||
|
|
||||||
evidence canAccessResource(user: Employee, resource: Resource) {
|
evidence canAccessResource(user: Employee, resource: Resource) {
|
||||||
isMember(user, *org) {
|
isMember(user, *org) {
|
||||||
canAccessResource(org, resource)
|
reachable(org, resource)
|
||||||
} limit 5
|
} limit 5
|
||||||
|
|
||||||
parentOf(user, *parent) {
|
parentOf(user, *parent) {
|
||||||
canAccessResource(parent, resource)
|
reachable(parent, resource)
|
||||||
} limit 2
|
} limit 2
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
@@ -379,6 +381,7 @@ describe('Integration Tests', () => {
|
|||||||
fact hasInterest(user: any, interest: string) CACHE lazy
|
fact hasInterest(user: any, interest: string) CACHE lazy
|
||||||
fact hasTag(doc: any, tag: string) CACHE lazy
|
fact hasTag(doc: any, tag: string) CACHE lazy
|
||||||
fact owns(user: any, doc: any) CACHE eager
|
fact owns(user: any, doc: any) CACHE eager
|
||||||
|
fact reachable(user: any, doc: any) CACHE lazy
|
||||||
fact similar(a: any, b: any) CACHE lazy
|
fact similar(a: any, b: any) CACHE lazy
|
||||||
fact isPublic(doc: any) CACHE eager
|
fact isPublic(doc: any) CACHE eager
|
||||||
fact hasInterests(user: any) CACHE lazy
|
fact hasInterests(user: any) CACHE lazy
|
||||||
@@ -390,12 +393,12 @@ describe('Integration Tests', () => {
|
|||||||
owns(user, doc)
|
owns(user, doc)
|
||||||
|
|
||||||
similar(doc, *similar) |similarity| {
|
similar(doc, *similar) |similarity| {
|
||||||
canRead(user, similar)
|
reachable(user, similar)
|
||||||
isPublic(similar)
|
isPublic(similar)
|
||||||
} limit 10 with similarity > 0.7
|
} limit 10 with similarity > 0.7
|
||||||
|
|
||||||
isFriend(user, *friend) {
|
isFriend(user, *friend) {
|
||||||
canRead(friend, doc)
|
reachable(friend, doc)
|
||||||
} limit 5
|
} limit 5
|
||||||
|
|
||||||
fusion majority {
|
fusion majority {
|
||||||
@@ -406,7 +409,7 @@ describe('Integration Tests', () => {
|
|||||||
|
|
||||||
evidence canRecommend(user: Employee, doc: Document) {
|
evidence canRecommend(user: Employee, doc: Document) {
|
||||||
similar(user, *similarUser) |similarity| {
|
similar(user, *similarUser) |similarity| {
|
||||||
canRead(similarUser, doc)
|
reachable(similarUser, doc)
|
||||||
} limit 20 with similarity > 0.8
|
} limit 20 with similarity > 0.8
|
||||||
|
|
||||||
fusion average {
|
fusion average {
|
||||||
@@ -556,13 +559,14 @@ describe('Integration Tests', () => {
|
|||||||
fact isFriend(user: any, friend: any) symmetrical CACHE eager limit 50
|
fact isFriend(user: any, friend: any) symmetrical CACHE eager limit 50
|
||||||
fact hasPermission(user: Employee, resource: Resource, action: string) CACHE eager
|
fact hasPermission(user: Employee, resource: Resource, action: string) CACHE eager
|
||||||
fact owns(user: Employee, resource: Resource) CACHE eager
|
fact owns(user: Employee, resource: Resource) CACHE eager
|
||||||
|
fact reachable(user: any, doc: any) CACHE lazy
|
||||||
|
|
||||||
// Optimized evidence rules
|
// Optimized evidence rules
|
||||||
evidence canAccess(user: Employee, resource: Resource) {
|
evidence canAccess(user: Employee, resource: Resource) {
|
||||||
owns(user, resource)
|
owns(user, resource)
|
||||||
|
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canAccess(group, resource)
|
reachable(group, resource)
|
||||||
} limit 3
|
} limit 3
|
||||||
|
|
||||||
WHEN hasPermission(user, resource, 'read')
|
WHEN hasPermission(user, resource, 'read')
|
||||||
@@ -572,7 +576,7 @@ describe('Integration Tests', () => {
|
|||||||
owns(user, resource)
|
owns(user, resource)
|
||||||
|
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canModify(group, resource)
|
reachable(group, resource)
|
||||||
} limit 2
|
} limit 2
|
||||||
|
|
||||||
WHEN hasPermission(user, resource, 'write')
|
WHEN hasPermission(user, resource, 'write')
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ const FACTS = `
|
|||||||
fact can_access(group: Group, doc: Doc)
|
fact can_access(group: Group, doc: Doc)
|
||||||
fact owner(group: Group, doc: Doc)
|
fact owner(group: Group, doc: Doc)
|
||||||
fact granted(user: Employee, doc: Doc)
|
fact granted(user: Employee, doc: Doc)
|
||||||
|
fact group_perm(group: Group, doc: Doc)
|
||||||
fact banned(user: Employee)
|
fact banned(user: Employee)
|
||||||
fact mfa(user: Employee)
|
fact mfa(user: Employee)
|
||||||
`;
|
`;
|
||||||
@@ -106,11 +107,39 @@ function buildProgram(kind, ps) {
|
|||||||
oracle = pG * pM;
|
oracle = pG * pM;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
case 'composition': {
|
||||||
|
// can_via composes the direct evidence can_read, which reads the owns
|
||||||
|
// edge — an evidence-in-evidence reference resolved at compile time.
|
||||||
|
const [pOwn] = ps;
|
||||||
|
evidence = `evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
|
evidence can_via(user: Employee, doc: Doc) { can_read(user, doc) }`;
|
||||||
|
edges.push({ src: 'u:1', relation: 'owns', dst: 'doc:9', possibility: pOwn });
|
||||||
|
oracle = pOwn;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'chain_step_composition': {
|
||||||
|
// group_read (a direct evidence) used as a CHAIN STEP inside can_via:
|
||||||
|
// the step is expanded at compile time to the underlying can_view edge.
|
||||||
|
const [pm, pv] = ps;
|
||||||
|
evidence = `evidence group_read(group: Group, doc: Doc) { group_perm(group, doc) }
|
||||||
|
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { group_read(g, doc) } }`;
|
||||||
|
edges.push({ src: 'u:1', relation: 'member_of', dst: 'g:1', possibility: pm });
|
||||||
|
edges.push({ src: 'g:1', relation: 'group_perm', dst: 'doc:9', possibility: pv });
|
||||||
|
oracle = Math.min(pm, pv);
|
||||||
|
break;
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
throw new Error(`unknown construct: ${kind}`);
|
throw new Error(`unknown construct: ${kind}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return { dsl: FACTS + evidence, edges, oracle, relation: evidence.match(/evidence (\w+)/)[1] };
|
return {
|
||||||
|
dsl: FACTS + evidence,
|
||||||
|
edges,
|
||||||
|
oracle,
|
||||||
|
// Check the LAST evidence declaration: the composition construct declares
|
||||||
|
// two evidences (can_read + can_via), and the composed one is the target.
|
||||||
|
relation: [...evidence.matchAll(/evidence\s+(\w+)/g)].at(-1)[1]
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function runCheck({ kind, ps }) {
|
function runCheck({ kind, ps }) {
|
||||||
@@ -134,7 +163,7 @@ function runCheck({ kind, ps }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const CONSTRUCTS = ['direct', 'chain', 'tuple_to_userset', 'fusion_min', 'fusion_max',
|
const CONSTRUCTS = ['direct', 'chain', 'tuple_to_userset', 'fusion_min', 'fusion_max',
|
||||||
'when_unless', 'never_always', 'requires_when'];
|
'when_unless', 'never_always', 'requires_when', 'composition', 'chain_step_composition'];
|
||||||
|
|
||||||
describe('DSL generative oracle parity (rigor)', () => {
|
describe('DSL generative oracle parity (rigor)', () => {
|
||||||
it('generated legal DSL compiles and every check matches the oracle', async () => {
|
it('generated legal DSL compiles and every check matches the oracle', async () => {
|
||||||
|
|||||||
@@ -81,6 +81,29 @@ const MUTATIONS = {
|
|||||||
desc: 'evidence declared with mismatched parameter arity',
|
desc: 'evidence declared with mismatched parameter arity',
|
||||||
mustFail: true,
|
mustFail: true,
|
||||||
apply: () => VALID_DSL.replace('evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }', 'evidence can_read(user: Employee) { owns(user, doc) }')
|
apply: () => VALID_DSL.replace('evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }', 'evidence can_read(user: Employee) { owns(user, doc) }')
|
||||||
|
},
|
||||||
|
cyclic_evidence_ref: {
|
||||||
|
desc: 'two evidences referencing each other (cycle)',
|
||||||
|
mustFail: true,
|
||||||
|
apply: () => VALID_DSL + `
|
||||||
|
evidence can_cyc_a(user: Employee, doc: Doc) { can_cyc_b(user, doc) }
|
||||||
|
evidence can_cyc_b(user: Employee, doc: Doc) { can_cyc_a(user, doc) }`
|
||||||
|
},
|
||||||
|
cross_kind_collision: {
|
||||||
|
desc: 'fact and evidence sharing a relation name',
|
||||||
|
mustFail: true,
|
||||||
|
apply: () => VALID_DSL.replace(
|
||||||
|
'evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }',
|
||||||
|
'fact can_read(user: Employee, doc: Doc)\n evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }'
|
||||||
|
)
|
||||||
|
},
|
||||||
|
non_lowerable_chain_step: {
|
||||||
|
desc: 'a defeasible evidence used as a chain step (cannot lower to an edge)',
|
||||||
|
mustFail: true,
|
||||||
|
apply: () => VALID_DSL.replace(
|
||||||
|
'evidence can_enter(user: Employee, doc: Doc) { member_of(user, *g) { can_access(g, doc) } }',
|
||||||
|
'evidence can_gated(group: Group, doc: Doc) { WHEN can_access(group, doc) UNLESS banned(group) }\n evidence can_enter(user: Employee, doc: Doc) { member_of(user, *g) { can_gated(g, doc) } }'
|
||||||
|
).replace('fact can_access(group: Group, doc: Doc)', 'fact can_access(group: Group, doc: Doc)\n fact banned(group: Group)')
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user