Skip to content

datalog components parser helper and authorization helper #120

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/main/java/org/biscuitsec/biscuit/token/Authorizer.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import static io.vavr.API.Right;

import io.vavr.Tuple2;
import io.vavr.Tuple5;
import io.vavr.control.Either;
import io.vavr.control.Option;
import java.time.Instant;
Expand Down Expand Up @@ -203,6 +204,39 @@ public Authorizer addToken(Biscuit token) throws Error.FailedLogic {
return this;
}

public Either<Map<Integer, List<Error>>, Authorizer> addDatalog(String s) {
Either<Map<Integer, List<org.biscuitsec.biscuit.token.builder.parser.Error>>, Tuple5<List<org.biscuitsec.biscuit.token.builder.Fact>, List<org.biscuitsec.biscuit.token.builder.Rule>, List<org.biscuitsec.biscuit.token.builder.Check>, List<org.biscuitsec.biscuit.token.builder.Scope>, List<Policy>>> result = Parser
.datalogComponents(s);

if (result.isLeft()) {
Map<Integer, List<org.biscuitsec.biscuit.token.builder.parser.Error>> errors = result.getLeft();
Map<Integer, List<Error>> errorMap = new HashMap<>();
for (Map.Entry<Integer, List<org.biscuitsec.biscuit.token.builder.parser.Error>> entry : errors.entrySet()) {
List<Error> errorsList = new ArrayList<>();
for (org.biscuitsec.biscuit.token.builder.parser.Error error : entry.getValue()) {
errorsList.add(new Error.Parser(error));
}
errorMap.put(entry.getKey(), errorsList);
}
return Either.left(errorMap);
}

Tuple5<List<org.biscuitsec.biscuit.token.builder.Fact>, List<org.biscuitsec.biscuit.token.builder.Rule>, List<org.biscuitsec.biscuit.token.builder.Check>, List<org.biscuitsec.biscuit.token.builder.Scope>, List<Policy>> components = result
.get();
components._1.forEach(this::addFact);
components._2.forEach(this::addRule);
components._3.forEach(this::addCheck);
components._4.forEach(this::addScope);
components._5.forEach(this::addPolicy);

return Either.right(this);
}

public Authorizer addScope(org.biscuitsec.biscuit.token.builder.Scope s) {
this.scopes.add(s.convert(symbolTable));
return this;
}

