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 c3610f8b..050e3549 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,6 +14,7 @@ public final class World { private final FactSet facts; private final RuleSet rules; + private int iterations; public void addFact(final Origin origin, final Fact fact) { this.facts.add(origin, fact); @@ -66,6 +67,7 @@ public void run(RunLimits limits, StepBudget steps, final SymbolTable symbolTabl this.facts.merge(newFacts); if (this.facts.size() == len) { + this.iterations += iterations; return; } @@ -84,6 +86,10 @@ public FactSet getFacts() { return this.facts; } + public int iterations() { + return this.iterations; + } + public RuleSet getRules() { return this.rules; } @@ -144,6 +150,7 @@ public World(FactSet facts, RuleSet rules) { public World(World w) { this.facts = w.facts.clone(); this.rules = w.rules.clone(); + this.iterations = w.iterations; } public String print(SymbolTable symbolTable) { 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 c588363d..5259be15 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 @@ -7,9 +7,9 @@ import static org.eclipse.biscuit.datalog.Check.Kind.REJECT; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; -import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -25,6 +25,7 @@ import org.eclipse.biscuit.error.FailedCheck; import org.eclipse.biscuit.error.LogicError; import org.eclipse.biscuit.error.Result; +import org.eclipse.biscuit.token.builder.AuthorizerBuilder; import org.eclipse.biscuit.token.builder.Check; import org.eclipse.biscuit.token.builder.Fact; import org.eclipse.biscuit.token.builder.Rule; @@ -34,7 +35,7 @@ /** Token verification class */ public final class Authorizer { - private Biscuit token; + private final Biscuit token; private final List checks; private final List policies; private final List scopes; @@ -42,75 +43,92 @@ public final class Authorizer { 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<>(); - this.publicKeyToBlockId = new HashMap<>(); - updateOnToken(); - } - - /** - * Creates an empty authorizer - * - *

used to apply policies when unauthenticated (no token) and to preload an authorizer that is - * cloned for each new request - */ - 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<>(); - this.publicKeyToBlockId = new HashMap<>(); - } + private final RunLimits limits; + private Duration executionTime; private Authorizer( Biscuit token, List checks, List policies, + List scopes, + HashMap> publicKeyToBlockId, World world, SymbolTable symbolTable, - StepCounter steps) { + StepCounter steps, + RunLimits limits, + Duration executionTime) { this.token = token; this.checks = checks; this.policies = policies; + this.scopes = scopes; + this.publicKeyToBlockId = publicKeyToBlockId; this.world = world; this.symbolTable = symbolTable; this.steps = steps; - this.scopes = new ArrayList<>(); - this.publicKeyToBlockId = new HashMap<>(); + this.limits = limits; + this.executionTime = executionTime; } /** - * Creates a authorizer for a token - * - *

also checks that the token is valid for this root public key + * Creates an authorizer from the contents of a builder, for a token or without one * - * @param token - * @return Authorizer + *

the Datalog evaluation is not run here, but on the first call to {@code authorize} or + * {@code query} */ - public static Authorizer make(Biscuit token) throws Error.FailedLogic { - return new Authorizer(token, new World()); + public static Authorizer make(AuthorizerBuilder builder, Biscuit token) throws Error.FailedLogic { + SymbolTable symbolTable = + token != null ? new SymbolTable(token.symbolTable) : Biscuit.defaultSymbolTable(); + Authorizer authorizer = + new Authorizer( + token, + new ArrayList<>(builder.checks()), + new ArrayList<>(builder.policies()), + new ArrayList<>(), + new HashMap<>(), + new World(), + symbolTable, + new StepCounter(), + builder.limits(), + null); + authorizer.loadToken(); + + for (org.eclipse.biscuit.token.builder.Scope scope : builder.scopes()) { + authorizer.scopes.add(scope.convert(symbolTable)); + } + for (Fact fact : builder.facts()) { + authorizer.world.addFact(Origin.authorizer(), fact.convert(symbolTable)); + } + TrustedOrigins authorizerTrustedOrigins = authorizer.authorizerTrustedOrigins(); + for (Rule rule : builder.rules()) { + org.eclipse.biscuit.datalog.Rule r = rule.convert(symbolTable); + TrustedOrigins ruleTrustedOrigins = + TrustedOrigins.fromScopes( + r.scopes(), authorizerTrustedOrigins, Long.MAX_VALUE, authorizer.publicKeyToBlockId); + authorizer.world.addRule(Long.MAX_VALUE, ruleTrustedOrigins, r); + } + + return authorizer; } public Authorizer clone() { + HashMap> publicKeyToBlockId = new HashMap<>(); + for (Map.Entry> entry : this.publicKeyToBlockId.entrySet()) { + publicKeyToBlockId.put(entry.getKey(), new ArrayList<>(entry.getValue())); + } return new Authorizer( this.token, new ArrayList<>(this.checks), new ArrayList<>(this.policies), + new ArrayList<>(this.scopes), + publicKeyToBlockId, new World(this.world), new SymbolTable(this.symbolTable), - new StepCounter(this.steps.taken())); + new StepCounter(this.steps.taken()), + this.limits, + this.executionTime); } - public void updateOnToken() throws Error.FailedLogic { + private void loadToken() throws Error.FailedLogic { if (token != null) { for (long i = 0; i < token.blocks.size(); i++) { Block block = token.blocks.get((int) i); @@ -212,76 +230,52 @@ private List translateBlockScopes( return translated; } - public Authorizer addToken(Biscuit token) throws Error.FailedLogic { - if (this.token != null) { - throw new Error.FailedLogic(new LogicError.AuthorizerNotEmpty()); - } - - this.token = token; - updateOnToken(); - return this; + /** Runs the Datalog evaluation with the authorizer's limits, if it has not run yet */ + public Duration run() throws Error { + return this.run(this.limitsWithMaxSteps(this.remainingSteps())); } - public Result>> addDatalog(String s) { - var result = Parser.datalogComponents(s); - - if (result.isErr()) { - var errors = result.getErr(); - Map> errorMap = new HashMap<>(); - for (Map.Entry> entry : - errors.entrySet()) { - List errorsList = new ArrayList<>(); - for (org.eclipse.biscuit.token.builder.parser.Error error : entry.getValue()) { - errorsList.add(new Error.Parser(error)); - } - errorMap.put(entry.getKey(), errorsList); - } - return Result.err(errorMap); + /** Runs the Datalog evaluation with the given limits, if it has not run yet */ + public Duration run(RunLimits limits) throws Error { + long maxSteps = this.maxSteps(limits); + if (this.executionTime != null) { + return this.executionTime; } - - var components = result.getOk(); - components.facts.forEach(this::addFact); - components.rules.forEach(this::addRule); - components.checks.forEach(this::addCheck); - components.scopes.forEach(this::addScope); - components.policies.forEach(this::addPolicy); - - return Result.ok(this); + Instant start = Instant.now(); + this.world.run(limits, this.steps.budget(maxSteps), this.symbolTable); + this.executionTime = Duration.between(start, Instant.now()); + return this.executionTime; } - public Authorizer addScope(org.eclipse.biscuit.token.builder.Scope s) { - this.scopes.add(s.convert(symbolTable)); - return this; + /** The limits of the authorizer, minus what was already used by previous calls */ + private RunLimits remainingLimits(Duration executionTime) throws Error.Timeout { + if (executionTime.compareTo(this.limits.getMaxTime()) >= 0) { + throw new Error.Timeout(); + } + return new RunLimits( + this.limits.getMaxFacts(), + this.limits.getMaxIterations() - this.world.iterations(), + this.limits.getMaxTime().minus(executionTime), + this.remainingSteps()); } - public Authorizer addFact(Fact fact) { - world.addFact(Origin.authorizer(), fact.convert(symbolTable)); - return this; + private RunLimits limitsWithMaxSteps(long maxSteps) { + return new RunLimits( + this.limits.getMaxFacts(), + this.limits.getMaxIterations(), + this.limits.getMaxTime(), + maxSteps); } - public Authorizer addFact(String s) throws Error.Parser { - var res = Parser.fact(s); - if (res.isErr()) { - throw new Error.Parser(res.getErr()); - } - return this.addFact(res.getOk()._2); + private long remainingSteps() { + return Math.max(0, this.limits.getMaxSteps() - this.steps.taken()); } - public Authorizer addRule(Rule rule) { - org.eclipse.biscuit.datalog.Rule r = rule.convert(symbolTable); - TrustedOrigins ruleTrustedOrigins = - TrustedOrigins.fromScopes( - r.scopes(), this.authorizerTrustedOrigins(), Long.MAX_VALUE, this.publicKeyToBlockId); - world.addRule(Long.MAX_VALUE, ruleTrustedOrigins, r); - return this; - } - - public Authorizer addRule(String s) throws Error.Parser { - var res = Parser.rule(s); - if (res.isErr()) { - throw new Error.Parser(res.getErr()); - } - return addRule(res.getOk()._1); + /** Total step count the authorizer can reach in a call using {@code 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; } public TrustedOrigins authorizerTrustedOrigins() { @@ -289,26 +283,6 @@ public TrustedOrigins authorizerTrustedOrigins() { this.scopes, TrustedOrigins.defaultOrigins(), Long.MAX_VALUE, this.publicKeyToBlockId); } - public Authorizer addCheck(Check check) { - this.checks.add(check); - return this; - } - - public Authorizer addCheck(String s) throws Error.Parser { - var res = Parser.check(s); - if (res.isErr()) { - throw new Error.Parser(res.getErr()); - } - return addCheck(res.getOk()._2); - } - - public Authorizer setTime() throws Error.Language { - world.addFact( - Origin.authorizer(), - Utils.fact("time", List.of(Utils.date(new Date()))).convert(symbolTable)); - return this; - } - public List getRevocationIds() throws Error { ArrayList ids = new ArrayList<>(); @@ -333,68 +307,40 @@ public List getRevocationIds() throws Error { return ids; } - public Authorizer allow() { - ArrayList q = new ArrayList<>(); - - q.add( - Utils.constrainedRule( - "allow", new ArrayList<>(), new ArrayList<>(), List.of(new Term.Bool(true)))); - - this.policies.add(new Policy(q, Policy.Kind.ALLOW)); - return this; - } - - public Authorizer deny() { - ArrayList q = new ArrayList<>(); - - q.add( - Utils.constrainedRule( - "deny", new ArrayList<>(), new ArrayList<>(), List.of(new Term.Bool(true)))); - - this.policies.add(new Policy(q, Policy.Kind.DENY)); - return this; + public Set query(Rule query) throws Error { + Duration executionTime = this.run(); + return this.query(query, this.remainingLimits(executionTime)); } - public Authorizer addPolicy(String s) throws Error.Parser { - var res = Parser.policy(s); + public Set query(String s) throws Error { + var res = Parser.rule(s); if (res.isErr()) { throw new Error.Parser(res.getErr()); } - this.policies.add(res.getOk()._2); - return this; - } - - public Authorizer addPolicy(Policy p) { - this.policies.add(p); - return this; - } - - public Authorizer addScope(Scope s) { - this.scopes.add(s); - return this; + return query(res.getOk()._2); } - public Set query(Rule query) throws Error { - RunLimits limits = new RunLimits(); - return this.query(query, limits, Math.max(this.steps.taken(), limits.getMaxSteps())); + /** Runs a query, overriding the authorizer's limits for this call */ + public Set query(Rule query, RunLimits limits) throws Error { + long maxSteps = this.maxSteps(limits); + Duration executionTime = this.run(limits); + Instant start = Instant.now(); + try { + return this.queryInner(query, maxSteps); + } finally { + this.executionTime = executionTime.plus(Duration.between(start, Instant.now())); + } } - public Set query(String s) throws Error { + public Set query(String s, RunLimits limits) throws Error { var res = Parser.rule(s); if (res.isErr()) { throw new Error.Parser(res.getErr()); } - return query(res.getOk()._2); - } - - public Set query(Rule query, RunLimits limits) throws Error { - return this.query(query, limits, this.maxSteps(limits)); + return query(res.getOk()._2, limits); } - private Set query(Rule query, RunLimits limits, long maxSteps) throws Error { - StepBudget budget = this.steps.budget(maxSteps); - world.run(limits, budget, symbolTable); - + private Set queryInner(Rule query, long maxSteps) throws Error { org.eclipse.biscuit.datalog.Rule rule = query.convert(symbolTable); TrustedOrigins ruleTrustedorigins = TrustedOrigins.fromScopes( @@ -403,7 +349,9 @@ private Set query(Rule query, RunLimits limits, long maxSteps) throws Erro Long.MAX_VALUE, this.publicKeyToBlockId); - FactSet facts = world.queryRule(rule, Long.MAX_VALUE, ruleTrustedorigins, symbolTable, budget); + FactSet facts = + world.queryRule( + rule, Long.MAX_VALUE, ruleTrustedorigins, symbolTable, this.steps.budget(maxSteps)); Set s = new HashSet<>(); for (Iterator it = facts.stream().iterator(); @@ -415,39 +363,46 @@ private Set query(Rule query, RunLimits limits, long maxSteps) throws Erro return s; } - public Set query(String s, RunLimits limits) - throws Error { - var res = Parser.rule(s); - if (res.isErr()) { - throw new Error.Parser(res.getErr()); + public Long authorize() throws Error { + Duration executionTime = this.run(); + return this.authorize(this.remainingLimits(executionTime)); + } + + /** Verifies the checks and policies, overriding the authorizer's limits for this call */ + public Long authorize(RunLimits limits) throws Error { + long maxSteps = this.maxSteps(limits); + Duration executionTime = this.run(limits); + Instant start = Instant.now(); + try { + return this.authorizeInner(limits, maxSteps); + } finally { + this.executionTime = executionTime.plus(Duration.between(start, Instant.now())); } - return query(res.getOk()._2, limits); } - public Long authorize() throws Error { - RunLimits limits = new RunLimits(); - return this.authorize(limits, Math.max(this.steps.taken(), limits.getMaxSteps())); + public Optional executionTime() { + return Optional.ofNullable(this.executionTime); } - public Long authorize(RunLimits limits) throws Error { - return this.authorize(limits, this.maxSteps(limits)); + public int iterations() { + return this.world.iterations(); } - 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; + public long elapsedSteps() { + return this.steps.taken(); } - private Long authorize(RunLimits limits, long maxSteps) throws Error { + public RunLimits limits() { + return this.limits; + } + + private Long authorizeInner(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, budget, symbolTable); - for (int i = 0; i < this.checks.size(); i++) { org.eclipse.biscuit.datalog.Check c = this.checks.get(i).convert(symbolTable); boolean successful = false; diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/token/Biscuit.java b/biscuit-core/src/main/java/org/eclipse/biscuit/token/Biscuit.java index 34ab15b8..bcaad6e5 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/token/Biscuit.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/token/Biscuit.java @@ -264,7 +264,7 @@ static Biscuit fromSerializedBiscuit(SerializedBiscuit ser, SymbolTable symbolTa * @return */ public Authorizer authorizer() throws Error.FailedLogic { - return Authorizer.make(this); + return new org.eclipse.biscuit.token.builder.AuthorizerBuilder().build(this); } /** diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/token/builder/AuthorizerBuilder.java b/biscuit-core/src/main/java/org/eclipse/biscuit/token/builder/AuthorizerBuilder.java new file mode 100644 index 00000000..55238c82 --- /dev/null +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/token/builder/AuthorizerBuilder.java @@ -0,0 +1,273 @@ +/* + * Copyright (c) 2019 Geoffroy Couprie and Contributors to the Eclipse Foundation. + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.eclipse.biscuit.token.builder; + +import static org.eclipse.biscuit.datalog.Check.Kind.ONE; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.eclipse.biscuit.datalog.RunLimits; +import org.eclipse.biscuit.error.Error; +import org.eclipse.biscuit.error.Result; +import org.eclipse.biscuit.token.Authorizer; +import org.eclipse.biscuit.token.Biscuit; +import org.eclipse.biscuit.token.Policy; +import org.eclipse.biscuit.token.builder.parser.Parser; + +public final class AuthorizerBuilder { + private final List facts = new ArrayList<>(); + private final List rules = new ArrayList<>(); + private final List checks = new ArrayList<>(); + private final List scopes = new ArrayList<>(); + private final List policies = new ArrayList<>(); + private RunLimits limits = new RunLimits(); + + public AuthorizerBuilder() {} + + public AuthorizerBuilder clone() { + AuthorizerBuilder clone = new AuthorizerBuilder(); + clone.facts.addAll(this.facts); + clone.rules.addAll(this.rules); + clone.checks.addAll(this.checks); + clone.scopes.addAll(this.scopes); + clone.policies.addAll(this.policies); + clone.limits = + new RunLimits( + this.limits.getMaxFacts(), + this.limits.getMaxIterations(), + this.limits.getMaxTime(), + this.limits.getMaxSteps()); + return clone; + } + + public AuthorizerBuilder addFact(Fact fact) { + this.facts.add(fact); + return this; + } + + public AuthorizerBuilder addFact(String s) throws Error.Parser { + var res = Parser.fact(s); + if (res.isErr()) { + throw new Error.Parser(res.getErr()); + } + return this.addFact(res.getOk()._2); + } + + public AuthorizerBuilder addRule(Rule rule) { + this.rules.add(rule); + return this; + } + + public AuthorizerBuilder addRule(String s) throws Error.Parser { + var res = Parser.rule(s); + if (res.isErr()) { + throw new Error.Parser(res.getErr()); + } + return this.addRule(res.getOk()._2); + } + + public AuthorizerBuilder addCheck(Check check) { + this.checks.add(check); + return this; + } + + public AuthorizerBuilder addCheck(String s) throws Error.Parser { + var res = Parser.check(s); + if (res.isErr()) { + throw new Error.Parser(res.getErr()); + } + return this.addCheck(res.getOk()._2); + } + + public AuthorizerBuilder addScope(Scope scope) { + this.scopes.add(scope); + return this; + } + + public AuthorizerBuilder addPolicy(Policy policy) { + this.policies.add(policy); + return this; + } + + public AuthorizerBuilder addPolicy(String s) throws Error.Parser { + var res = Parser.policy(s); + if (res.isErr()) { + throw new Error.Parser(res.getErr()); + } + return this.addPolicy(res.getOk()._2); + } + + public Result>> addDatalog(String s) { + var result = Parser.datalogComponents(s); + + if (result.isErr()) { + var errors = result.getErr(); + Map> errorMap = new HashMap<>(); + for (Map.Entry> entry : + errors.entrySet()) { + List errorsList = new ArrayList<>(); + for (org.eclipse.biscuit.token.builder.parser.Error error : entry.getValue()) { + errorsList.add(new Error.Parser(error)); + } + errorMap.put(entry.getKey(), errorsList); + } + return Result.err(errorMap); + } + + var components = result.getOk(); + this.facts.addAll(components.facts); + this.rules.addAll(components.rules); + this.checks.addAll(components.checks); + this.scopes.addAll(components.scopes); + this.policies.addAll(components.policies); + + return Result.ok(this); + } + + public AuthorizerBuilder setTime() throws Error.Language { + return this.addFact(Utils.fact("time", List.of(Utils.date(new Date())))); + } + + public AuthorizerBuilder allow() { + return this.addPolicy( + new Policy( + Utils.constrainedRule( + "allow", new ArrayList<>(), new ArrayList<>(), List.of(new Term.Bool(true))), + Policy.Kind.ALLOW)); + } + + public AuthorizerBuilder deny() { + return this.addPolicy( + new Policy( + Utils.constrainedRule( + "deny", new ArrayList<>(), new ArrayList<>(), List.of(new Term.Bool(true))), + Policy.Kind.DENY)); + } + + public AuthorizerBuilder addResource(String name) { + return this.addFact(new Fact("resource", List.of(Utils.string(name)))); + } + + public AuthorizerBuilder addOperation(String name) { + return this.addFact(new Fact("operation", List.of(Utils.string(name)))); + } + + public AuthorizerBuilder checkResource(String name) { + return this.addCheck( + new Check( + ONE, + Utils.rule( + "resource_check", + List.of(Utils.string("resource_check")), + List.of(Utils.pred("resource", List.of(Utils.string(name))))))); + } + + public AuthorizerBuilder checkOperation(String name) { + return this.addCheck( + new Check( + ONE, + Utils.rule( + "operation_check", + List.of(Utils.string("operation_check")), + List.of(Utils.pred("operation", List.of(Utils.string(name))))))); + } + + public AuthorizerBuilder resourcePrefix(String prefix) { + return this.mergeBlock(new Block().resourcePrefix(prefix)); + } + + public AuthorizerBuilder resourceSuffix(String suffix) { + return this.mergeBlock(new Block().resourceSuffix(suffix)); + } + + public AuthorizerBuilder setExpirationDate(Date date) { + return this.mergeBlock(new Block().setExpirationDate(date)); + } + + public AuthorizerBuilder setLimits(RunLimits limits) { + this.limits = limits; + return this; + } + + public RunLimits limits() { + return this.limits; + } + + public AuthorizerBuilder mergeBlock(Block block) { + this.facts.addAll(block.facts()); + this.rules.addAll(block.rules()); + this.checks.addAll(block.checks()); + this.scopes.addAll(block.scopes()); + return this; + } + + public AuthorizerBuilder merge(AuthorizerBuilder other) { + this.facts.addAll(other.facts); + this.rules.addAll(other.rules); + this.checks.addAll(other.checks); + this.scopes.addAll(other.scopes); + this.policies.addAll(other.policies); + return this; + } + + public Authorizer build(Biscuit token) throws Error.FailedLogic { + return Authorizer.make(this, token); + } + + public Authorizer buildUnauthenticated() throws Error.FailedLogic { + return Authorizer.make(this, null); + } + + public List facts() { + return this.facts; + } + + public List rules() { + return this.rules; + } + + public List checks() { + return this.checks; + } + + public List scopes() { + return this.scopes; + } + + public List policies() { + return this.policies; + } + + @Override + public String toString() { + StringBuilder s = new StringBuilder(); + for (Fact fact : this.facts) { + s.append(fact).append(";\n"); + } + if (!this.facts.isEmpty()) { + s.append("\n"); + } + for (Rule rule : this.rules) { + s.append(rule).append(";\n"); + } + if (!this.rules.isEmpty()) { + s.append("\n"); + } + for (Check check : this.checks) { + s.append(check).append(";\n"); + } + if (!this.checks.isEmpty()) { + s.append("\n"); + } + for (Policy policy : this.policies) { + s.append(policy).append(";\n"); + } + return s.toString(); + } +} diff --git a/biscuit/src/test/java/org/eclipse/biscuit/token/AuthorizerTest.java b/biscuit/src/test/java/org/eclipse/biscuit/token/AuthorizerTest.java index 47f5a275..b1cda437 100644 --- a/biscuit/src/test/java/org/eclipse/biscuit/token/AuthorizerTest.java +++ b/biscuit/src/test/java/org/eclipse/biscuit/token/AuthorizerTest.java @@ -13,12 +13,14 @@ import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; +import java.util.Date; import java.util.List; import java.util.Set; import org.eclipse.biscuit.crypto.KeyPair; import org.eclipse.biscuit.datalog.RunLimits; import org.eclipse.biscuit.error.Error; import org.eclipse.biscuit.error.Error.Parser; +import org.eclipse.biscuit.token.builder.AuthorizerBuilder; import org.eclipse.biscuit.token.builder.Term; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -36,12 +38,12 @@ public void setUp() throws Exception { @Test public void testAuthorizerPolicy() throws Parser { - Authorizer authorizer = new Authorizer(); - List policies = authorizer.getPolicies(); - authorizer.deny(); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + List policies = authorizerBuilder.policies(); + authorizerBuilder.deny(); assertEquals(1, policies.size()); - authorizer.addPolicy( + authorizerBuilder.addPolicy( new Policy( Arrays.asList( constrainedRule( @@ -52,7 +54,7 @@ public void testAuthorizerPolicy() throws Parser { Policy.Kind.DENY)); assertEquals(2, policies.size()); - authorizer.addPolicy("deny if true"); + authorizerBuilder.addPolicy("deny if true"); assertEquals(3, policies.size()); } @@ -103,11 +105,11 @@ public void eliminateUnusedBodyPredicateInRule() throws Exception { var token = block.build(); Authorizer authorizer = - Biscuit.fromBase64Url(token.serializeBase64Url(), keyPair.getPublicKey()) - .verify(keyPair.getPublicKey()) - .authorizer(); - - authorizer.addPolicy("allow if true"); + new AuthorizerBuilder() + .addPolicy("allow if true") + .build( + Biscuit.fromBase64Url(token.serializeBase64Url(), keyPair.getPublicKey()) + .verify(keyPair.getPublicKey())); RunLimits limits = new RunLimits(1_000_000_000, 1_000_000_000, Duration.ofDays(20), 1000); assertEquals(6, authorizer.getRules().stream().findFirst().get().body().size()); @@ -127,16 +129,17 @@ public void testDatalogAuthorizer() throws Exception { .addAuthorityFact("perms({1,2,3})") .build(); - Authorizer authorizer = - Biscuit.fromBase64Url(token.serializeBase64Url(), keypair.getPublicKey()) - .verify(keypair.getPublicKey()) - .authorizer(); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); String l0 = "right($email) <- email($email)"; String l1 = "check if right(\"bob@example.com\")"; String l2 = "allow if true"; String datalog = String.join(";", Arrays.asList(l0, l1, l2)); - authorizer.addDatalog(datalog); + authorizerBuilder.addDatalog(datalog); + Authorizer authorizer = + authorizerBuilder.build( + Biscuit.fromBase64Url(token.serializeBase64Url(), keypair.getPublicKey()) + .verify(keypair.getPublicKey())); assertDoesNotThrow(() -> authorizer.authorize(runLimits)); @@ -144,6 +147,105 @@ public void testDatalogAuthorizer() throws Exception { assertEquals("bob@example.com", ((Term.Str) emailTerm).getValue()); } + @Test + public void mergeCombinesBuilders() throws Exception { + AuthorizerBuilder facts = new AuthorizerBuilder().addFact("resource(\"file1\")"); + AuthorizerBuilder policies = + new AuthorizerBuilder().addCheck("check if resource(\"file1\")").allow(); + + Authorizer authorizer = + new AuthorizerBuilder().merge(facts).merge(policies).buildUnauthenticated(); + + assertEquals(0, authorizer.authorize()); + assertEquals(1, facts.facts().size()); + assertEquals(0, facts.policies().size()); + } + + @Test + public void mergeBlockAddsTheBlockContents() throws Exception { + org.eclipse.biscuit.token.builder.Block block = new org.eclipse.biscuit.token.builder.Block(); + block.addFact("resource(\"file1\")"); + block.addRule("allowed($r) <- resource($r)"); + block.addCheck("check if allowed(\"file1\")"); + + Authorizer authorizer = + new AuthorizerBuilder().mergeBlock(block).allow().buildUnauthenticated(); + + assertEquals(0, authorizer.authorize()); + } + + @Test + public void builderPrintsItsDatalog() throws Exception { + AuthorizerBuilder builder = + new AuthorizerBuilder() + .addFact("resource(\"file1\")") + .addRule("allowed($r) <- resource($r)") + .addCheck("check if allowed(\"file1\")") + .addPolicy("allow if true"); + + assertEquals( + "resource(\"file1\");\n\n" + + "allowed($r) <- resource($r);\n\n" + + "check if allowed(\"file1\");\n\n" + + "allow if true;\n", + builder.toString()); + } + + @Test + public void resourceAndOperationHelpers() throws Exception { + AuthorizerBuilder builder = + new AuthorizerBuilder() + .addResource("file1") + .addOperation("read") + .checkResource("file1") + .checkOperation("read") + .allow(); + assertEquals(0, builder.buildUnauthenticated().authorize()); + + Authorizer wrongOperation = + new AuthorizerBuilder() + .addResource("file1") + .addOperation("write") + .checkOperation("read") + .allow() + .buildUnauthenticated(); + assertThrows(Error.FailedLogic.class, wrongOperation::authorize); + } + + @Test + public void resourcePrefixAndSuffixHelpers() throws Exception { + Authorizer matching = + new AuthorizerBuilder() + .addResource("/folder/file.txt") + .resourcePrefix("/folder/") + .resourceSuffix(".txt") + .allow() + .buildUnauthenticated(); + assertEquals(0, matching.authorize()); + + Authorizer wrongPrefix = + new AuthorizerBuilder() + .addResource("/other/file.txt") + .resourcePrefix("/folder/") + .allow() + .buildUnauthenticated(); + assertThrows(Error.FailedLogic.class, wrongPrefix::authorize); + } + + @Test + public void expirationDateHelper() throws Exception { + Date future = new Date(System.currentTimeMillis() + 3_600_000); + Date past = new Date(System.currentTimeMillis() - 3_600_000); + + Authorizer valid = + new AuthorizerBuilder().setTime().setExpirationDate(future).allow().buildUnauthenticated(); + assertEquals(0, valid.authorize()); + + Authorizer expired = + new AuthorizerBuilder().setTime().setExpirationDate(past).allow().buildUnauthenticated(); + assertThrows(Error.FailedLogic.class, expired::authorize); + } + private static Term queryFirstResult(Authorizer authorizer, String query) throws Error { return authorizer.query(query).iterator().next().terms().get(0); } diff --git a/biscuit/src/test/java/org/eclipse/biscuit/token/BiscuitTest.java b/biscuit/src/test/java/org/eclipse/biscuit/token/BiscuitTest.java index dc429dcb..05693a17 100644 --- a/biscuit/src/test/java/org/eclipse/biscuit/token/BiscuitTest.java +++ b/biscuit/src/test/java/org/eclipse/biscuit/token/BiscuitTest.java @@ -35,6 +35,7 @@ import org.eclipse.biscuit.error.Error; import org.eclipse.biscuit.error.FailedCheck; import org.eclipse.biscuit.error.LogicError; +import org.eclipse.biscuit.token.builder.AuthorizerBuilder; import org.eclipse.biscuit.token.builder.Block; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -151,19 +152,21 @@ public void testBasic() // check System.out.println("will check the token for resource=file1 and operation=read"); - Authorizer authorizer = finalToken.authorizer(); - authorizer.addFact("resource(\"file1\")"); - authorizer.addFact("operation(\"read\")"); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addFact("resource(\"file1\")"); + authorizerBuilder.addFact("operation(\"read\")"); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(finalToken); authorizer.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); System.out.println("will check the token for resource=file2 and operation=write"); - Authorizer authorizer2 = finalToken.authorizer(); - authorizer2.addFact("resource(\"file2\")"); - authorizer2.addFact("operation(\"write\")"); - authorizer2.addPolicy("allow if true"); + AuthorizerBuilder authorizer2Builder = new AuthorizerBuilder(); + authorizer2Builder.addFact("resource(\"file2\")"); + authorizer2Builder.addFact("operation(\"write\")"); + authorizer2Builder.addPolicy("allow if true"); + Authorizer authorizer2 = authorizer2Builder.build(finalToken); try { authorizer2.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); } catch (Error e) { @@ -209,16 +212,18 @@ public void testFolders() throws NoSuchAlgorithmException, Error { KeyPair keypair2 = KeyPair.generate(Schema.PublicKey.Algorithm.Ed25519, rng); Biscuit b2 = b.attenuate(rng, keypair2, block2); - Authorizer v1 = b2.authorizer(); - v1.addFact("resource(\"/folder1/file1\")"); - v1.addFact("operation(\"read\")"); - v1.allow(); + AuthorizerBuilder v1Builder = new AuthorizerBuilder(); + v1Builder.addFact("resource(\"/folder1/file1\")"); + v1Builder.addFact("operation(\"read\")"); + v1Builder.allow(); + Authorizer v1 = v1Builder.build(b2); v1.authorize(); - Authorizer v2 = b2.authorizer(); - v2.addFact("resource(\"/folder2/file3\")"); - v2.addFact("operation(\"read\")"); - v2.allow(); + AuthorizerBuilder v2Builder = new AuthorizerBuilder(); + v2Builder.addFact("resource(\"/folder2/file3\")"); + v2Builder.addFact("operation(\"read\")"); + v2Builder.allow(); + Authorizer v2 = v2Builder.build(b2); try { v2.authorize(); fail(); @@ -226,10 +231,11 @@ public void testFolders() throws NoSuchAlgorithmException, Error { // Empty } - Authorizer v3 = b2.authorizer(); - v3.addFact("resource(\"/folder2/file1\")"); - v3.addFact("operation(\"write\")"); - v3.allow(); + AuthorizerBuilder v3Builder = new AuthorizerBuilder(); + v3Builder.addFact("resource(\"/folder2/file1\")"); + v3Builder.addFact("operation(\"write\")"); + v3Builder.allow(); + Authorizer v3 = v3Builder.build(b2); try { v3.authorize(); fail(); @@ -318,28 +324,34 @@ public void testReset() throws Error, NoSuchAlgorithmException { KeyPair keypair2 = KeyPair.generate(Schema.PublicKey.Algorithm.Ed25519, rng); Biscuit b2 = b.attenuate(rng, keypair2, block2); - Authorizer v1 = b2.authorizer(); - v1.allow(); + AuthorizerBuilder v1Builder = new AuthorizerBuilder(); + v1Builder.allow(); - Authorizer v2 = v1.clone(); - - v2.addFact("resource(\"/folder1/file1\")"); - v2.addFact("operation(\"read\")"); + Authorizer v2 = + new AuthorizerBuilder() + .merge(v1Builder) + .addFact("resource(\"/folder1/file1\")") + .addFact("operation(\"read\")") + .build(b2); v2.authorize(); - Authorizer v3 = v1.clone(); - - v3.addFact("resource(\"/folder2/file3\")"); - v3.addFact("operation(\"read\")"); + Authorizer v3 = + new AuthorizerBuilder() + .merge(v1Builder) + .addFact("resource(\"/folder2/file3\")") + .addFact("operation(\"read\")") + .build(b2); Assertions.assertThrows(Error.class, v3::authorize); System.out.println(v3.formatWorld()); - Authorizer v4 = v1.clone(); - - v4.addFact("resource(\"/folder2/file1\")"); - v4.addFact("operation(\"write\")"); + Authorizer v4 = + new AuthorizerBuilder() + .merge(v1Builder) + .addFact("resource(\"/folder2/file1\")") + .addFact("operation(\"write\")") + .build(b2); var e = Assertions.assertThrows(Error.class, v4::authorize); @@ -388,17 +400,15 @@ public void testEmptyAuthorizer() throws Error, NoSuchAlgorithmException { KeyPair keypair2 = KeyPair.generate(Schema.PublicKey.Algorithm.Ed25519, rng); Biscuit b2 = b.attenuate(rng, keypair2, block2); - Authorizer v1 = new Authorizer(); - v1.allow(); - - v1.authorize(); + AuthorizerBuilder v1Builder = new AuthorizerBuilder(); + v1Builder.allow(); - v1.addToken(b2); + v1Builder.buildUnauthenticated().authorize(); - v1.addFact("resource(\"/folder2/file1\")"); - v1.addFact("operation(\"write\")"); + v1Builder.addFact("resource(\"/folder2/file1\")"); + v1Builder.addFact("operation(\"write\")"); - assertThrows(Error.class, v1::authorize); + assertThrows(Error.class, v1Builder.build(b2)::authorize); } @Test @@ -496,19 +506,21 @@ public void testBasicWithNamespaces() // check System.out.println("will check the token for resource=file1 and operation=read"); - Authorizer authorizer = finalToken.authorizer(); - authorizer.addFact("resource(\"file1\")"); - authorizer.addFact("operation(\"read\")"); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addFact("resource(\"file1\")"); + authorizerBuilder.addFact("operation(\"read\")"); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(finalToken); authorizer.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); System.out.println("will check the token for resource=file2 and operation=write"); - Authorizer authorizer2 = finalToken.authorizer(); - authorizer2.addFact("resource(\"file2\")"); - authorizer2.addFact("operation(\"write\")"); - authorizer2.addPolicy("allow if true"); + AuthorizerBuilder authorizer2Builder = new AuthorizerBuilder(); + authorizer2Builder.addFact("resource(\"file2\")"); + authorizer2Builder.addFact("operation(\"write\")"); + authorizer2Builder.addPolicy("allow if true"); + Authorizer authorizer2 = authorizer2Builder.build(finalToken); try { authorizer2.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); } catch (Error e) { @@ -623,18 +635,20 @@ public void testBasicWithNamespacesWithAddAuthorityFact() // check System.out.println("will check the token for resource=file1 and operation=read"); - Authorizer authorizer = finalToken.authorizer(); - authorizer.addFact("resource(\"file1\")"); - authorizer.addFact("operation(\"read\")"); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addFact("resource(\"file1\")"); + authorizerBuilder.addFact("operation(\"read\")"); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(finalToken); authorizer.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); System.out.println("will check the token for resource=file2 and operation=write"); - Authorizer authorizer2 = finalToken.authorizer(); - authorizer2.addFact("resource(\"file2\")"); - authorizer2.addFact("operation(\"write\")"); - authorizer2.addPolicy("allow if true"); + AuthorizerBuilder authorizer2Builder = new AuthorizerBuilder(); + authorizer2Builder.addFact("resource(\"file2\")"); + authorizer2Builder.addFact("operation(\"write\")"); + authorizer2Builder.addPolicy("allow if true"); + Authorizer authorizer2 = authorizer2Builder.build(finalToken); try { authorizer2.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); } catch (Error e) { @@ -742,12 +756,13 @@ public void testCheckAll() .addAuthorityCheck( "check all operation($op), allowed_operations($allowed), $allowed.contains($op)") .build(); - Authorizer authorizer = biscuit.verify(root.getPublicKey()).authorizer(); - authorizer.addFact("operation(\"read\")"); - authorizer.addFact("operation(\"write\")"); - authorizer.addFact("allowed_operations({\"write\"})"); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addFact("operation(\"read\")"); + authorizerBuilder.addFact("operation(\"write\")"); + authorizerBuilder.addFact("allowed_operations({\"write\"})"); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(biscuit.verify(root.getPublicKey())); try { authorizer.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); } catch (Error.FailedLogic e) { @@ -765,12 +780,13 @@ public void testCheckAll() e); } - Authorizer authorizer2 = biscuit.verify(root.getPublicKey()).authorizer(); - authorizer2.addFact("operation(\"read\")"); - authorizer2.addFact("operation(\"write\")"); - authorizer2.addFact("allowed_operations({\"read\", \"write\"})"); - authorizer2.addPolicy("allow if true"); + AuthorizerBuilder authorizer2Builder = new AuthorizerBuilder(); + authorizer2Builder.addFact("operation(\"read\")"); + authorizer2Builder.addFact("operation(\"write\")"); + authorizer2Builder.addFact("allowed_operations({\"read\", \"write\"})"); + authorizer2Builder.addPolicy("allow if true"); + Authorizer authorizer2 = authorizer2Builder.build(biscuit.verify(root.getPublicKey())); authorizer2.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); } } diff --git a/biscuit/src/test/java/org/eclipse/biscuit/token/ExampleTest.java b/biscuit/src/test/java/org/eclipse/biscuit/token/ExampleTest.java index 99fa9028..8007e669 100644 --- a/biscuit/src/test/java/org/eclipse/biscuit/token/ExampleTest.java +++ b/biscuit/src/test/java/org/eclipse/biscuit/token/ExampleTest.java @@ -11,6 +11,7 @@ import java.security.SignatureException; import org.eclipse.biscuit.crypto.KeyPair; import org.eclipse.biscuit.error.Error; +import org.eclipse.biscuit.token.builder.AuthorizerBuilder; import org.eclipse.biscuit.token.builder.Block; /* example code for the documentation at https://www.biscuitsec.org @@ -30,11 +31,11 @@ public Biscuit createToken(KeyPair root) throws Error { public Long authorize(KeyPair root, byte[] serializedToken) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { - return Biscuit.fromBytes(serializedToken, root.getPublicKey()) - .authorizer() + return new AuthorizerBuilder() .addFact("resource(\"/folder1/file1\")") .addFact("operation(\"read\")") .allow() + .build(Biscuit.fromBytes(serializedToken, root.getPublicKey())) .authorize(); } diff --git a/biscuit/src/test/java/org/eclipse/biscuit/token/SamplesTest.java b/biscuit/src/test/java/org/eclipse/biscuit/token/SamplesTest.java index ee6022bd..59b22858 100644 --- a/biscuit/src/test/java/org/eclipse/biscuit/token/SamplesTest.java +++ b/biscuit/src/test/java/org/eclipse/biscuit/token/SamplesTest.java @@ -41,6 +41,7 @@ import org.eclipse.biscuit.datalog.SymbolTable; import org.eclipse.biscuit.error.Error; import org.eclipse.biscuit.error.Result; +import org.eclipse.biscuit.token.builder.AuthorizerBuilder; import org.eclipse.biscuit.token.builder.Check; import org.eclipse.biscuit.token.builder.parser.Parser; import org.eclipse.biscuit.token.format.SignedBlock; @@ -207,7 +208,7 @@ DynamicTest processTestcase( // TODO Add check of the token - Authorizer authorizer = token.authorizer(); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); System.out.println(token.print()); for (String f : authorizerFacts) { f = f.trim(); @@ -215,16 +216,17 @@ DynamicTest processTestcase( if (f.startsWith("check if") || f.startsWith("check all") || f.startsWith("reject if")) { - authorizer.addCheck(f); + authorizerBuilder.addCheck(f); } else if (f.startsWith("allow if") || f.startsWith("deny if")) { - authorizer.addPolicy(f); + authorizerBuilder.addPolicy(f); } else if (f.startsWith("revocation_id")) { // do nothing } else { - authorizer.addFact(f); + authorizerBuilder.addFact(f); } } } + Authorizer authorizer = authorizerBuilder.build(token); System.out.println(authorizer.formatWorld()); try { 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 0c6f5914..923d8a7d 100644 --- a/biscuit/src/test/java/org/eclipse/biscuit/token/StepLimitTest.java +++ b/biscuit/src/test/java/org/eclipse/biscuit/token/StepLimitTest.java @@ -8,6 +8,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import biscuit.format.schema.Schema; import java.security.SecureRandom; @@ -15,6 +16,7 @@ import org.eclipse.biscuit.crypto.KeyPair; import org.eclipse.biscuit.datalog.RunLimits; import org.eclipse.biscuit.error.Error; +import org.eclipse.biscuit.token.builder.AuthorizerBuilder; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -57,9 +59,10 @@ public void joinOverBudgetThrowsTooManySteps() throws Exception { } block.addAuthorityRule("b($0) <- f($0), f($1), f($2), f($3)"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertThrows(Error.TooManySteps.class, () -> authorizer.authorize(steps(1000))); } @@ -72,9 +75,10 @@ public void smallJoinWithinBudgetAuthorizes() throws Exception { } block.addAuthorityRule("b($0) <- f($0), f($1)"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertDoesNotThrow(() -> authorizer.authorize(steps(1000))); } @@ -89,9 +93,10 @@ public void exactBudgetAuthorizes() throws Exception { } block.addAuthorityRule("b($0) <- f($0)"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertDoesNotThrow(() -> authorizer.authorize(steps(10))); } @@ -106,16 +111,17 @@ public void oneStepUnderBudgetThrowsTooManySteps() throws Exception { } block.addAuthorityRule("b($0) <- f($0)"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertThrows(Error.TooManySteps.class, () -> authorizer.authorize(steps(9))); } @Test public void zeroBudgetWithNothingToDoAuthorizes() throws Exception { - Authorizer authorizer = new Authorizer(); - authorizer.addPolicy("allow if true"); + Authorizer authorizer = + new AuthorizerBuilder().addPolicy("allow if true").buildUnauthenticated(); assertDoesNotThrow(() -> authorizer.authorize(steps(0))); } @@ -127,9 +133,10 @@ public void zeroBudgetWithFactsToScanThrowsTooManySteps() throws Exception { block.addAuthorityFact("f(1)"); block.addAuthorityRule("b($0) <- f($0)"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertThrows(Error.TooManySteps.class, () -> authorizer.authorize(steps(0))); } @@ -145,9 +152,10 @@ public void budgetIsSharedAcrossRules() throws Exception { block.addAuthorityRule("b($0) <- f($0)"); block.addAuthorityRule("c($0) <- f($0)"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertThrows(Error.TooManySteps.class, () -> authorizer.authorize(steps(15))); } @@ -160,78 +168,107 @@ public void stepLimitDoesNotHideTooManyFacts() throws Exception { } block.addAuthorityRule("g($0) <- f($0)"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); RunLimits limits = new RunLimits(10, 1_000_000, Duration.ofDays(1), 1_000_000); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertThrows(Error.TooManyFacts.class, () -> authorizer.authorize(limits)); } @Test 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 second call gets - // 20 steps on top of the ones already taken. + // The check visits the 8 facts and compares each one: 16 steps per authorization. 16 + 16 + // 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++) { block.addAuthorityFact("f(" + i + ")"); } - block.addAuthorityRule("b($0) <- f($0)"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + Authorizer authorizer = + new AuthorizerBuilder() + .addCheck("check all f($0), $0 >= 0") + .addPolicy("allow if true") + .build(block.build()); assertDoesNotThrow(() -> authorizer.authorize(steps(20))); 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(); + public void authorizerLimitsCountTheStepsAlreadyTaken() throws Exception { + // The first call takes 1001 steps: 1000 for the evaluation (500 facts, two passes) and 1 for + // the check. That is more than the authorizer's 1000 steps, so the second call fails on its + // first step. + Authorizer authorizer = authorizerBudgetTaken(); - assertDoesNotThrow(() -> authorizer.authorize(steps(1000))); + assertDoesNotThrow(() -> authorizer.authorize(steps(1001))); assertThrows(Error.TooManySteps.class, () -> authorizer.authorize()); } @Test - public void queryWithDefaultLimitsCountsTheStepsTakenByAuthorize() throws Exception { - Authorizer authorizer = defaultBudgetTaken(); + public void queryWithAuthorizerLimitsCountsTheStepsTakenByAuthorize() throws Exception { + Authorizer authorizer = authorizerBudgetTaken(); - assertDoesNotThrow(() -> authorizer.authorize(steps(1000))); + assertDoesNotThrow(() -> authorizer.authorize(steps(1001))); assertThrows(Error.TooManySteps.class, () -> authorizer.query("q($0) <- b($0)")); } @Test public void clonedAuthorizerKeepsTheStepsTaken() throws Exception { - Authorizer authorizer = defaultBudgetTaken(); + Authorizer authorizer = authorizerBudgetTaken(); - assertDoesNotThrow(() -> authorizer.authorize(steps(1000))); + assertDoesNotThrow(() -> authorizer.authorize(steps(1001))); Authorizer cloned = authorizer.clone(); assertThrows(Error.TooManySteps.class, () -> cloned.authorize()); } @Test public void maximumBudgetDoesNotOverflowAfterStepsWereTaken() throws Exception { - Authorizer authorizer = defaultBudgetTaken(); + Authorizer authorizer = authorizerBudgetTaken(); assertDoesNotThrow(() -> authorizer.authorize(steps(Long.MAX_VALUE))); assertDoesNotThrow(() -> authorizer.authorize(steps(Long.MAX_VALUE))); } - private Authorizer defaultBudgetTaken() throws Exception { + @Test + public void evaluationRunsOnlyOnce() throws Exception { + // Running the evaluation again would take 500 steps, the check alone takes 1. + Authorizer authorizer = authorizerBudgetTaken(); + + assertDoesNotThrow(() -> authorizer.authorize(steps(1001))); + assertDoesNotThrow(() -> authorizer.authorize(steps(1))); + assertEquals(1002, authorizer.elapsedSteps()); + } + + @Test + public void buildDoesNotRunTheEvaluation() throws Exception { + AuthorizerBuilder builder = new AuthorizerBuilder().addPolicy("allow if true"); + builder.setLimits(steps(10)); + Authorizer authorizer = builder.build(fiveHundredFacts()); + + assertTrue(authorizer.executionTime().isEmpty()); + assertThrows(Error.TooManySteps.class, () -> authorizer.authorize()); + } + + private Biscuit fiveHundredFacts() 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)"); + return block.build(); + } - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); - return authorizer; + private Authorizer authorizerBudgetTaken() throws Exception { + return new AuthorizerBuilder() + .addCheck("check if 1 == 1") + .addPolicy("allow if true") + .setLimits(steps(1000)) + .build(fiveHundredFacts()); } // --------------------------------------------------------------------------------------------- @@ -246,9 +283,10 @@ public void anyWithoutAMatchVisitsEveryElement() throws Exception { block.addAuthorityFact("x([" + TWENTY + "])"); block.addAuthorityRule("ok(1) <- x($0), $0.any($1 -> $1 == -1)"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertThrows(Error.TooManySteps.class, () -> authorizer.authorize(steps(40))); } @@ -261,9 +299,10 @@ public void anyStopsCountingAtTheFirstMatch() throws Exception { block.addAuthorityFact("x([" + TWENTY + "])"); block.addAuthorityRule("ok(1) <- x($0), $0.any($1 -> $1 == 0)"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertDoesNotThrow(() -> authorizer.authorize(steps(8))); } @@ -275,11 +314,14 @@ public void allStopsCountingAtTheFirstFailure() throws Exception { block.addAuthorityFact("x([100, " + TWENTY + "])"); block.addAuthorityRule("ok(1) <- x($0), $0.all($1 -> $1 < 50)"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Biscuit token = block.build(); + Authorizer authorizer = authorizerBuilder.build(token); + Authorizer tooSmall = authorizerBuilder.build(token); assertDoesNotThrow(() -> authorizer.authorize(steps(4))); - assertThrows(Error.TooManySteps.class, () -> authorizer.authorize(steps(3))); + assertThrows(Error.TooManySteps.class, () -> tooSmall.authorize(steps(3))); } @Test @@ -290,9 +332,10 @@ public void allVisitsEveryElementWhenTheyAllPass() throws Exception { block.addAuthorityFact("x([" + TWENTY + ", 100])"); block.addAuthorityRule("ok(1) <- x($0), $0.all($1 -> $1 < 50)"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertThrows(Error.TooManySteps.class, () -> authorizer.authorize(steps(43))); assertDoesNotThrow(() -> authorizer.authorize(steps(44))); } @@ -305,9 +348,10 @@ public void lightClosureBodyFitsTheBudget() throws Exception { block.addAuthorityFact("x([" + TWENTY + "])"); block.addAuthorityRule("ok(1) <- x($0), $0.any($1 -> $1 == -1)"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertDoesNotThrow(() -> authorizer.authorize(steps(42))); } @@ -320,9 +364,10 @@ public void everyOperatorInsideAClosureCounts() throws Exception { block.addAuthorityFact("x([" + TWENTY + "])"); block.addAuthorityRule("ok(1) <- x($0), $0.any($1 -> $1 + 1 + 1 + 1 + 1 == -1)"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertThrows(Error.TooManySteps.class, () -> authorizer.authorize(steps(50))); } @@ -335,9 +380,10 @@ public void applyingAnyToEachElementCountsEvenWithoutOperators() throws Exceptio block.addAuthorityFact("x([" + TWENTY + "])"); block.addAuthorityRule("ok(1) <- x($0), $0.any($1 -> false)"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertThrows(Error.TooManySteps.class, () -> authorizer.authorize(steps(10))); } @@ -349,9 +395,10 @@ public void nestedAnyOverTenElementsFitsTheDefaultBudget() throws Exception { block.addAuthorityFact("x([" + TEN + "])"); block.addAuthorityRule("ok(1) <- x($0), $0.any($1 -> $0.any($2 -> $2 == 999))"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertDoesNotThrow(() -> authorizer.authorize(steps(new RunLimits().getMaxSteps()))); } @@ -365,9 +412,10 @@ public void deeplyNestedAnyExceedsTheDefaultBudget() throws Exception { block.addAuthorityRule( "ok(1) <- x($0), $0.any($1 -> $0.any($2 -> $0.any($3 -> $0.any($4 -> $4 == 999))))"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertThrows( Error.TooManySteps.class, () -> authorizer.authorize(steps(new RunLimits().getMaxSteps()))); } @@ -385,10 +433,11 @@ public void exhaustionInsideACheckIsReportedAsTooManySteps() throws Exception { var block = Biscuit.builder(keyPair); block.addAuthorityFact("x([" + TWENTY + "])"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addCheck("check if x($a), $a.any($e -> $e == 19)"); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addCheck("check if x($a), $a.any($e -> $e == 19)"); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertThrows(Error.TooManySteps.class, () -> authorizer.authorize(steps(10))); } @@ -399,10 +448,11 @@ public void exhaustionInsideARejectCheckDoesNotLetAuthorizationThrough() throws var block = Biscuit.builder(keyPair); block.addAuthorityFact("x([" + TWENTY + "])"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addCheck("reject if x($a), $a.any($e -> $e == 19)"); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addCheck("reject if x($a), $a.any($e -> $e == 19)"); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertThrows(Error.TooManySteps.class, () -> authorizer.authorize(steps(10))); } @@ -412,10 +462,11 @@ public void tryOrDoesNotSwallowStepExhaustion() throws Exception { var block = Biscuit.builder(keyPair); block.addAuthorityFact("x([" + TWENTY + "])"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addCheck("reject if x($a), ($a.any($e -> $e == 19)).try_or(false)"); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addCheck("reject if x($a), ($a.any($e -> $e == 19)).try_or(false)"); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertThrows(Error.TooManySteps.class, () -> authorizer.authorize(steps(10))); } @@ -424,10 +475,11 @@ public void findMatchDoesNotSwallowExhaustion() throws Exception { KeyPair keyPair = KeyPair.generate(Schema.PublicKey.Algorithm.Ed25519, rng); var block = Biscuit.builder(keyPair); - Authorizer authorizer = block.build().authorizer(); - authorizer.addCheck("reject if ([" + TWENTY + "].any($e -> $e == 19)).try_or(false)"); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addCheck("reject if ([" + TWENTY + "].any($e -> $e == 19)).try_or(false)"); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertThrows(Error.TooManySteps.class, () -> authorizer.authorize(steps(10))); } @@ -436,10 +488,11 @@ public void checkMatchAllDoesNotSwallowExhaustion() throws Exception { KeyPair keyPair = KeyPair.generate(Schema.PublicKey.Algorithm.Ed25519, rng); var block = Biscuit.builder(keyPair); - Authorizer authorizer = block.build().authorizer(); - authorizer.addCheck("check all ([" + TWENTY + "].any($e -> $e == 19)).try_or(true)"); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addCheck("check all ([" + TWENTY + "].any($e -> $e == 19)).try_or(true)"); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertDoesNotThrow(() -> authorizer.authorize(steps(1_000))); assertThrows(Error.TooManySteps.class, () -> authorizer.authorize(steps(10))); } @@ -454,10 +507,11 @@ public void checkAllDoesNotPassWhenIterationIsCutShort() throws Exception { block.addAuthorityFact("f(" + i + ")"); } - Authorizer authorizer = block.build().authorizer(); - authorizer.addCheck("check all f($a)"); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addCheck("check all f($a)"); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertDoesNotThrow(() -> authorizer.authorize(steps(1_000))); assertThrows(Error.TooManySteps.class, () -> authorizer.authorize(steps(3))); } @@ -469,30 +523,32 @@ public void rejectCheckDeniesWhenThereAreEnoughSteps() throws Exception { var block = Biscuit.builder(keyPair); block.addAuthorityFact("x([" + TWENTY + "])"); - Authorizer authorizer = block.build().authorizer(); - authorizer.addCheck("reject if x($a), $a.any($e -> $e == 19)"); - authorizer.addCheck("reject if ([" + TWENTY + "].any($e -> $e == 19)).try_or(false)"); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addCheck("reject if x($a), $a.any($e -> $e == 19)"); + authorizerBuilder.addCheck("reject if ([" + TWENTY + "].any($e -> $e == 19)).try_or(false)"); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(block.build()); assertThrows(Error.FailedLogic.class, () -> authorizer.authorize(steps(1_000))); } @Test public void expressionOnlyChecksCountTowardTheBudget() throws Exception { // Each check costs 1 any + 20 * (1 call + 1 comparison) = 41 steps. - Authorizer oneCheck = new Authorizer(); - oneCheck.addCheck("check if [" + TWENTY + "].any($e -> $e == 19)"); - oneCheck.addPolicy("allow if true"); - - Authorizer oneCheckUnderBudget = new Authorizer(); - oneCheckUnderBudget.addCheck("check if [" + TWENTY + "].any($e -> $e == 19)"); - oneCheckUnderBudget.addPolicy("allow if true"); + AuthorizerBuilder oneCheckBuilder = + new AuthorizerBuilder() + .addCheck("check if [" + TWENTY + "].any($e -> $e == 19)") + .addPolicy("allow if true"); + Authorizer oneCheck = oneCheckBuilder.buildUnauthenticated(); + Authorizer oneCheckUnderBudget = oneCheckBuilder.buildUnauthenticated(); // The checks share one budget: 41 + 41 = 82 steps. - Authorizer twoChecks = new Authorizer(); - twoChecks.addCheck("check if [" + TWENTY + "].any($e -> $e == 19)"); - twoChecks.addCheck("check if [" + TWENTY + "].any($e -> $e == 19)"); - twoChecks.addPolicy("allow if true"); + Authorizer twoChecks = + new AuthorizerBuilder() + .addCheck("check if [" + TWENTY + "].any($e -> $e == 19)") + .addCheck("check if [" + TWENTY + "].any($e -> $e == 19)") + .addPolicy("allow if true") + .buildUnauthenticated(); assertDoesNotThrow(() -> oneCheck.authorize(steps(41))); assertThrows(Error.TooManySteps.class, () -> oneCheckUnderBudget.authorize(steps(40))); diff --git a/biscuit/src/test/java/org/eclipse/biscuit/token/ThirdPartyTest.java b/biscuit/src/test/java/org/eclipse/biscuit/token/ThirdPartyTest.java index 3eb9b7a0..b1f03101 100644 --- a/biscuit/src/test/java/org/eclipse/biscuit/token/ThirdPartyTest.java +++ b/biscuit/src/test/java/org/eclipse/biscuit/token/ThirdPartyTest.java @@ -5,6 +5,7 @@ package org.eclipse.biscuit.token; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -23,6 +24,7 @@ import org.eclipse.biscuit.error.Error; import org.eclipse.biscuit.error.FailedCheck; import org.eclipse.biscuit.error.LogicError; +import org.eclipse.biscuit.token.builder.AuthorizerBuilder; import org.eclipse.biscuit.token.builder.Block; import org.eclipse.biscuit.token.builder.Scope; import org.junit.jupiter.api.BeforeEach; @@ -84,16 +86,18 @@ public void testRoundTrip() assertEquals(Optional.of(external.getPublicKey()), b2.blockExternalKey(1)); System.out.println("will check the token for resource=file1"); - Authorizer authorizer = deser.authorizer(); - authorizer.addFact("resource(\"file1\")"); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addFact("resource(\"file1\")"); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(deser); authorizer.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); System.out.println("will check the token for resource=file2"); - Authorizer authorizer2 = deser.authorizer(); - authorizer2.addFact("resource(\"file2\")"); - authorizer2.addPolicy("allow if true"); + AuthorizerBuilder authorizer2Builder = new AuthorizerBuilder(); + authorizer2Builder.addFact("resource(\"file2\")"); + authorizer2Builder.addPolicy("allow if true"); + Authorizer authorizer2 = authorizer2Builder.build(deser); try { authorizer2.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); } catch (Error e) { @@ -172,16 +176,18 @@ public void testPublicKeyInterning() System.out.println("TOKEN: " + deser4.print()); System.out.println("will check the token for resource=file1"); - Authorizer authorizer = deser4.authorizer(); - authorizer.addFact("resource(\"file1\")"); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addFact("resource(\"file1\")"); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(deser4); System.out.println("Authorizer world:\n" + authorizer.formatWorld()); authorizer.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); System.out.println("will check the token for resource=file2"); - Authorizer authorizer2 = deser4.authorizer(); - authorizer2.addFact("resource(\"file2\")"); - authorizer2.addPolicy("allow if true"); + AuthorizerBuilder authorizer2Builder = new AuthorizerBuilder(); + authorizer2Builder.addFact("resource(\"file2\")"); + authorizer2Builder.addPolicy("allow if true"); + Authorizer authorizer2 = authorizer2Builder.build(deser4); System.out.println("Authorizer world 2:\n" + authorizer2.formatWorld()); try { @@ -232,17 +238,19 @@ public void testReusedSymbols() assertEquals(b2.print(), deser.print()); System.out.println("will check the token for resource=file1"); - Authorizer authorizer = deser.authorizer(); - authorizer.addFact("resource(\"file1\")"); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addFact("resource(\"file1\")"); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(deser); authorizer.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); System.out.println("Authorizer world:\n" + authorizer.formatWorld()); System.out.println("will check the token for resource=file2"); - Authorizer authorizer2 = deser.authorizer(); - authorizer2.addFact("resource(\"file2\")"); - authorizer2.addPolicy("allow if true"); + AuthorizerBuilder authorizer2Builder = new AuthorizerBuilder(); + authorizer2Builder.addFact("resource(\"file2\")"); + authorizer2Builder.addPolicy("allow if true"); + Authorizer authorizer2 = authorizer2Builder.build(deser); try { authorizer2.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); } catch (Error e) { @@ -304,8 +312,9 @@ public void testDeterministicECDSA() assertEquals(b1.print(), b2.print()); // Make sure that the token is still valid - Authorizer authorizer = b1.authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(b1); authorizer.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); } @@ -374,9 +383,10 @@ public void testThirdPartyBlockLevelScopeRejectsFactFromUntrustedKey() Biscuit token = buildTokenForBlockLevelScopeTest(root, evil, idp, partner, evil); - Authorizer authorizer = token.authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(token); Error.FailedLogic e = assertThrows( Error.FailedLogic.class, @@ -406,8 +416,36 @@ public void testThirdPartyBlockLevelScopeAcceptsFactFromTrustedKey() Biscuit token = buildTokenForBlockLevelScopeTest(root, evil, idp, partner, partner); - Authorizer authorizer = token.authorizer(); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(token); authorizer.authorize(new RunLimits(500, 100, Duration.ofSeconds(5))); } + + @Test + public void clonedAuthorizerKeepsItsScopes() throws Exception { + final KeyPair root = KeyPair.generate(Schema.PublicKey.Algorithm.Ed25519, rng); + final KeyPair external = KeyPair.generate(Schema.PublicKey.Algorithm.Ed25519, rng); + + Block authority = new Block(); + authority.addFact("right(\"read\")"); + Biscuit b1 = Biscuit.make(rng, root, authority.build()); + + Block thirdParty = new Block(); + thirdParty.addFact("group(\"admin\")"); + ThirdPartyBlockContents response = + b1.thirdPartyRequest().createBlock(external, thirdParty).getOk(); + Biscuit b2 = b1.appendThirdPartyBlock(external.getPublicKey(), response); + + // the third-party fact is only visible through the authorizer scope + Authorizer authorizer = + new AuthorizerBuilder() + .addScope(Scope.publicKey(external.getPublicKey())) + .addPolicy("allow if group(\"admin\")") + .build(b2); + Authorizer cloned = authorizer.clone(); + + assertDoesNotThrow(() -> authorizer.authorize(new RunLimits(500, 100, Duration.ofSeconds(5)))); + assertDoesNotThrow(() -> cloned.authorize(new RunLimits(500, 100, Duration.ofSeconds(5)))); + } } diff --git a/biscuit/src/test/java/org/eclipse/biscuit/token/UnverifiedBiscuitTest.java b/biscuit/src/test/java/org/eclipse/biscuit/token/UnverifiedBiscuitTest.java index 76b0770d..9d50f493 100644 --- a/biscuit/src/test/java/org/eclipse/biscuit/token/UnverifiedBiscuitTest.java +++ b/biscuit/src/test/java/org/eclipse/biscuit/token/UnverifiedBiscuitTest.java @@ -21,6 +21,7 @@ import org.eclipse.biscuit.error.Error; import org.eclipse.biscuit.error.FailedCheck; import org.eclipse.biscuit.error.LogicError; +import org.eclipse.biscuit.token.builder.AuthorizerBuilder; import org.eclipse.biscuit.token.builder.Block; import org.eclipse.biscuit.token.builder.Utils; import org.junit.jupiter.api.BeforeEach; @@ -130,19 +131,21 @@ public void testBasic() // check System.out.println("will check the token for resource=file1 and operation=read"); - Authorizer authorizer = finalBiscuit.authorizer(); - authorizer.addFact("resource(\"file1\")"); - authorizer.addFact("operation(\"read\")"); - authorizer.addPolicy("allow if true"); + AuthorizerBuilder authorizerBuilder = new AuthorizerBuilder(); + authorizerBuilder.addFact("resource(\"file1\")"); + authorizerBuilder.addFact("operation(\"read\")"); + authorizerBuilder.addPolicy("allow if true"); + Authorizer authorizer = authorizerBuilder.build(finalBiscuit); authorizer.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); System.out.println("will check the token for resource=file2 and operation=write"); - Authorizer authorizer2 = finalBiscuit.authorizer(); - authorizer2.addFact("resource(\"file2\")"); - authorizer2.addFact("operation(\"write\")"); - authorizer2.addPolicy("allow if true"); + AuthorizerBuilder authorizer2Builder = new AuthorizerBuilder(); + authorizer2Builder.addFact("resource(\"file2\")"); + authorizer2Builder.addFact("operation(\"write\")"); + authorizer2Builder.addPolicy("allow if true"); + Authorizer authorizer2 = authorizer2Builder.build(finalBiscuit); try { authorizer2.authorize(new RunLimits(500, 100, Duration.ofMillis(500))); } catch (Error e) {