From 9eebf04306c17b1f27e0cec3ec8fa9364bed3386 Mon Sep 17 00:00:00 2001 From: Clement Delafargue Date: Sat, 21 Nov 2026 22:01:29 +0100 Subject: [PATCH 1/2] carry a monotonous step count in Authorizer - carry the step counter in Authorizer - make it monotonous - check the current step counter against a budget that can be overriden at call sites - make step count `long` to align with the rust implementation and the protobuf representation --- .../eclipse/biscuit/datalog/Combinator.java | 4 +- .../biscuit/datalog/MatchedVariables.java | 2 +- .../org/eclipse/biscuit/datalog/Rule.java | 6 +- .../eclipse/biscuit/datalog/RunLimits.java | 6 +- .../eclipse/biscuit/datalog/StepBudget.java | 19 ++++++ .../eclipse/biscuit/datalog/StepCounter.java | 27 +++----- .../org/eclipse/biscuit/datalog/Term.java | 2 +- .../org/eclipse/biscuit/datalog/World.java | 35 ++++++---- .../datalog/expressions/Expression.java | 4 +- .../biscuit/datalog/expressions/Op.java | 12 ++-- .../org/eclipse/biscuit/token/Authorizer.java | 65 ++++++++++++++----- .../biscuit/builder/parser/ParserTest.java | 6 +- .../biscuit/datalog/ExpressionTest.java | 12 ++-- .../eclipse/biscuit/token/StepLimitTest.java | 55 +++++++++++++++- 14 files changed, 178 insertions(+), 77 deletions(-) create mode 100644 biscuit-core/src/main/java/org/eclipse/biscuit/datalog/StepBudget.java diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Combinator.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Combinator.java index a4c3c6f1..24be6861 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Combinator.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Combinator.java @@ -21,7 +21,7 @@ public final class Combinator implements Iterator>> private final Iterator> currentFacts; private Combinator currentIt; private final SymbolTable symbolTable; - private final StepCounter steps; + private final StepBudget steps; private Origin currentOrigin; private Optional>> nextElement; @@ -163,7 +163,7 @@ public Combinator( final FactSet facts, final TrustedOrigins scope, final SymbolTable symbolTable, - StepCounter steps) { + StepBudget steps) { this.variables = variables; this.facts = facts; this.scope = scope; diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/MatchedVariables.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/MatchedVariables.java index 3c80593b..71ffb5c2 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/MatchedVariables.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/MatchedVariables.java @@ -68,7 +68,7 @@ public MatchedVariables(final Set ids) { } public Optional> checkExpressions( - List expressions, SymbolTable symbolTable, StepCounter steps) throws Error { + List expressions, SymbolTable symbolTable, StepBudget steps) throws Error { final Optional> vars = this.complete(); if (vars.isPresent()) { Map variables = vars.get(); diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Rule.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Rule.java index 95ce8842..7d061187 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Rule.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Rule.java @@ -48,7 +48,7 @@ public Stream, Error>> apply( Long ruleOrigin, TrustedOrigins scope, SymbolTable symbolTable, - StepCounter steps) { + StepBudget steps) { MatchedVariables variables = variablesSet(); Combinator combinator = new Combinator(variables, this.body, facts, scope, symbolTable, steps); @@ -117,7 +117,7 @@ public boolean findMatch( Long origin, TrustedOrigins scope, SymbolTable symbolTable, - StepCounter steps) + StepBudget steps) throws Error { MatchedVariables variables = variablesSet(); @@ -146,7 +146,7 @@ public boolean findMatch( // verifies that the expressions return true for every matching set of facts public boolean checkMatchAll( - final FactSet facts, TrustedOrigins scope, SymbolTable symbolTable, StepCounter steps) + final FactSet facts, TrustedOrigins scope, SymbolTable symbolTable, StepBudget steps) throws Error { MatchedVariables variables = variablesSet(); diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/RunLimits.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/RunLimits.java index f2514bfc..45ee3950 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/RunLimits.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/RunLimits.java @@ -11,7 +11,7 @@ public final class RunLimits { private int maxFacts = 1000; private int maxIterations = 100; private Duration maxTime = Duration.ofMillis(5); - private int maxSteps = 1000; + private long maxSteps = 1000; public RunLimits() {} @@ -19,7 +19,7 @@ public RunLimits(int maxFacts, int maxIterations, Duration maxTime) { this(maxFacts, maxIterations, maxTime, 1000); } - public RunLimits(int maxFacts, int maxIterations, Duration maxTime, int maxSteps) { + public RunLimits(int maxFacts, int maxIterations, Duration maxTime, long maxSteps) { this.maxFacts = maxFacts; this.maxIterations = maxIterations; this.maxTime = maxTime; @@ -38,7 +38,7 @@ public Duration getMaxTime() { return this.maxTime; } - public int getMaxSteps() { + public long getMaxSteps() { return this.maxSteps; } } diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/StepBudget.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/StepBudget.java new file mode 100644 index 00000000..653316b4 --- /dev/null +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/StepBudget.java @@ -0,0 +1,19 @@ +package org.eclipse.biscuit.datalog; + +public final class StepBudget { + private final StepCounter counter; + private final long maxSteps; + + StepBudget(StepCounter counter, long maxSteps) { + this.counter = counter; + this.maxSteps = maxSteps; + } + + public boolean step() { + return ++counter.count <= maxSteps; + } + + public boolean exceeded() { + return counter.count > maxSteps; + } +} diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/StepCounter.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/StepCounter.java index fc07f368..4aeb3865 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/StepCounter.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/StepCounter.java @@ -1,28 +1,21 @@ package org.eclipse.biscuit.datalog; -public class StepCounter implements Cloneable { - private int counter; - private final int maxSteps; +public final class StepCounter { + long count; - public StepCounter(int maxSteps) { - this.maxSteps = maxSteps; - this.counter = 0; + public StepCounter() { + this(0); } - public boolean step() { - return ++counter <= maxSteps; + public StepCounter(long taken) { + this.count = taken; } - public boolean exceeded() { - return counter > maxSteps; + public long taken() { + return this.count; } - @Override - public StepCounter clone() { - try { - return (StepCounter) super.clone(); - } catch (CloneNotSupportedException e) { - throw new AssertionError(); - } + public StepBudget budget(long maxSteps) { + return new StepBudget(this, maxSteps); } } diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Term.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Term.java index 5d2e3188..a23fbd4f 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Term.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Term.java @@ -38,7 +38,7 @@ public void evaluate( Deque stack, java.util.Map variables, TemporarySymbolTable temporarySymbolTable, - StepCounter steps) + StepBudget steps) throws Error.Execution { if (this instanceof Term.Variable) { Term.Variable var = (Term.Variable) this; diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/World.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/World.java index 2d94777f..21144e3a 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/World.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/World.java @@ -14,7 +14,6 @@ public final class World { private final FactSet facts; private final RuleSet rules; - private StepCounter steps; public void addFact(final Origin origin, final Fact fact) { this.facts.add(origin, fact); @@ -33,9 +32,12 @@ public void run(final SymbolTable symbolTable) throws Error { } public void run(RunLimits limits, final SymbolTable symbolTable) throws Error { + this.run(limits, new StepCounter().budget(limits.getMaxSteps()), symbolTable); + } + + public void run(RunLimits limits, StepBudget steps, final SymbolTable symbolTable) throws Error { int iterations = 0; Instant limit = Instant.now().plus(limits.getMaxTime()); - this.steps = new StepCounter(limits.getMaxSteps()); while (true) { final FactSet newFacts = new FactSet(); @@ -43,7 +45,7 @@ public void run(RunLimits limits, final SymbolTable symbolTable) throws Error { for (Map.Entry>> entry : this.rules.getRules().entrySet()) { for (Pair t : entry.getValue()) { - var stream = t._2.apply(this.facts, t._1, entry.getKey(), symbolTable, this.steps); + var stream = t._2.apply(this.facts, t._1, entry.getKey(), symbolTable, steps); for (var it = stream.iterator(); it.hasNext(); ) { var res = it.next(); if (Instant.now().compareTo(limit) >= 0) { @@ -60,7 +62,7 @@ public void run(RunLimits limits, final SymbolTable symbolTable) throws Error { } } - if (this.steps.exceeded()) throw new Error.TooManySteps(); + if (steps.exceeded()) throw new Error.TooManySteps(); final int len = this.facts.size(); this.facts.merge(newFacts); @@ -90,9 +92,16 @@ public RuleSet getRules() { public FactSet queryRule( final Rule rule, Long origin, TrustedOrigins scope, SymbolTable symbolTable) throws Error { + return this.queryRule( + rule, origin, scope, symbolTable, new StepCounter().budget(new RunLimits().getMaxSteps())); + } + + public FactSet queryRule( + final Rule rule, Long origin, TrustedOrigins scope, SymbolTable symbolTable, StepBudget steps) + throws Error { final FactSet newFacts = new FactSet(); - var stream = rule.apply(this.facts, origin, scope, symbolTable, this.steps); + var stream = rule.apply(this.facts, origin, scope, symbolTable, steps); for (var it = stream.iterator(); it.hasNext(); ) { var res = it.next(); @@ -104,43 +113,41 @@ public FactSet queryRule( } } - if (this.steps.exceeded()) throw new Error.TooManySteps(); + if (steps.exceeded()) throw new Error.TooManySteps(); return newFacts; } public boolean queryMatch( - final Rule rule, Long origin, TrustedOrigins scope, SymbolTable symbolTable) throws Error { - return rule.findMatch(this.facts, origin, scope, symbolTable, this.steps); + final Rule rule, Long origin, TrustedOrigins scope, SymbolTable symbolTable, StepBudget steps) + throws Error { + return rule.findMatch(this.facts, origin, scope, symbolTable, steps); } - public boolean queryMatchAll(final Rule rule, TrustedOrigins scope, SymbolTable symbolTable) + public boolean queryMatchAll( + final Rule rule, TrustedOrigins scope, SymbolTable symbolTable, StepBudget steps) throws Error { - return rule.checkMatchAll(this.facts, scope, symbolTable, this.steps); + return rule.checkMatchAll(this.facts, scope, symbolTable, steps); } public World() { this.facts = new FactSet(); this.rules = new RuleSet(); - this.steps = new StepCounter(new RunLimits().getMaxSteps()); } public World(FactSet facts) { this.facts = facts.clone(); this.rules = new RuleSet(); - this.steps = new StepCounter(new RunLimits().getMaxSteps()); } public World(FactSet facts, RuleSet rules) { this.facts = facts.clone(); this.rules = rules.clone(); - this.steps = new StepCounter(new RunLimits().getMaxSteps()); } public World(World w) { this.facts = w.facts.clone(); this.rules = w.rules.clone(); - this.steps = w.steps.clone(); } public String print(SymbolTable symbolTable) { diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/expressions/Expression.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/expressions/Expression.java index 5f8efd11..34b92d93 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/expressions/Expression.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/expressions/Expression.java @@ -12,7 +12,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; -import org.eclipse.biscuit.datalog.StepCounter; +import org.eclipse.biscuit.datalog.StepBudget; import org.eclipse.biscuit.datalog.SymbolTable; import org.eclipse.biscuit.datalog.TemporarySymbolTable; import org.eclipse.biscuit.datalog.Term; @@ -32,7 +32,7 @@ public ArrayList getOps() { // FIXME: should return a Result public Term evaluate( - Map variables, TemporarySymbolTable temporarySymbolTable, StepCounter steps) + Map variables, TemporarySymbolTable temporarySymbolTable, StepBudget steps) throws Error { Deque stack = new ArrayDeque(16); // Default value for (Op op : ops) { diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/expressions/Op.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/expressions/Op.java index 0180c4cc..f9214fb8 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/expressions/Op.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/expressions/Op.java @@ -28,7 +28,7 @@ public abstract void evaluate( Deque stack, Map variables, TemporarySymbolTable temporarySymbolTable, - StepCounter steps) + StepBudget steps) throws Error; public abstract String print(Deque stack, SymbolTable symbols); @@ -73,7 +73,7 @@ public void evaluate( Deque stack, Map variables, TemporarySymbolTable temporarySymbolTable, - StepCounter steps) + StepBudget steps) throws Error { if (!steps.step()) throw new Error.TooManySteps(); @@ -261,7 +261,7 @@ public void evaluate( Deque stack, Map variables, TemporarySymbolTable temporarySymbolTable, - StepCounter steps) + StepBudget steps) throws Error { if (!steps.step()) throw new Error.TooManySteps(); @@ -1080,7 +1080,7 @@ public void evaluate( Deque stack, Map variables, TemporarySymbolTable temporarySymbolTable, - StepCounter steps) + StepBudget steps) throws Error { stack.push(this); } @@ -1090,7 +1090,7 @@ int arity() { } Term call( - Map variables, TemporarySymbolTable temporarySymbolTable, StepCounter steps) + Map variables, TemporarySymbolTable temporarySymbolTable, StepBudget steps) throws Error { if (!steps.step()) throw new Error.TooManySteps(); @@ -1111,7 +1111,7 @@ Term call( Term arg, Map variables, TemporarySymbolTable temporarySymbolTable, - StepCounter steps) + StepBudget steps) throws Error { if (!steps.step()) { throw new Error.TooManySteps(); diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/token/Authorizer.java b/biscuit-core/src/main/java/org/eclipse/biscuit/token/Authorizer.java index 70fcf911..c588363d 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/token/Authorizer.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/token/Authorizer.java @@ -41,11 +41,13 @@ public final class Authorizer { private final HashMap> publicKeyToBlockId; private final World world; private final SymbolTable symbolTable; + private final StepCounter steps; private Authorizer(Biscuit token, World w) throws Error.FailedLogic { this.token = token; this.world = w; this.symbolTable = new SymbolTable(this.token.symbolTable); + this.steps = new StepCounter(); this.checks = new ArrayList<>(); this.policies = new ArrayList<>(); this.scopes = new ArrayList<>(); @@ -62,6 +64,7 @@ private Authorizer(Biscuit token, World w) throws Error.FailedLogic { public Authorizer() { this.world = new World(); this.symbolTable = Biscuit.defaultSymbolTable(); + this.steps = new StepCounter(); this.checks = new ArrayList<>(); this.policies = new ArrayList<>(); this.scopes = new ArrayList<>(); @@ -73,12 +76,14 @@ private Authorizer( List checks, List policies, World world, - SymbolTable symbolTable) { + SymbolTable symbolTable, + StepCounter steps) { this.token = token; this.checks = checks; this.policies = policies; this.world = world; this.symbolTable = symbolTable; + this.steps = steps; this.scopes = new ArrayList<>(); this.publicKeyToBlockId = new HashMap<>(); } @@ -101,7 +106,8 @@ public Authorizer clone() { new ArrayList<>(this.checks), new ArrayList<>(this.policies), new World(this.world), - new SymbolTable(this.symbolTable)); + new SymbolTable(this.symbolTable), + new StepCounter(this.steps.taken())); } public void updateOnToken() throws Error.FailedLogic { @@ -369,7 +375,8 @@ public Authorizer addScope(Scope s) { } public Set query(Rule query) throws Error { - return this.query(query, new RunLimits()); + RunLimits limits = new RunLimits(); + return this.query(query, limits, Math.max(this.steps.taken(), limits.getMaxSteps())); } public Set query(String s) throws Error { @@ -381,7 +388,12 @@ public Set query(String s) throws Error } public Set query(Rule query, RunLimits limits) throws Error { - world.run(limits, symbolTable); + return this.query(query, limits, this.maxSteps(limits)); + } + + private Set query(Rule query, RunLimits limits, long maxSteps) throws Error { + StepBudget budget = this.steps.budget(maxSteps); + world.run(limits, budget, symbolTable); org.eclipse.biscuit.datalog.Rule rule = query.convert(symbolTable); TrustedOrigins ruleTrustedorigins = @@ -391,7 +403,7 @@ public Set query(Rule query, RunLimits limits) throws Error { Long.MAX_VALUE, this.publicKeyToBlockId); - FactSet facts = world.queryRule(rule, Long.MAX_VALUE, ruleTrustedorigins, symbolTable); + FactSet facts = world.queryRule(rule, Long.MAX_VALUE, ruleTrustedorigins, symbolTable, budget); Set s = new HashSet<>(); for (Iterator it = facts.stream().iterator(); @@ -413,16 +425,28 @@ public Set query(String s, RunLimits lim } public Long authorize() throws Error { - return this.authorize(new RunLimits()); + RunLimits limits = new RunLimits(); + return this.authorize(limits, Math.max(this.steps.taken(), limits.getMaxSteps())); } public Long authorize(RunLimits limits) throws Error { + return this.authorize(limits, this.maxSteps(limits)); + } + + private long maxSteps(RunLimits limits) { + long taken = this.steps.taken(); + long maxSteps = limits.getMaxSteps(); + return maxSteps > Long.MAX_VALUE - taken ? Long.MAX_VALUE : taken + maxSteps; + } + + private Long authorize(RunLimits limits, long maxSteps) throws Error { + StepBudget budget = this.steps.budget(maxSteps); Instant timeLimit = Instant.now().plus(limits.getMaxTime()); List errors = new LinkedList<>(); TrustedOrigins authorizerTrustedOrigins = this.authorizerTrustedOrigins(); - world.run(limits, symbolTable); + world.run(limits, budget, symbolTable); for (int i = 0; i < this.checks.size(); i++) { org.eclipse.biscuit.datalog.Check c = this.checks.get(i).convert(symbolTable); @@ -434,13 +458,15 @@ public Long authorize(RunLimits limits) throws Error { query.scopes(), authorizerTrustedOrigins, Long.MAX_VALUE, this.publicKeyToBlockId); switch (c.kind()) { case ONE: - successful = world.queryMatch(query, Long.MAX_VALUE, ruleTrustedOrigins, symbolTable); + successful = + world.queryMatch(query, Long.MAX_VALUE, ruleTrustedOrigins, symbolTable, budget); break; case ALL: - successful = world.queryMatchAll(query, ruleTrustedOrigins, symbolTable); + successful = world.queryMatchAll(query, ruleTrustedOrigins, symbolTable, budget); break; case REJECT: - successful = world.queryMatch(query, Long.MAX_VALUE, ruleTrustedOrigins, symbolTable); + successful = + world.queryMatch(query, Long.MAX_VALUE, ruleTrustedOrigins, symbolTable, budget); break; default: throw new RuntimeException("unmapped kind"); @@ -481,13 +507,15 @@ public Long authorize(RunLimits limits) throws Error { query.scopes(), authorityTrustedOrigins, 0, this.publicKeyToBlockId); switch (check.kind()) { case ONE: - successful = world.queryMatch(query, (long) 0, ruleTrustedOrigins, symbolTable); + successful = + world.queryMatch(query, (long) 0, ruleTrustedOrigins, symbolTable, budget); break; case ALL: - successful = world.queryMatchAll(query, ruleTrustedOrigins, symbolTable); + successful = world.queryMatchAll(query, ruleTrustedOrigins, symbolTable, budget); break; case REJECT: - successful = world.queryMatch(query, (long) 0, ruleTrustedOrigins, symbolTable); + successful = + world.queryMatch(query, (long) 0, ruleTrustedOrigins, symbolTable, budget); break; default: throw new RuntimeException("unmapped kind"); @@ -518,7 +546,8 @@ public Long authorize(RunLimits limits) throws Error { TrustedOrigins policyTrustedOrigins = TrustedOrigins.fromScopes( query.scopes(), authorizerTrustedOrigins, Long.MAX_VALUE, this.publicKeyToBlockId); - boolean res = world.queryMatch(query, Long.MAX_VALUE, policyTrustedOrigins, symbolTable); + boolean res = + world.queryMatch(query, Long.MAX_VALUE, policyTrustedOrigins, symbolTable, budget); if (Instant.now().compareTo(timeLimit) >= 0) { throw new Error.Timeout(); @@ -562,13 +591,15 @@ public Long authorize(RunLimits limits) throws Error { query.scopes(), blockTrustedOrigins, i + 1, this.publicKeyToBlockId); switch (check.kind()) { case ONE: - successful = world.queryMatch(query, (long) i + 1, ruleTrustedOrigins, symbolTable); + successful = + world.queryMatch(query, (long) i + 1, ruleTrustedOrigins, symbolTable, budget); break; case ALL: - successful = world.queryMatchAll(query, ruleTrustedOrigins, symbolTable); + successful = world.queryMatchAll(query, ruleTrustedOrigins, symbolTable, budget); break; case REJECT: - successful = world.queryMatch(query, (long) i + 1, ruleTrustedOrigins, symbolTable); + successful = + world.queryMatch(query, (long) i + 1, ruleTrustedOrigins, symbolTable, budget); break; default: throw new RuntimeException("unmapped kind"); diff --git a/biscuit/src/test/java/org/eclipse/biscuit/builder/parser/ParserTest.java b/biscuit/src/test/java/org/eclipse/biscuit/builder/parser/ParserTest.java index f8a04949..1a97aec6 100644 --- a/biscuit/src/test/java/org/eclipse/biscuit/builder/parser/ParserTest.java +++ b/biscuit/src/test/java/org/eclipse/biscuit/builder/parser/ParserTest.java @@ -383,7 +383,9 @@ void testParens() throws org.eclipse.biscuit.error.Error { Map variables = new HashMap<>(); org.eclipse.biscuit.datalog.Term value = ex.evaluate( - variables, new TemporarySymbolTable(s), new StepCounter(new RunLimits().getMaxSteps())); + variables, + new TemporarySymbolTable(s), + new StepCounter().budget(new RunLimits().getMaxSteps())); assertEquals(new org.eclipse.biscuit.datalog.Term.Integer(7), value); assertEquals("1 + 2 * 3", ex.print(s).get()); @@ -422,7 +424,7 @@ void testParens() throws org.eclipse.biscuit.error.Error { ex2.evaluate( variables2, new TemporarySymbolTable(s2), - new StepCounter(new RunLimits().getMaxSteps())); + new StepCounter().budget(new RunLimits().getMaxSteps())); assertEquals(new org.eclipse.biscuit.datalog.Term.Integer(9), value2); assertEquals("(1 + 2) * 3", ex2.print(s2).get()); } diff --git a/biscuit/src/test/java/org/eclipse/biscuit/datalog/ExpressionTest.java b/biscuit/src/test/java/org/eclipse/biscuit/datalog/ExpressionTest.java index e2a9eac7..b3f00b5a 100644 --- a/biscuit/src/test/java/org/eclipse/biscuit/datalog/ExpressionTest.java +++ b/biscuit/src/test/java/org/eclipse/biscuit/datalog/ExpressionTest.java @@ -45,7 +45,7 @@ public void testNegate() throws Error { e.evaluate( variables, new TemporarySymbolTable(symbolTable), - new StepCounter(new RunLimits().getMaxSteps()))); + new StepCounter().budget(new RunLimits().getMaxSteps()))); } @Test @@ -70,7 +70,7 @@ public void testAddsStr() throws Error { e.evaluate( new HashMap<>(), new TemporarySymbolTable(symbolTable), - new StepCounter(new RunLimits().getMaxSteps()))); + new StepCounter().budget(new RunLimits().getMaxSteps()))); } @Test @@ -94,7 +94,7 @@ public void testContainsStr() throws Error { e.evaluate( new HashMap<>(), new TemporarySymbolTable(symbolTable), - new StepCounter(new RunLimits().getMaxSteps()))); + new StepCounter().budget(new RunLimits().getMaxSteps()))); } @Test @@ -119,7 +119,7 @@ public void testNegativeContainsStr() throws Error { e.evaluate( new HashMap<>(), new TemporarySymbolTable(symbolTable), - new StepCounter(new RunLimits().getMaxSteps()))); + new StepCounter().budget(new RunLimits().getMaxSteps()))); } @Test @@ -147,7 +147,7 @@ public void testIntersectionAndContains() throws Error { e.evaluate( new HashMap<>(), new TemporarySymbolTable(symbolTable), - new StepCounter(new RunLimits().getMaxSteps()))); + new StepCounter().budget(new RunLimits().getMaxSteps()))); } private static Term evaluate(Op... ops) throws Error { @@ -155,7 +155,7 @@ private static Term evaluate(Op... ops) throws Error { .evaluate( new HashMap<>(), new TemporarySymbolTable(new SymbolTable()), - new StepCounter(new RunLimits().getMaxSteps())); + new StepCounter().budget(new RunLimits().getMaxSteps())); } private static Op.Closure closure(Op... ops) { diff --git a/biscuit/src/test/java/org/eclipse/biscuit/token/StepLimitTest.java b/biscuit/src/test/java/org/eclipse/biscuit/token/StepLimitTest.java index 7461743e..0c6f5914 100644 --- a/biscuit/src/test/java/org/eclipse/biscuit/token/StepLimitTest.java +++ b/biscuit/src/test/java/org/eclipse/biscuit/token/StepLimitTest.java @@ -33,7 +33,7 @@ public class StepLimitTest { private SecureRandom rng; /** Limits where only maxSteps can realistically trip. */ - private static RunLimits steps(int maxSteps) { + private static RunLimits steps(long maxSteps) { return new RunLimits(1_000_000, 1_000_000, Duration.ofDays(1), maxSteps); } @@ -168,9 +168,10 @@ public void stepLimitDoesNotHideTooManyFacts() throws Exception { } @Test - public void counterIsResetBetweenAuthorizations() throws Exception { + public void explicitLimitsGiveEachAuthorizationAFullBudget() throws Exception { // First run costs 16 steps (8 facts, two passes). The second run finds nothing new, so one - // pass of 8 steps. 16 + 8 would not fit in 20, so this only passes if the counter is reset. + // pass of 8 steps. 16 + 8 would not fit in 20, so this only passes if the second call gets + // 20 steps on top of the ones already taken. KeyPair keyPair = KeyPair.generate(Schema.PublicKey.Algorithm.Ed25519, rng); var block = Biscuit.builder(keyPair); for (int i = 0; i < 8; i++) { @@ -185,6 +186,54 @@ public void counterIsResetBetweenAuthorizations() throws Exception { assertDoesNotThrow(() -> authorizer.authorize(steps(20))); } + @Test + public void defaultLimitsCountTheStepsAlreadyTaken() throws Exception { + // The first run takes 1000 steps (500 facts, two passes), which leaves none of the default + // 1000 steps for the second one. It fails on its first step, well before the default timeout. + Authorizer authorizer = defaultBudgetTaken(); + + assertDoesNotThrow(() -> authorizer.authorize(steps(1000))); + assertThrows(Error.TooManySteps.class, () -> authorizer.authorize()); + } + + @Test + public void queryWithDefaultLimitsCountsTheStepsTakenByAuthorize() throws Exception { + Authorizer authorizer = defaultBudgetTaken(); + + assertDoesNotThrow(() -> authorizer.authorize(steps(1000))); + assertThrows(Error.TooManySteps.class, () -> authorizer.query("q($0) <- b($0)")); + } + + @Test + public void clonedAuthorizerKeepsTheStepsTaken() throws Exception { + Authorizer authorizer = defaultBudgetTaken(); + + assertDoesNotThrow(() -> authorizer.authorize(steps(1000))); + Authorizer cloned = authorizer.clone(); + assertThrows(Error.TooManySteps.class, () -> cloned.authorize()); + } + + @Test + public void maximumBudgetDoesNotOverflowAfterStepsWereTaken() throws Exception { + Authorizer authorizer = defaultBudgetTaken(); + + assertDoesNotThrow(() -> authorizer.authorize(steps(Long.MAX_VALUE))); + assertDoesNotThrow(() -> authorizer.authorize(steps(Long.MAX_VALUE))); + } + + private Authorizer defaultBudgetTaken() throws Exception { + KeyPair keyPair = KeyPair.generate(Schema.PublicKey.Algorithm.Ed25519, rng); + var block = Biscuit.builder(keyPair); + for (int i = 0; i < 500; i++) { + block.addAuthorityFact("f(" + i + ")"); + } + block.addAuthorityRule("b($0) <- f($0)"); + + Authorizer authorizer = block.build().authorizer(); + authorizer.addPolicy("allow if true"); + return authorizer; + } + // --------------------------------------------------------------------------------------------- // Expression evaluation // --------------------------------------------------------------------------------------------- From 343a8b8bf34d8ecf414d84f77a45169f8fd087ce Mon Sep 17 00:00:00 2001 From: Clement Delafargue Date: Sat, 21 Nov 2026 22:09:03 +0100 Subject: [PATCH 2/2] make `StepBudget.step()` throw and `Combinator` yield `Result<>` This removes the need for explicitly checking `StepBudget.exceeded()` --- .../eclipse/biscuit/datalog/Combinator.java | 34 ++++++++++++------- .../org/eclipse/biscuit/datalog/Rule.java | 25 ++++++++------ .../eclipse/biscuit/datalog/StepBudget.java | 12 +++---- .../org/eclipse/biscuit/datalog/World.java | 4 --- .../biscuit/datalog/expressions/Op.java | 10 +++--- 5 files changed, 45 insertions(+), 40 deletions(-) diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Combinator.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Combinator.java index 24be6861..9c360540 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Combinator.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Combinator.java @@ -12,8 +12,10 @@ import java.util.NoSuchElementException; import java.util.Optional; import java.util.Set; +import org.eclipse.biscuit.error.Error; +import org.eclipse.biscuit.error.Result; -public final class Combinator implements Iterator>> { +public final class Combinator implements Iterator>, Error>> { private MatchedVariables variables; private final List predicates; private final FactSet facts; @@ -24,7 +26,7 @@ public final class Combinator implements Iterator>> private final StepBudget steps; private Origin currentOrigin; - private Optional>> nextElement; + private Optional>, Error>> nextElement; @Override public boolean hasNext() { @@ -36,22 +38,20 @@ public boolean hasNext() { } @Override - public Pair> next() { + public Result>, Error> next() { if (this.nextElement == null || this.nextElement.isEmpty()) { this.nextElement = getNext(); } if (this.nextElement == null || this.nextElement.isEmpty()) { throw new NoSuchElementException(); } else { - Pair> t = this.nextElement.get(); + Result>, Error> t = this.nextElement.get(); this.nextElement = Optional.empty(); return t; } } - public Optional>> getNext() { - if (steps.exceeded()) return Optional.empty(); - + public Optional>, Error>> getNext() { if (this.predicates.isEmpty()) { final Optional> vOpt = this.variables.complete(); if (vOpt.isEmpty()) { @@ -66,7 +66,7 @@ public Optional>> getNext() { set.add((long) 0); this.variables = new MatchedVariables(set); - return Optional.of(new Pair<>(new Origin(), variables)); + return Optional.of(Result.ok(new Pair<>(new Origin(), variables))); } } @@ -77,7 +77,11 @@ public Optional>> getNext() { while (true) { // we iterate over the facts that match the current predicate if (this.currentFacts.hasNext()) { - if (!this.steps.step()) return Optional.empty(); + try { + this.steps.step(); + } catch (Error.TooManySteps e) { + return Optional.of(Result.err(e)); + } final Pair t = this.currentFacts.next(); Origin currentOrigin = t._1.clone(); @@ -121,7 +125,7 @@ public Optional>> getNext() { if (vOpt.isEmpty()) { continue; } else { - return Optional.of(new Pair<>(currentOrigin, vOpt.get())); + return Optional.of(Result.ok(new Pair<>(currentOrigin, vOpt.get()))); } } else { this.currentOrigin = currentOrigin; @@ -145,11 +149,15 @@ public Optional>> getNext() { } } - Optional>> opt = this.currentIt.getNext(); + Optional>, Error>> opt = this.currentIt.getNext(); if (opt.isPresent()) { - Pair> t = opt.get(); - return Optional.of(new Pair<>(t._1.union(currentOrigin), t._2)); + Result>, Error> res = opt.get(); + if (res.isErr()) { + return opt; + } + Pair> t = res.getOk(); + return Optional.of(Result.ok(new Pair<>(t._1.union(currentOrigin), t._2))); } else { currentOrigin = null; currentIt = null; diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Rule.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Rule.java index 7d061187..de826b81 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Rule.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Rule.java @@ -53,12 +53,17 @@ public Stream, Error>> apply( Combinator combinator = new Combinator(variables, this.body, facts, scope, symbolTable, steps); - Spliterator>> splitItr = + Spliterator>, Error>> splitItr = Spliterators.spliteratorUnknownSize(combinator, Spliterator.ORDERED); - Stream>> stream = StreamSupport.stream(splitItr, false); + Stream>, Error>> stream = + StreamSupport.stream(splitItr, false); return stream.flatMap( - t -> { + res -> { + if (res.isErr()) { + return Stream.of(Result.err(res.getErr())); + } + Pair> t = res.getOk(); Origin origin = t._1; Map generatedVariables = t._2; TemporarySymbolTable temporarySymbols = new TemporarySymbolTable(symbolTable); @@ -128,11 +133,7 @@ public boolean findMatch( var stream = this.apply(facts, origin, scope, symbolTable, steps); var it = stream.iterator(); - boolean res = it.hasNext(); - - if (steps.exceeded()) throw new Error.TooManySteps(); - - if (!res) { + if (!it.hasNext()) { return false; } @@ -159,7 +160,11 @@ public boolean checkMatchAll( boolean found = false; for (Combinator it = combinator; it.hasNext(); ) { - Pair> t = it.next(); + Result>, Error> res = it.next(); + if (res.isErr()) { + throw res.getErr(); + } + Pair> t = res.getOk(); Map generatedVariables = t._2; found = true; @@ -179,8 +184,6 @@ public boolean checkMatchAll( } } - if (steps.exceeded()) throw new Error.TooManySteps(); - return found; } diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/StepBudget.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/StepBudget.java index 653316b4..b6c86385 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/StepBudget.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/StepBudget.java @@ -1,5 +1,7 @@ package org.eclipse.biscuit.datalog; +import org.eclipse.biscuit.error.Error; + public final class StepBudget { private final StepCounter counter; private final long maxSteps; @@ -9,11 +11,9 @@ public final class StepBudget { this.maxSteps = maxSteps; } - public boolean step() { - return ++counter.count <= maxSteps; - } - - public boolean exceeded() { - return counter.count > maxSteps; + public void step() throws Error.TooManySteps { + if (++counter.count > maxSteps) { + throw new Error.TooManySteps(); + } } } diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/World.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/World.java index 21144e3a..c3610f8b 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/World.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/World.java @@ -62,8 +62,6 @@ public void run(RunLimits limits, StepBudget steps, final SymbolTable symbolTabl } } - if (steps.exceeded()) throw new Error.TooManySteps(); - final int len = this.facts.size(); this.facts.merge(newFacts); @@ -113,8 +111,6 @@ public FactSet queryRule( } } - if (steps.exceeded()) throw new Error.TooManySteps(); - return newFacts; } diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/expressions/Op.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/expressions/Op.java index f9214fb8..9a83116f 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/expressions/Op.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/expressions/Op.java @@ -75,7 +75,7 @@ public void evaluate( TemporarySymbolTable temporarySymbolTable, StepBudget steps) throws Error { - if (!steps.step()) throw new Error.TooManySteps(); + steps.step(); Op value = stack.pop(); switch (this.op) { @@ -263,7 +263,7 @@ public void evaluate( TemporarySymbolTable temporarySymbolTable, StepBudget steps) throws Error { - if (!steps.step()) throw new Error.TooManySteps(); + steps.step(); Op right = stack.pop(); Op left = stack.pop(); @@ -1092,7 +1092,7 @@ int arity() { Term call( Map variables, TemporarySymbolTable temporarySymbolTable, StepBudget steps) throws Error { - if (!steps.step()) throw new Error.TooManySteps(); + steps.step(); if (arity() != 0) { throw new Error.Execution("called closure with arity " + arity() + "with no arguments"); @@ -1113,9 +1113,7 @@ Term call( TemporarySymbolTable temporarySymbolTable, StepBudget steps) throws Error { - if (!steps.step()) { - throw new Error.TooManySteps(); - } + steps.step(); if (arity() != 1) { throw new Error.Execution("called closure with arity " + arity() + "with 1 argument");