public Authorizer addFact(org.biscuitsec.biscuit.token.builder.Fact fact) {
world.addFact(Origin.authorizer(), fact.convert(symbolTable));
return this;
Expand Down
147 changes: 97 additions & 50 deletions src/main/java/org/biscuitsec/biscuit/token/builder/parser/Parser.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import biscuit.format.schema.Schema;
import io.vavr.Tuple2;
import io.vavr.Tuple5;
import io.vavr.Tuple4;
import io.vavr.collection.Stream;
import io.vavr.control.Either;
Expand Down Expand Up @@ -34,16 +35,20 @@ private Parser() {}
*
* <p>If one succeeds it returns Right(Block) else it returns a Map[lineNumber, List[Error]]
*
* @param index block index
* @param s datalog string to parse
* @return Either<Map<Integer, List<Error>>, Block>
* @return Either<Map<Integer, List<Error>>, Tuple5<List<Fact>, List<Rule>,
* List<Check>, List<Scope>, List<Policy>>>
*/
public static Either<Map<Integer, List<Error>>, Block> datalog(long index, String s) {
Block blockBuilder = new Block();
public static Either<Map<Integer, List<Error>>, Tuple5<List<Fact>, List<Rule>, List<Check>, List<Scope>, List<Policy>>> datalogComponents(
String s) {
List<Fact> facts = new ArrayList<>();
List<Rule> rules = new ArrayList<>();
List<Check> checks = new ArrayList<>();
List<Scope> scopes = new ArrayList<>();
List<Policy> policies = new ArrayList<>();

// empty block code
if (s.isEmpty()) {
return Either.right(blockBuilder);
return Either.right(new Tuple5<>(facts, rules, checks, scopes, policies));
}

Map<Integer, List<Error>> errors = new HashMap<>();
Expand All @@ -61,58 +66,67 @@ public static Either<Map<Integer, List<Error>>, Block> datalog(long index, Strin
List<Error> lineErrors = new ArrayList<>();

boolean parsed = false;
parsed =
rule(code)
.fold(
e -> {
lineErrors.add(e);
return false;
},
r -> {
blockBuilder.addRule(r._2);
return true;
});
parsed = rule(code)
.fold(
e -> {
lineErrors.add(e);
return false;
},
r -> {
rules.add(r._2);
return true;
});

if (!parsed) {
parsed = fact(code)
.fold(
e -> {
lineErrors.add(e);
return false;
},
r -> {
facts.add(r._2);
return true;
});
}

if (!parsed) {
parsed =
fact(code)
.fold(
e -> {
lineErrors.add(e);
return false;
},
r -> {
blockBuilder.addFact(r._2);
return true;
});
parsed = check(code)
.fold(
e -> {
lineErrors.add(e);
return false;
},
r -> {
checks.add(r._2);
return true;
});
}

if (!parsed) {
parsed =
check(code)
.fold(
e -> {
lineErrors.add(e);
return false;
},
r -> {
blockBuilder.addCheck(r._2);
return true;
});
parsed = scope(code)
.fold(
e -> {
lineErrors.add(e);
return false;
},
r -> {
scopes.add(r._2);
return true;
});
}

if (!parsed) {
parsed =
scope(code)
.fold(
e -> {
lineErrors.add(e);
return false;
},
r -> {
blockBuilder.addScope(r._2);
return true;
});
parsed = policy(code)
.fold(
e -> {
lineErrors.add(e);
return false;
},
r -> {
policies.add(r._2);
return true;
});
}

if (!parsed) {
Expand All @@ -127,6 +141,39 @@ public static Either<Map<Integer, List<Error>>, Block> datalog(long index, Strin
return Either.left(errors);
}

return Either.right(new Tuple5<>(facts, rules, checks, scopes, policies));
}

/**
* Takes a datalog string with <code>\n</code> as datalog line separator. It
* tries to parse each
* line using fact, rule, check and scope sequentially.
*
* <p>
* If one succeeds it returns Right(Block) else it returns a Map[lineNumber,
* List[Error]]
*
* @param index block index
* @param s datalog string to parse
* @return Either<Map<Integer, List<Error>>, Block>
*/
public static Either<Map<Integer, List<Error>>, Block> datalog(long index, String s) {
Block blockBuilder = new Block();

Either<Map<Integer, List<Error>>, Tuple5<List<Fact>, List<Rule>, List<Check>, List<Scope>, List<Policy>>> result = datalogComponents(
s);

if (result.isLeft()) {
return Either.left(result.getLeft());
}

Tuple5<List<Fact>, List<Rule>, List<Check>, List<Scope>, List<Policy>> components = result.get();

components._1.forEach(blockBuilder::addFact);
components._2.forEach(blockBuilder::addRule);
components._3.forEach(blockBuilder::addCheck);
components._4.forEach(blockBuilder::addScope);

return Either.right(blockBuilder);
}

Expand Down
29 changes: 29 additions & 0 deletions src/test/java/org/biscuitsec/biscuit/token/AuthorizerTest.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package org.biscuitsec.biscuit.token;

import static org.biscuitsec.biscuit.token.builder.Utils.constrainedRule;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;

import biscuit.format.schema.Schema;
Expand Down Expand Up @@ -73,6 +75,33 @@ public void testPuttingSomeFactsInBiscuitAndGettingThemBackOutAgain() throws Exc
((Term.Set) permsTerm).getValue());
}

@Test
public void testDatalogAuthorizer() throws Exception {
KeyPair keypair = KeyPair.generate(Schema.PublicKey.Algorithm.Ed25519, new SecureRandom());

Biscuit token = Biscuit.builder(keypair)
.addAuthorityFact("email(\"[email protected]\")")
.addAuthorityFact("id(123)")
.addAuthorityFact("enabled(true)")
.addAuthorityFact("perms([1,2,3])")
.build();

Authorizer authorizer = Biscuit.fromBase64Url(token.serializeBase64Url(), keypair.getPublicKey())
.verify(keypair.getPublicKey())
.authorizer();

String l0 = "right($email) <- email($email)";
String l1 = "check if right(\"[email protected]\")";
String l2 = "allow if true";
String datalog = String.join(";", Arrays.asList(l0, l1, l2));
authorizer.addDatalog(datalog);

assertDoesNotThrow(() -> authorizer.authorize());

Term emailTerm = queryFirstResult(authorizer, "right($address) <- email($address)");
assertEquals("[email protected]", ((Term.Str) emailTerm).getValue());
}

private static Term queryFirstResult(Authorizer authorizer, String query) throws Error {
return authorizer.query(query).iterator().next().terms().get(0);
}
Expand Down