diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Check.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Check.java index 438a718f..49767fdc 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Check.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Check.java @@ -14,6 +14,7 @@ import java.util.Objects; import org.eclipse.biscuit.error.Error; import org.eclipse.biscuit.error.Result; +import org.eclipse.biscuit.token.DeserializationLimit; public final class Check { public enum Kind { @@ -62,7 +63,8 @@ public Schema.CheckV2 serialize() { return b.build(); } - public static Result deserializeV2(Schema.CheckV2 check) { + public static Result deserializeV2( + Schema.CheckV2 check, DeserializationLimit.PerBlock limits, SymbolTable symbols) { ArrayList queries = new ArrayList<>(); Kind kind; @@ -81,8 +83,20 @@ public static Result deserializeV2(Schema.CheckV2 chec break; } + var allowedKinds = limits.getAllowedCheckKinds(); + if (allowedKinds != null && !allowedKinds.contains(kind)) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.CHECK_KIND_NOT_ALLOWED)); + } + if (check.getQueriesCount() > limits.getMaxQueriesPerCheck()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.TOO_MANY_QUERIES)); + } + for (Schema.RuleV2 query : check.getQueriesList()) { - var res = Rule.deserializeV2(query); + var res = Rule.deserializeV2(query, limits, symbols); if (res.isErr()) { return Result.err(res.getErr()); } else { diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Fact.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Fact.java index 0986c7d3..8bc45874 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Fact.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Fact.java @@ -10,6 +10,7 @@ import java.util.Objects; import org.eclipse.biscuit.error.Error; import org.eclipse.biscuit.error.Result; +import org.eclipse.biscuit.token.DeserializationLimit; public final class Fact { private final Predicate predicate; @@ -56,8 +57,9 @@ public Schema.FactV2 serialize() { return Schema.FactV2.newBuilder().setPredicate(this.predicate.serialize()).build(); } - public static Result deserializeV2(Schema.FactV2 fact) { - var res = Predicate.deserializeV2(fact.getPredicate()); + public static Result deserializeV2( + Schema.FactV2 fact, DeserializationLimit.PerBlock limits, SymbolTable symbols) { + var res = Predicate.deserializeV2(fact.getPredicate(), limits, symbols); if (res.isErr()) { return Result.err(res.getErr()); } else { diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/MapKey.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/MapKey.java index c9008b0e..86253fea 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/MapKey.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/MapKey.java @@ -3,19 +3,47 @@ import biscuit.format.schema.Schema; import org.eclipse.biscuit.error.Error; import org.eclipse.biscuit.error.Result; +import org.eclipse.biscuit.token.DeserializationLimit; public abstract class MapKey extends Term { public abstract Schema.MapKey serializeMapKey(); public abstract org.eclipse.biscuit.token.builder.MapKey toMapKey(SymbolTable symbolTable); - public static Result deserializeMapKeyEnum(Schema.MapKey mapKey) { - if (mapKey.hasInteger()) { - return Term.Integer.deserializeMapKey(mapKey); - } else if (mapKey.hasString()) { - return Term.Str.deserializeMapKey(mapKey); - } else { - return Result.err(new Error.FormatError.DeserializationError("invalid MapKey kind")); + public static Result deserializeMapKeyEnum( + Schema.MapKey mapKey, DeserializationLimit.PerBlock limits, SymbolTable symbols) { + var allowedTypes = limits.getAllowedMapKeyTypes(); + var type = mapKeyType(mapKey.getContentCase()); + if (allowedTypes != null && type != null && !allowedTypes.contains(type)) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.MAP_KEY_TYPE_NOT_ALLOWED)); + } + + switch (mapKey.getContentCase()) { + case INTEGER: + return Term.Integer.deserializeMapKey(mapKey); + case STRING: + var stringError = limits.checkString(symbols, mapKey.getString()); + if (stringError != null) { + return Result.err(stringError); + } + return Term.Str.deserializeMapKey(mapKey); + default: + return Result.err(new Error.FormatError.DeserializationError("invalid MapKey kind")); + } + } + + private static DeserializationLimit.MapKeyType mapKeyType(Schema.MapKey.ContentCase content) { + switch (content) { + case INTEGER: + return DeserializationLimit.MapKeyType.INTEGER; + case STRING: + return DeserializationLimit.MapKeyType.STRING; + case CONTENT_NOT_SET: + return null; + default: + throw new IllegalStateException("unhandled map key kind " + content); } } } diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Predicate.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Predicate.java index 7d114b89..0d18a996 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Predicate.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Predicate.java @@ -13,6 +13,7 @@ import java.util.stream.Collectors; import org.eclipse.biscuit.error.Error; import org.eclipse.biscuit.error.Result; +import org.eclipse.biscuit.token.DeserializationLimit; public final class Predicate { private final long name; @@ -92,10 +93,21 @@ public Schema.PredicateV2 serialize() { return builder.build(); } - public static Result deserializeV2(Schema.PredicateV2 predicate) { + public static Result deserializeV2( + Schema.PredicateV2 predicate, DeserializationLimit.PerBlock limits, SymbolTable symbols) { + if (predicate.getTermsCount() > limits.getMaxTermsPerPredicate()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.TOO_MANY_TERMS)); + } + var nameError = limits.checkName(symbols, predicate.getName()); + if (nameError != null) { + return Result.err(nameError); + } + ArrayList terms = new ArrayList<>(); for (Schema.TermV2 id : predicate.getTermsList()) { - var res = Term.deserializeEnumV2(id); + var res = Term.deserializeEnumV2(id, limits, symbols); if (res.isErr()) { return Result.err(res.getErr()); } else { 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 de826b81..ff595b49 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 @@ -20,6 +20,7 @@ import org.eclipse.biscuit.datalog.expressions.Expression; import org.eclipse.biscuit.error.Error; import org.eclipse.biscuit.error.Result; +import org.eclipse.biscuit.token.DeserializationLimit; public final class Rule { private final Predicate head; @@ -224,10 +225,22 @@ public Schema.RuleV2 serialize() { return b.build(); } - public static Result deserializeV2(Schema.RuleV2 rule) { + public static Result deserializeV2( + Schema.RuleV2 rule, DeserializationLimit.PerBlock limits, SymbolTable symbols) { + if (rule.getBodyCount() > limits.getMaxPredicatesPerBody()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.TOO_MANY_PREDICATES)); + } + if (rule.getExpressionsCount() > limits.getMaxExpressionsPerBody()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.TOO_MANY_EXPRESSIONS)); + } + ArrayList body = new ArrayList<>(); for (Schema.PredicateV2 predicate : rule.getBodyList()) { - var res = Predicate.deserializeV2(predicate); + var res = Predicate.deserializeV2(predicate, limits, symbols); if (res.isErr()) { return Result.err(res.getErr()); } else { @@ -237,7 +250,7 @@ public static Result deserializeV2(Schema.RuleV2 rule) ArrayList expressions = new ArrayList<>(); for (Schema.ExpressionV2 expression : rule.getExpressionsList()) { - var res = Expression.deserializeV2(expression); + var res = Expression.deserializeV2(expression, limits, symbols); if (res.isErr()) { return Result.err(res.getErr()); } else { @@ -247,7 +260,7 @@ public static Result deserializeV2(Schema.RuleV2 rule) ArrayList scopes = new ArrayList<>(); for (Schema.Scope scope : rule.getScopeList()) { - var res = Scope.deserialize(scope); + var res = Scope.deserialize(scope, limits, symbols); if (res.isErr()) { return Result.err(res.getErr()); } else { @@ -255,7 +268,7 @@ public static Result deserializeV2(Schema.RuleV2 rule) } } - var res = Predicate.deserializeV2(rule.getHead()); + var res = Predicate.deserializeV2(rule.getHead(), limits, symbols); if (res.isErr()) { Error.FormatError e = res.getErr(); return Result.err(e); diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Scope.java b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Scope.java index 0d573352..c801eb81 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Scope.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/datalog/Scope.java @@ -6,8 +6,11 @@ package org.eclipse.biscuit.datalog; import biscuit.format.schema.Schema; +import java.util.Optional; +import org.eclipse.biscuit.crypto.PublicKey; import org.eclipse.biscuit.error.Error; import org.eclipse.biscuit.error.Result; +import org.eclipse.biscuit.token.DeserializationLimit; public final class Scope { public enum Kind { @@ -63,6 +66,47 @@ public Schema.Scope serialize() { return b.build(); } + public static Result deserialize( + Schema.Scope scope, DeserializationLimit.PerBlock limits, SymbolTable symbols) { + var res = deserialize(scope); + if (res.isErr()) { + return res; + } + + var allowedScopes = limits.getAllowedTrustingScopes(); + if (allowedScopes != null) { + DeserializationLimit.TrustedScopeKind kind; + switch (res.getOk().kind()) { + case Authority: + kind = DeserializationLimit.TrustedScopeKind.AUTHORITY; + break; + case Previous: + kind = DeserializationLimit.TrustedScopeKind.PREVIOUS; + break; + case PublicKey: + long index = res.getOk().getPublicKey(); + var key = + index >= 0 && index <= java.lang.Integer.MAX_VALUE + ? symbols.getPublicKey((int) index) + : Optional.empty(); + if (key.isEmpty()) { + return Result.err(new Error.FormatError.UnknownPublicKey()); + } + kind = DeserializationLimit.TrustedScopeKind.publicKey(key.get().getAlgorithm()); + break; + default: + // a new kind of scope has to be mapped to a TrustedScopeKind here + throw new IllegalStateException("unhandled scope kind " + res.getOk().kind()); + } + if (!allowedScopes.contains(kind)) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.TRUSTED_SCOPE_NOT_ALLOWED)); + } + } + return res; + } + public static Result deserialize(Schema.Scope scope) { if (scope.hasPublicKey()) { long publicKey = scope.getPublicKey(); 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 a23fbd4f..e770b5b5 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 @@ -17,6 +17,7 @@ import org.eclipse.biscuit.datalog.expressions.Op; import org.eclipse.biscuit.error.Error; import org.eclipse.biscuit.error.Result; +import org.eclipse.biscuit.token.DeserializationLimit; public abstract class Term extends Op { @@ -60,30 +61,85 @@ public String print(Deque stack, SymbolTable symbols) { return s; } - public static Result deserializeEnumV2(Schema.TermV2 term) { - if (term.hasDate()) { - return Date.deserializeV2(term); - } else if (term.hasInteger()) { - return Integer.deserializeV2(term); - } else if (term.hasString()) { - return Str.deserializeV2(term); - } else if (term.hasBytes()) { - return Bytes.deserializeV2(term); - } else if (term.hasVariable()) { - return Variable.deserializeV2(term); - } else if (term.hasBool()) { - return Bool.deserializeV2(term); - } else if (term.hasSet()) { - return Set.deserializeV2(term); - } else if (term.hasNull()) { - return Null.deserializeV2(term); - } else if (term.hasArray()) { - return Array.deserializeV2(term); - } else if (term.hasMap()) { - return Map.deserializeV2(term); - } else { + public static Result deserializeEnumV2( + Schema.TermV2 term, DeserializationLimit.PerBlock limits, SymbolTable symbols) { + var allowedTypes = limits.getAllowedTermTypes(); + // a variable is not a value, so it has no type + var type = termType(term.getContentCase()); + if (allowedTypes != null && type != null && !allowedTypes.contains(type)) { return Result.err( - new Error.FormatError.DeserializationError("invalid Term kind: term.getKind()")); + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.TERM_TYPE_NOT_ALLOWED)); + } + + switch (term.getContentCase()) { + case DATE: + return Date.deserializeV2(term); + case INTEGER: + return Integer.deserializeV2(term); + case STRING: + var stringError = limits.checkString(symbols, term.getString()); + if (stringError != null) { + return Result.err(stringError); + } + return Str.deserializeV2(term); + case BYTES: + if (term.getBytes().size() > limits.getMaxBytesLength()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.BYTES_TOO_LONG)); + } + return Bytes.deserializeV2(term); + case VARIABLE: + var nameError = + limits.checkName(symbols, java.lang.Integer.toUnsignedLong(term.getVariable())); + if (nameError != null) { + return Result.err(nameError); + } + return Variable.deserializeV2(term); + case BOOL: + return Bool.deserializeV2(term); + case SET: + return Set.deserializeV2(term, limits, symbols); + case NULL: + return Null.deserializeV2(term); + case ARRAY: + return Array.deserializeV2(term, limits, symbols); + case MAP: + return Map.deserializeV2(term, limits, symbols); + default: + return Result.err( + new Error.FormatError.DeserializationError( + "invalid Term kind: " + term.getContentCase())); + } + } + + private static DeserializationLimit.TermType termType(Schema.TermV2.ContentCase content) { + switch (content) { + case INTEGER: + return DeserializationLimit.TermType.INTEGER; + case STRING: + return DeserializationLimit.TermType.STRING; + case DATE: + return DeserializationLimit.TermType.DATE; + case BYTES: + return DeserializationLimit.TermType.BYTES; + case BOOL: + return DeserializationLimit.TermType.BOOL; + case SET: + return DeserializationLimit.TermType.SET; + case NULL: + return DeserializationLimit.TermType.NULL; + case ARRAY: + return DeserializationLimit.TermType.ARRAY; + case MAP: + return DeserializationLimit.TermType.MAP; + case VARIABLE: + case CONTENT_NOT_SET: + // not values, so they have no type + return null; + default: + throw new IllegalStateException("unhandled term kind " + content); } } @@ -621,7 +677,8 @@ public String typeOf() { return "array"; } - public static Result deserializeV2(Schema.TermV2 term) { + public static Result deserializeV2( + Schema.TermV2 term, DeserializationLimit.PerBlock limits, SymbolTable symbols) { if (!term.hasArray()) { return Result.err( new Error.FormatError.DeserializationError("invalid Term kind, expected array")); @@ -629,8 +686,14 @@ public static Result deserializeV2(Schema.TermV2 term) java.util.List values = new ArrayList<>(); Schema.Array s = term.getArray(); + if (s.getArrayCount() > limits.getMaxArrayLength()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.ARRAY_TOO_LONG)); + } + for (Schema.TermV2 l : s.getArrayList()) { - var res = Term.deserializeEnumV2(l); + var res = Term.deserializeEnumV2(l, limits, symbols); if (res.isErr()) { return Result.err(res.getErr()); } else { @@ -726,7 +789,8 @@ public String typeOf() { return "map"; } - public static Result deserializeV2(Schema.TermV2 term) { + public static Result deserializeV2( + Schema.TermV2 term, DeserializationLimit.PerBlock limits, SymbolTable symbols) { if (!term.hasMap()) { return Result.err( new Error.FormatError.DeserializationError("invalid Term kind, expected map")); @@ -734,12 +798,18 @@ public static Result deserializeV2(Schema.TermV2 term) java.util.HashMap values = new HashMap<>(); Schema.Map s = term.getMap(); + if (s.getEntriesCount() > limits.getMaxMapLength()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.MAP_TOO_LONG)); + } + for (Schema.MapEntry l : s.getEntriesList()) { - var resKey = MapKey.deserializeMapKeyEnum(l.getKey()); + var resKey = MapKey.deserializeMapKeyEnum(l.getKey(), limits, symbols); if (resKey.isErr()) { return Result.err(resKey.getErr()); } - var resValue = Term.deserializeEnumV2(l.getValue()); + var resValue = Term.deserializeEnumV2(l.getValue(), limits, symbols); if (resValue.isErr()) { return Result.err(resValue.getErr()); } @@ -842,7 +912,8 @@ public String typeOf() { return "set"; } - public static Result deserializeV2(Schema.TermV2 term) { + public static Result deserializeV2( + Schema.TermV2 term, DeserializationLimit.PerBlock limits, SymbolTable symbols) { if (!term.hasSet()) { return Result.err( new Error.FormatError.DeserializationError("invalid Term kind, expected set")); @@ -850,8 +921,14 @@ public static Result deserializeV2(Schema.TermV2 term) java.util.HashSet values = new HashSet<>(); Schema.TermSet s = term.getSet(); + if (s.getSetCount() > limits.getMaxSetLength()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.SET_TOO_LONG)); + } + for (Schema.TermV2 l : s.getSetList()) { - var res = Term.deserializeEnumV2(l); + var res = Term.deserializeEnumV2(l, limits, symbols); if (res.isErr()) { return Result.err(res.getErr()); } else { 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 34b92d93..e771db94 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 @@ -18,6 +18,7 @@ import org.eclipse.biscuit.datalog.Term; import org.eclipse.biscuit.error.Error; import org.eclipse.biscuit.error.Result; +import org.eclipse.biscuit.token.DeserializationLimit; public final class Expression { private final ArrayList ops; @@ -72,11 +73,14 @@ public Schema.ExpressionV2 serialize() { return b.build(); } - public static Result deserializeV2(Schema.ExpressionV2 e) { + public static Result deserializeV2( + Schema.ExpressionV2 e, DeserializationLimit.PerBlock limits, SymbolTable symbols) { ArrayList ops = new ArrayList<>(); + // closures share the limit with the expression they are nested in + int[] remainingOps = {limits.getMaxOpsPerExpression()}; for (Schema.Op op : e.getOpsList()) { - var res = Op.deserializeV2(op); + var res = Op.deserializeV2(op, limits, symbols, remainingOps); if (res.isErr()) { return Result.err(res.getErr()); 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 9a83116f..2f618544 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 @@ -21,6 +21,7 @@ import org.eclipse.biscuit.error.Error; import org.eclipse.biscuit.error.Result; import org.eclipse.biscuit.regex.PatternMatcher; +import org.eclipse.biscuit.token.DeserializationLimit; import org.eclipse.biscuit.token.builder.Expression; public abstract class Op { @@ -35,21 +36,65 @@ public abstract void evaluate( public abstract Schema.Op serialize(); - public static Result deserializeV2(Schema.Op op) { + public static Result deserializeV2( + Schema.Op op, DeserializationLimit.PerBlock limits, SymbolTable symbols, int[] remainingOps) { + if (remainingOps[0] <= 0) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.TOO_MANY_OPS)); + } + remainingOps[0]--; + if (op.hasValue()) { - var res = Term.deserializeEnumV2(op.getValue()); + var res = Term.deserializeEnumV2(op.getValue(), limits, symbols); return res.isOk() ? Result.ok(res.getOk()) : Result.err(res.getErr()); } else if (op.hasUnary()) { - return Op.Unary.deserializeV2(op.getUnary()); + return Op.Unary.deserializeV2(op.getUnary(), limits, symbols); } else if (op.hasBinary()) { - return Op.Binary.deserializeV1(op.getBinary()); + return Op.Binary.deserializeV1(op.getBinary(), limits, symbols); } else if (op.hasClosure()) { - return Op.Closure.deserializeV1(op.getClosure()); + if (!limits.getAllowClosures()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.CLOSURES_NOT_ALLOWED)); + } + return Op.Closure.deserializeV1(op.getClosure(), limits, symbols, remainingOps); } else { return Result.err(new Error.FormatError.DeserializationError("invalid unary operation")); } } + /** + * Checks the name of a foreign function: it must not be too long and, if the allowed functions + * are restricted, must be one of them + * + * @return the error if the call is not allowed, or null + */ + private static Error.FormatError checkExternalFunction( + long nameIndex, + DeserializationLimit.PerBlock limits, + SymbolTable symbols, + java.util.Set allowedFunctions) { + var nameError = limits.checkName(symbols, nameIndex); + if (nameError != null) { + return nameError; + } + if (allowedFunctions != null) { + var name = + nameIndex >= 0 && nameIndex <= java.lang.Integer.MAX_VALUE + ? symbols.getSymbol((int) nameIndex) + : Optional.empty(); + if (name.isEmpty()) { + return new Error.FormatError.DeserializationError("unknown symbol " + nameIndex); + } + if (!allowedFunctions.contains(name.get())) { + return new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.EXTERNAL_FUNCTION_NOT_ALLOWED); + } + } + return null; + } + public enum UnaryOp { Negate, Parens, @@ -172,6 +217,29 @@ public Schema.Op serialize() { return b.build(); } + public static Result deserializeV2( + Schema.OpUnary op, DeserializationLimit.PerBlock limits, SymbolTable symbols) { + if (op.getKind() == Schema.OpUnary.Kind.Ffi && op.hasFfiName()) { + var error = + checkExternalFunction( + op.getFfiName(), limits, symbols, limits.getAllowedUnaryExternalFunctions()); + if (error != null) { + return Result.err(error); + } + } + + var res = deserializeV2(op); + var allowedOps = limits.getAllowedUnaryOps(); + if (allowedOps != null + && res.isOk() + && !allowedOps.contains(((Op.Unary) res.getOk()).getOp())) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.UNARY_OPERATION_NOT_ALLOWED)); + } + return res; + } + public static Result deserializeV2(Schema.OpUnary op) { switch (op.getKind()) { case Negate: @@ -975,6 +1043,29 @@ public Schema.Op serialize() { return b.build(); } + public static Result deserializeV1( + Schema.OpBinary op, DeserializationLimit.PerBlock limits, SymbolTable symbols) { + if (op.getKind() == Schema.OpBinary.Kind.Ffi && op.hasFfiName()) { + var error = + checkExternalFunction( + op.getFfiName(), limits, symbols, limits.getAllowedBinaryExternalFunctions()); + if (error != null) { + return Result.err(error); + } + } + + var res = deserializeV1(op); + var allowedOps = limits.getAllowedBinaryOps(); + if (allowedOps != null + && res.isOk() + && !allowedOps.contains(((Op.Binary) res.getOk()).getOp())) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.BINARY_OPERATION_NOT_ALLOWED)); + } + return res; + } + public static Result deserializeV1(Schema.OpBinary op) { switch (op.getKind()) { case LessThan: @@ -1175,16 +1266,24 @@ public Schema.Op serialize() { return b.build(); } - public static Result deserializeV1(Schema.OpClosure closure) { + public static Result deserializeV1( + Schema.OpClosure closure, + DeserializationLimit.PerBlock limits, + SymbolTable symbols, + int[] remainingOps) { ArrayList params = new ArrayList<>(); ArrayList ops = new ArrayList<>(); - for (long param : closure.getParamsList()) { - params.add(param); + for (int param : closure.getParamsList()) { + var nameError = limits.checkName(symbols, java.lang.Integer.toUnsignedLong(param)); + if (nameError != null) { + return Result.err(nameError); + } + params.add((long) param); } for (Schema.Op op : closure.getOpsList()) { - var res = Op.deserializeV2(op); + var res = Op.deserializeV2(op, limits, symbols, remainingOps); if (res.isErr()) { return Result.err(res.getErr()); } else { diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/error/Error.java b/biscuit-core/src/main/java/org/eclipse/biscuit/error/Error.java index 2c200bb9..f0c8b975 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/error/Error.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/error/Error.java @@ -195,6 +195,105 @@ public JsonNode toJson() { } } + /** The token contains a feature which is not permitted by the DeserializationLimit it was checked with */ + public static final class DeserializationLimitError extends FormatError { + /** The way in which a token violated the DeserializationLimit */ + public enum Reason { + TOKEN_TOO_LARGE("Biscuit is too large"), + BLOCK_TOO_LARGE("Biscuit Datalog block is too large"), + TOO_MANY_BLOCKS("Biscuit contains too many blocks"), + TOO_MANY_FACTS("Biscuit block contains too many facts"), + TOO_MANY_RULES("Biscuit block contains too many rules"), + TOO_MANY_CHECKS("Biscuit block contains too many checks"), + TOO_MANY_SYMBOLS("Biscuit block contains too many symbols"), + TOO_MANY_PUBLIC_KEYS("Biscuit block contains too many public keys"), + TOO_MANY_QUERIES("Biscuit check contains too many queries"), + TOO_MANY_PREDICATES("Biscuit rule or query body contains too many predicates"), + TOO_MANY_EXPRESSIONS("Biscuit rule or query body contains too many expressions"), + TOO_MANY_OPS("Biscuit expression contains too many operations"), + TOO_MANY_TERMS("Biscuit fact or predicate contains too many terms"), + NAME_TOO_LONG("Biscuit contains a name which is too long"), + STRING_TOO_LONG("Biscuit contains a string which is too long"), + BYTES_TOO_LONG("Biscuit contains a bytes value which is too long"), + SET_TOO_LONG("Biscuit contains a set which is too long"), + ARRAY_TOO_LONG("Biscuit contains an array which is too long"), + MAP_TOO_LONG("Biscuit contains a map which is too long"), + CLOSURES_NOT_ALLOWED("Biscuit contains closures, which are not allowed"), + SIGNATURE_VERSION_TOO_LOW("Biscuit block uses a signature version which is too low"), + INTERNAL_SIGNING_ALGORITHM_NOT_ALLOWED( + "Biscuit block is signed with an algorithm which is not allowed"), + EXTERNAL_SIGNING_ALGORITHM_NOT_ALLOWED( + "Biscuit block has a third party signature with an algorithm which is not allowed"), + BINARY_OPERATION_NOT_ALLOWED("Biscuit contains a binary operation which is not allowed"), + UNARY_OPERATION_NOT_ALLOWED("Biscuit contains a unary operation which is not allowed"), + EXTERNAL_FUNCTION_NOT_ALLOWED("Biscuit calls a foreign function which is not allowed"), + TERM_TYPE_NOT_ALLOWED("Biscuit contains a term of a type which is not allowed"), + MAP_KEY_TYPE_NOT_ALLOWED("Biscuit contains a map key of a type which is not allowed"), + TRUSTED_SCOPE_NOT_ALLOWED("Biscuit trusts a scope which is not allowed"), + CONTEXT_TOO_LONG("Biscuit block contains a context which is too long"), + CHECK_KIND_NOT_ALLOWED("Biscuit contains a kind of check which is not allowed"), + SEALED_TOKENS_NOT_ALLOWED("Biscuit is sealed, which is not allowed"), + UNSEALED_TOKENS_NOT_ALLOWED("Biscuit is not sealed, which is not allowed"), + ATTENUATIONS_WITH_EXTERNAL_SIGNATURES_NOT_ALLOWED( + "Biscuit contains attenuations with external signatures, which are not allowed"), + ATTENUATIONS_WITHOUT_EXTERNAL_SIGNATURES_NOT_ALLOWED( + "Biscuit contains attenuations without external signatures, which are not allowed"); + + private final String description; + + Reason(String description) { + this.description = description; + } + + public String description() { + return description; + } + } + + private final Reason reason; + + public DeserializationLimitError(Reason reason) { + super(); + this.reason = reason; + } + + public Reason getReason() { + return reason; + } + + @Override + public String getMessage() { + return reason.description(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return reason == ((DeserializationLimitError) o).reason; + } + + @Override + public int hashCode() { + return Objects.hash(reason); + } + + @Override + public String toString() { + return "Err(Format(DeserializationLimitError(" + this.reason + ")))"; + } + + @Override + public JsonNode toJson() { + return FormatError.jsonWrapper( + objectMapper.createObjectNode().put("DeserializationLimitError", this.reason.name())); + } + } + public static final class SerializationError extends FormatError { private final String err; 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..7d0d1721 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 @@ -147,7 +147,26 @@ private static Biscuit make( */ public static Biscuit fromBase64Url(String data, PublicKey root) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { - return Biscuit.fromBytes(Base64.getUrlDecoder().decode(data), root); + return Biscuit.fromBase64Url(data, root, DeserializationLimit.allowEverything()); + } + + /** + * Deserializes a Biscuit token from a base64 url (RFC4648_URLSAFE) string, rejecting it if it + * contains features which are not permitted by the deserializationLimit + * + *

The deserializationLimit is checked before the signatures are verified. Apart from that, + * this behaves like {@link #fromBase64Url(String, PublicKey)}. + * + * @param data + * @param root + * @param deserializationLimit the features the token is allowed to contain + * @return Biscuit + * @throws Error.FormatError.DeserializationLimitError if the token violates the deserializationLimit + */ + public static Biscuit fromBase64Url( + String data, PublicKey root, DeserializationLimit deserializationLimit) + throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { + return Biscuit.fromBytes(Base64.getUrlDecoder().decode(data), root, deserializationLimit); } /** @@ -165,7 +184,27 @@ public static Biscuit fromBase64Url(String data, PublicKey root) */ public static Biscuit fromBase64Url(String data, KeyDelegate delegate) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { - return Biscuit.fromBytes(Base64.getUrlDecoder().decode(data), delegate); + return Biscuit.fromBase64Url(data, delegate, DeserializationLimit.allowEverything()); + } + + /** + * Deserializes a Biscuit token from a base64 url (RFC4648_URLSAFE) string, rejecting it if it + * contains features which are not permitted by the deserializationLimit + * + *

The deserializationLimit is checked before the root key is looked up and before the + * signatures are verified. Apart from that, this behaves like + * {@link #fromBase64Url(String, KeyDelegate)}. + * + * @param data + * @param delegate + * @param deserializationLimit the features the token is allowed to contain + * @return Biscuit + * @throws Error.FormatError.DeserializationLimitError if the token violates the deserializationLimit + */ + public static Biscuit fromBase64Url( + String data, KeyDelegate delegate, DeserializationLimit deserializationLimit) + throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { + return Biscuit.fromBytes(Base64.getUrlDecoder().decode(data), delegate, deserializationLimit); } /** @@ -183,14 +222,33 @@ public static Biscuit fromBase64Url(String data, KeyDelegate delegate) */ public static Biscuit fromBytes(byte[] data, PublicKey root) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { - return fromBytesWithSymbols(data, root, defaultSymbolTable()); + return fromBytes(data, root, DeserializationLimit.allowEverything()); + } + + /** + * Deserializes a Biscuit token from a byte array, rejecting it if it contains features which + * are not permitted by the deserializationLimit + * + *

The deserializationLimit is checked before the signatures are verified. Apart from that, + * this behaves like {@link #fromBytes(byte[], PublicKey)}. + * + * @param data + * @param root + * @param deserializationLimit the features the token is allowed to contain + * @return + * @throws Error.FormatError.DeserializationLimitError if the token violates the deserializationLimit + */ + public static Biscuit fromBytes( + byte[] data, PublicKey root, DeserializationLimit deserializationLimit) + throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { + return fromBytesWithSymbols(data, root, defaultSymbolTable(), deserializationLimit); } /** * Deserializes a Biscuit token from a byte array * *

This checks the signature, but does not verify that the first key is the root key, to allow - * appending blocks without knowing about the root key. + * appending blocks without knowing about the root key * *

The root key check is performed in the verify method * @@ -201,7 +259,27 @@ public static Biscuit fromBytes(byte[] data, PublicKey root) */ public static Biscuit fromBytes(byte[] data, KeyDelegate delegate) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { - return fromBytesWithSymbols(data, delegate, defaultSymbolTable()); + return fromBytes(data, delegate, DeserializationLimit.allowEverything()); + } + + /** + * Deserializes a Biscuit token from a byte array, rejecting it if it contains features which + * are not permitted by the deserializationLimit + * + *

The deserializationLimit is checked before the root key is looked up and before the + * signatures are verified. Apart from that, this behaves like + * {@link #fromBytes(byte[], KeyDelegate)}. + * + * @param data + * @param delegate + * @param deserializationLimit the features the token is allowed to contain + * @return + * @throws Error.FormatError.DeserializationLimitError if the token violates the deserializationLimit + */ + public static Biscuit fromBytes( + byte[] data, KeyDelegate delegate, DeserializationLimit deserializationLimit) + throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { + return fromBytesWithSymbols(data, delegate, defaultSymbolTable(), deserializationLimit); } /** @@ -217,11 +295,32 @@ public static Biscuit fromBytes(byte[] data, KeyDelegate delegate) */ public static Biscuit fromBytesWithSymbols(byte[] data, PublicKey root, SymbolTable symbolTable) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { - // System.out.println("will deserialize and verify token"); - SerializedBiscuit ser = SerializedBiscuit.fromBytes(data, root); - // System.out.println("deserialized token, will populate Biscuit structure"); + return fromBytesWithSymbols(data, root, symbolTable, DeserializationLimit.allowEverything()); + } - return Biscuit.fromSerializedBiscuit(ser, symbolTable); + /** + * Deserializes a Biscuit token from a byte array, rejecting it if it contains features which + * are not permitted by the deserializationLimit + * + *

The deserializationLimit is checked before the signatures are verified. Apart from that, + * this behaves like {@link #fromBytesWithSymbols(byte[], PublicKey, SymbolTable)}. + * + * @param data + * @param root + * @param symbolTable + * @param deserializationLimit the features the token is allowed to contain + * @return + * @throws Error.FormatError.DeserializationLimitError if the token violates the deserializationLimit + */ + public static Biscuit fromBytesWithSymbols( + byte[] data, + PublicKey root, + SymbolTable symbolTable, + DeserializationLimit deserializationLimit) + throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { + SerializedBiscuit ser = SerializedBiscuit.fromBytes(data, root, deserializationLimit); + + return Biscuit.fromSerializedBiscuit(ser, symbolTable, deserializationLimit); } /** @@ -238,11 +337,34 @@ public static Biscuit fromBytesWithSymbols(byte[] data, PublicKey root, SymbolTa public static Biscuit fromBytesWithSymbols( byte[] data, KeyDelegate delegate, SymbolTable symbolTable) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { - // System.out.println("will deserialize and verify token"); - SerializedBiscuit ser = SerializedBiscuit.fromBytes(data, delegate); - // System.out.println("deserialized token, will populate Biscuit structure"); + return fromBytesWithSymbols( + data, delegate, symbolTable, DeserializationLimit.allowEverything()); + } - return Biscuit.fromSerializedBiscuit(ser, symbolTable); + /** + * Deserializes a Biscuit token from a byte array, rejecting it if it contains features which + * are not permitted by the deserializationLimit + * + *

The deserializationLimit is checked before the root key is looked up and before the + * signatures are verified. Apart from that, this behaves like + * {@link #fromBytesWithSymbols(byte[], KeyDelegate, SymbolTable)}. + * + * @param data + * @param delegate + * @param symbolTable + * @param deserializationLimit the features the token is allowed to contain + * @return + * @throws Error.FormatError.DeserializationLimitError if the token violates the deserializationLimit + */ + public static Biscuit fromBytesWithSymbols( + byte[] data, + KeyDelegate delegate, + SymbolTable symbolTable, + DeserializationLimit deserializationLimit) + throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { + SerializedBiscuit ser = SerializedBiscuit.fromBytes(data, delegate, deserializationLimit); + + return Biscuit.fromSerializedBiscuit(ser, symbolTable, deserializationLimit); } /** @@ -252,12 +374,18 @@ public static Biscuit fromBytesWithSymbols( */ static Biscuit fromSerializedBiscuit(SerializedBiscuit ser, SymbolTable symbolTable) throws Error { - Pair> t = ser.extractBlocks(symbolTable); + return fromSerializedBiscuit(ser, symbolTable, DeserializationLimit.allowEverything()); + } + + static Biscuit fromSerializedBiscuit( + SerializedBiscuit ser, SymbolTable symbolTable, DeserializationLimit deserializationLimit) + throws Error { + Pair> t = ser.extractBlocks(symbolTable, deserializationLimit); return new Biscuit(t._1, t._2, symbolTable, ser); } /** - * Creates a authorizer for this token + * Creates an authorizer for this token * *

This function checks that the root key is the one we expect * diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/token/Block.java b/biscuit-core/src/main/java/org/eclipse/biscuit/token/Block.java index ab037885..0e7f59a6 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/token/Block.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/token/Block.java @@ -9,6 +9,7 @@ import com.google.protobuf.InvalidProtocolBufferException; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -234,6 +235,27 @@ public Schema.Block serialize() { */ public static Result deserialize( Schema.Block b, Optional externalKey) { + return deserialize( + b, externalKey, DeserializationLimit.PerBlock.allowEverything(), new SymbolTable()); + } + + /** + * Deserializes a block from its Protobuf representation, rejecting it if it contains features + * which are not permitted by the limits + * + * @param b + * @param externalKey + * @param limits the features the block is allowed to contain + * @param baseSymbols the symbols which are known before the block; this adds the block's symbols + * and public keys to it, so that the block's contents can refer to them, even if the block is + * then rejected + * @return + */ + public static Result deserialize( + Schema.Block b, + Optional externalKey, + DeserializationLimit.PerBlock limits, + SymbolTable baseSymbols) { int version = b.getVersion(); if (version < SerializedBiscuit.MIN_SCHEMA_VERSION || version > SerializedBiscuit.MAX_SCHEMA_VERSION) { @@ -242,17 +264,66 @@ public static Result deserialize( SerializedBiscuit.MIN_SCHEMA_VERSION, SerializedBiscuit.MAX_SCHEMA_VERSION, version)); } + if (b.getFactsV2Count() > limits.getMaxFacts()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.TOO_MANY_FACTS)); + } + if (b.getChecksV2Count() > limits.getMaxChecks()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.TOO_MANY_CHECKS)); + } + if (b.getRulesV2Count() > limits.getMaxRules()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.TOO_MANY_RULES)); + } + if (b.getSymbolsCount() > limits.getMaxSymbols()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.TOO_MANY_SYMBOLS)); + } + if (b.getPublicKeysCount() > limits.getMaxPublicKeys()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.TOO_MANY_PUBLIC_KEYS)); + } + if (b.getContext().getBytes(StandardCharsets.UTF_8).length > limits.getMaxContextLength()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.CONTEXT_TOO_LONG)); + } + SymbolTable newSymbolTable = new SymbolTable(); for (String s : b.getSymbolsList()) { newSymbolTable.add(s); } + ArrayList publicKeys = new ArrayList<>(); + for (Schema.PublicKey pk : b.getPublicKeysList()) { + try { + PublicKey key = PublicKey.deserialize(pk); + publicKeys.add(key); + newSymbolTable.getPublicKeys().add(key); + } catch (Error.FormatError e) { + return Result.err(e); + } + } + + for (PublicKey key : publicKeys) { + baseSymbols.insert(key); + } + for (String s : b.getSymbolsList()) { + baseSymbols.add(s); + } + ArrayList facts = new ArrayList<>(); ArrayList rules = new ArrayList<>(); ArrayList checks = new ArrayList<>(); for (Schema.FactV2 fact : b.getFactsV2List()) { - var res = Fact.deserializeV2(fact); + var res = Fact.deserializeV2(fact, limits, baseSymbols); if (res.isErr()) { return Result.err(res.getErr()); } else { @@ -261,7 +332,7 @@ public static Result deserialize( } for (Schema.RuleV2 rule : b.getRulesV2List()) { - var res = Rule.deserializeV2(rule); + var res = Rule.deserializeV2(rule, limits, baseSymbols); if (res.isErr()) { return Result.err(res.getErr()); } else { @@ -270,7 +341,7 @@ public static Result deserialize( } for (Schema.CheckV2 check : b.getChecksV2List()) { - var res = Check.deserializeV2(check); + var res = Check.deserializeV2(check, limits, baseSymbols); if (res.isErr()) { return Result.err(res.getErr()); } else { @@ -280,7 +351,7 @@ public static Result deserialize( ArrayList scopes = new ArrayList<>(); for (Schema.Scope scope : b.getScopeList()) { - var res = Scope.deserialize(scope); + var res = Scope.deserialize(scope, limits, baseSymbols); if (res.isErr()) { return Result.err(res.getErr()); } else { @@ -288,17 +359,6 @@ public static Result deserialize( } } - ArrayList publicKeys = new ArrayList<>(); - for (Schema.PublicKey pk : b.getPublicKeysList()) { - try { - PublicKey key = PublicKey.deserialize(pk); - publicKeys.add(key); - newSymbolTable.getPublicKeys().add(key); - } catch (Error.FormatError e) { - return Result.err(e); - } - } - var schemaVersion = new SchemaVersion(facts, rules, checks, scopes, externalKey); var res = schemaVersion.checkCompatibility(version); if (res.isErr()) { @@ -327,9 +387,33 @@ public static Result deserialize( */ public static Result fromBytes( byte[] slice, Optional externalKey) { + return fromBytes( + slice, externalKey, DeserializationLimit.PerBlock.allowEverything(), new SymbolTable()); + } + + /** + * Deserializes a Block from a byte array, rejecting it if it contains features which are not + * permitted by the limits + * + * @param slice + * @param externalKey + * @param limits the features the block is allowed to contain + * @param baseSymbols the symbols which are known before the block + * @return + */ + public static Result fromBytes( + byte[] slice, + Optional externalKey, + DeserializationLimit.PerBlock limits, + SymbolTable baseSymbols) { + if (slice.length > limits.getMaxBlockSize()) { + return Result.err( + new Error.FormatError.DeserializationLimitError( + Error.FormatError.DeserializationLimitError.Reason.BLOCK_TOO_LARGE)); + } try { Schema.Block data = Schema.Block.parseFrom(slice); - return Block.deserialize(data, externalKey); + return Block.deserialize(data, externalKey, limits, baseSymbols); } catch (InvalidProtocolBufferException e) { return Result.err(new Error.FormatError.DeserializationError(e.toString())); } diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/token/DeserializationLimit.java b/biscuit-core/src/main/java/org/eclipse/biscuit/token/DeserializationLimit.java new file mode 100644 index 00000000..ac49f181 --- /dev/null +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/token/DeserializationLimit.java @@ -0,0 +1,693 @@ +/* + * Copyright (c) 2019 Geoffroy Couprie and Contributors to the Eclipse Foundation. + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.eclipse.biscuit.token; + +import biscuit.format.schema.Schema.PublicKey.Algorithm; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import org.eclipse.biscuit.datalog.Check; +import org.eclipse.biscuit.datalog.SymbolTable; +import org.eclipse.biscuit.datalog.expressions.Op; +import org.eclipse.biscuit.error.Error; + +/** + * Restrictions on the features a token may contain, enforced while the token is deserialized. + * + *

Settings which apply to the token as a whole are properties of the DeserializationLimit + * itself, while settings which apply within each block are part of a {@link PerBlock} limit. + * Separate {@link PerBlock} limits are used for the authority block and for attenuations, so that + * attenuations can be restricted more tightly than the authority block. + * + *

Booleans and sets are "allow" settings: a boolean set to {@code false} forbids the feature, + * and a set restricts the feature to its members, with {@code null} meaning that any member is + * permitted. Integers are limits, with {@link Integer#MAX_VALUE} meaning unlimited, except for + * {@code minSignatureVersion}, where {@code 0} accepts every version. + * + *

A new limit allows nothing: every setting starts at its most restrictive value. Start from + * {@link #allowEverything()}, which allows everything, and restrict only the features you need to: + * + *

{@code
+ * DeserializationLimit limit = DeserializationLimit.allowEverything().setMaxBlocks(4);
+ * limit.getAttenuations().setAllowClosures(false);
+ * }
+ * + *

Alternatively, start from {@link #allowNothing()} and enable only the features you need. + * + *

A token which violates the limits is rejected with an {@link + * org.eclipse.biscuit.error.Error.FormatError.DeserializationLimitError}. The settings for the + * token as a whole (its size, number of blocks, sealing, signing algorithms, signature versions and + * external signatures) are checked before any signature is verified. The settings within each + * block are checked as the block is deserialized, which for a verified {@code Biscuit} is after its + * signatures have been verified. A DeserializationLimit is mutable and should not be modified while + * it is being used to deserialize a token. + */ +public final class DeserializationLimit { + private boolean allowAttenuationsWithExternalSignatures = false; + private boolean allowAttenuationsWithoutExternalSignatures = false; + private boolean allowSealedTokens = false; + private boolean allowUnsealedTokens = false; + private int maxTokenSize = 0; + private int maxBlocks = 0; + private int minSignatureVersion = HIGHEST_SIGNATURE_VERSION; + private Set allowedInternalSigningAlgorithms = Set.of(); + private Set allowedExternalSigningAlgorithms = Set.of(); + private PerBlock authority = PerBlock.allowNothing(); + private PerBlock attenuations = PerBlock.allowNothing(); + + private DeserializationLimit() {} + + public static DeserializationLimit allowEverything() { + DeserializationLimit deserializationLimit = new DeserializationLimit(); + deserializationLimit.allowAttenuationsWithExternalSignatures = true; + deserializationLimit.allowAttenuationsWithoutExternalSignatures = true; + deserializationLimit.allowSealedTokens = true; + deserializationLimit.allowUnsealedTokens = true; + deserializationLimit.maxTokenSize = Integer.MAX_VALUE; + deserializationLimit.maxBlocks = Integer.MAX_VALUE; + deserializationLimit.minSignatureVersion = 0; + deserializationLimit.allowedInternalSigningAlgorithms = null; + deserializationLimit.allowedExternalSigningAlgorithms = null; + deserializationLimit.authority = PerBlock.allowEverything(); + deserializationLimit.attenuations = PerBlock.allowEverything(); + return deserializationLimit; + } + + public static DeserializationLimit allowNothing() { + return new DeserializationLimit(); + } + + private static final int HIGHEST_SIGNATURE_VERSION = 1; + + public boolean getAllowAttenuationsWithExternalSignatures() { + return allowAttenuationsWithExternalSignatures; + } + + public DeserializationLimit setAllowAttenuationsWithExternalSignatures(boolean allow) { + this.allowAttenuationsWithExternalSignatures = allow; + return this; + } + + public boolean getAllowAttenuationsWithoutExternalSignatures() { + return allowAttenuationsWithoutExternalSignatures; + } + + public DeserializationLimit setAllowAttenuationsWithoutExternalSignatures(boolean allow) { + this.allowAttenuationsWithoutExternalSignatures = allow; + return this; + } + + public boolean getAllowSealedTokens() { + return allowSealedTokens; + } + + public DeserializationLimit setAllowSealedTokens(boolean allow) { + this.allowSealedTokens = allow; + return this; + } + + public boolean getAllowUnsealedTokens() { + return allowUnsealedTokens; + } + + public DeserializationLimit setAllowUnsealedTokens(boolean allow) { + this.allowUnsealedTokens = allow; + return this; + } + + public int getMaxTokenSize() { + return maxTokenSize; + } + + public DeserializationLimit setMaxTokenSize(int max) { + this.maxTokenSize = nonNegative(max); + return this; + } + + public int getMaxBlocks() { + return maxBlocks; + } + + public DeserializationLimit setMaxBlocks(int max) { + this.maxBlocks = nonNegative(max); + return this; + } + + public int getMinSignatureVersion() { + return minSignatureVersion; + } + + public DeserializationLimit setMinSignatureVersion(int min) { + if (min > HIGHEST_SIGNATURE_VERSION) { + throw new IllegalArgumentException( + "the minimum signature version " + + min + + " is higher than the highest supported version " + + HIGHEST_SIGNATURE_VERSION); + } + this.minSignatureVersion = nonNegative(min); + return this; + } + + public Set getAllowedInternalSigningAlgorithms() { + return allowedInternalSigningAlgorithms; + } + + public DeserializationLimit setAllowedInternalSigningAlgorithms(Set algorithms) { + this.allowedInternalSigningAlgorithms = copy(algorithms); + return this; + } + + public Set getAllowedExternalSigningAlgorithms() { + return allowedExternalSigningAlgorithms; + } + + public DeserializationLimit setAllowedExternalSigningAlgorithms(Set algorithms) { + this.allowedExternalSigningAlgorithms = copy(algorithms); + return this; + } + + public PerBlock getAuthority() { + return authority; + } + + public DeserializationLimit setAuthority(PerBlock authority) { + this.authority = Objects.requireNonNull(authority); + return this; + } + + public PerBlock getAttenuations() { + return attenuations; + } + + public DeserializationLimit setAttenuations(PerBlock attenuations) { + this.attenuations = Objects.requireNonNull(attenuations); + return this; + } + + private static int nonNegative(int value) { + if (value < 0) { + throw new IllegalArgumentException("a limit cannot be negative: " + value); + } + return value; + } + + private static Set copy(Set set) { + return set == null ? null : Set.copyOf(set); + } + + private Object[] state() { + return new Object[] { + allowAttenuationsWithExternalSignatures, + allowAttenuationsWithoutExternalSignatures, + allowSealedTokens, + allowUnsealedTokens, + maxTokenSize, + maxBlocks, + minSignatureVersion, + allowedInternalSigningAlgorithms, + allowedExternalSigningAlgorithms, + authority, + attenuations + }; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return Arrays.equals(state(), ((DeserializationLimit) o).state()); + } + + @Override + public int hashCode() { + return Arrays.hashCode(state()); + } + + public enum TermType { + INTEGER, + STRING, + DATE, + BYTES, + BOOL, + SET, + NULL, + ARRAY, + MAP + } + + public enum MapKeyType { + INTEGER, + STRING + } + + public static final class TrustedScopeKind { + private enum Kind { + AUTHORITY, + PREVIOUS, + PUBLIC_KEY + } + + public static final TrustedScopeKind AUTHORITY = new TrustedScopeKind(Kind.AUTHORITY, null); + public static final TrustedScopeKind PREVIOUS = new TrustedScopeKind(Kind.PREVIOUS, null); + + private final Kind kind; + private final Algorithm algorithm; + + private TrustedScopeKind(Kind kind, Algorithm algorithm) { + this.kind = kind; + this.algorithm = algorithm; + } + + public static TrustedScopeKind publicKey(Algorithm algorithm) { + return new TrustedScopeKind(Kind.PUBLIC_KEY, Objects.requireNonNull(algorithm)); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TrustedScopeKind that = (TrustedScopeKind) o; + return kind == that.kind && algorithm == that.algorithm; + } + + @Override + public int hashCode() { + return Objects.hash(kind, algorithm); + } + + @Override + public String toString() { + return kind == Kind.PUBLIC_KEY ? kind + "(" + algorithm + ")" : kind.toString(); + } + } + + public static final class PerBlock { + private boolean allowClosures = false; + private int maxBlockSize = 0; + private int maxFacts = 0; + private int maxRules = 0; + private int maxChecks = 0; + private int maxSymbols = 0; + private int maxPublicKeys = 0; + private int maxContextLength = 0; + private int maxQueriesPerCheck = 0; + private int maxPredicatesPerBody = 0; + private int maxExpressionsPerBody = 0; + private int maxOpsPerExpression = 0; + private int maxTermsPerPredicate = 0; + private int maxNameLength = 0; + private int maxBytesLength = 0; + private int maxStringLength = 0; + private int maxSetLength = 0; + private int maxArrayLength = 0; + private int maxMapLength = 0; + private Set allowedBinaryOps = Set.of(); + private Set allowedUnaryOps = Set.of(); + private Set allowedUnaryExternalFunctions = Set.of(); + private Set allowedBinaryExternalFunctions = Set.of(); + private Set allowedTermTypes = Set.of(); + private Set allowedMapKeyTypes = Set.of(); + private Set allowedTrustingScopes = Set.of(); + private Set allowedCheckKinds = Set.of(); + + private PerBlock() {} + + public static PerBlock allowEverything() { + PerBlock perBlock = new PerBlock(); + perBlock.allowClosures = true; + perBlock.maxBlockSize = Integer.MAX_VALUE; + perBlock.maxFacts = Integer.MAX_VALUE; + perBlock.maxRules = Integer.MAX_VALUE; + perBlock.maxChecks = Integer.MAX_VALUE; + perBlock.maxSymbols = Integer.MAX_VALUE; + perBlock.maxPublicKeys = Integer.MAX_VALUE; + perBlock.maxContextLength = Integer.MAX_VALUE; + perBlock.maxQueriesPerCheck = Integer.MAX_VALUE; + perBlock.maxPredicatesPerBody = Integer.MAX_VALUE; + perBlock.maxExpressionsPerBody = Integer.MAX_VALUE; + perBlock.maxOpsPerExpression = Integer.MAX_VALUE; + perBlock.maxTermsPerPredicate = Integer.MAX_VALUE; + perBlock.maxNameLength = Integer.MAX_VALUE; + perBlock.maxBytesLength = Integer.MAX_VALUE; + perBlock.maxStringLength = Integer.MAX_VALUE; + perBlock.maxSetLength = Integer.MAX_VALUE; + perBlock.maxArrayLength = Integer.MAX_VALUE; + perBlock.maxMapLength = Integer.MAX_VALUE; + perBlock.allowedBinaryOps = null; + perBlock.allowedUnaryOps = null; + perBlock.allowedUnaryExternalFunctions = null; + perBlock.allowedBinaryExternalFunctions = null; + perBlock.allowedTermTypes = null; + perBlock.allowedMapKeyTypes = null; + perBlock.allowedTrustingScopes = null; + perBlock.allowedCheckKinds = null; + return perBlock; + } + + public static PerBlock allowNothing() { + return new PerBlock(); + } + + public Error.FormatError checkName(SymbolTable symbols, long symbolIndex) { + return checkLength( + symbols, + symbolIndex, + maxNameLength, + Error.FormatError.DeserializationLimitError.Reason.NAME_TOO_LONG); + } + + public Error.FormatError checkString(SymbolTable symbols, long symbolIndex) { + return checkLength( + symbols, + symbolIndex, + maxStringLength, + Error.FormatError.DeserializationLimitError.Reason.STRING_TOO_LONG); + } + + private static Error.FormatError checkLength( + SymbolTable symbols, + long symbolIndex, + int maxLength, + Error.FormatError.DeserializationLimitError.Reason reason) { + if (maxLength == Integer.MAX_VALUE) { + return null; + } + Optional symbol = + symbolIndex >= 0 && symbolIndex <= Integer.MAX_VALUE + ? symbols.getSymbol((int) symbolIndex) + : Optional.empty(); + if (symbol.isEmpty()) { + return new Error.FormatError.DeserializationError("unknown symbol " + symbolIndex); + } + if (symbol.get().getBytes(StandardCharsets.UTF_8).length > maxLength) { + return new Error.FormatError.DeserializationLimitError(reason); + } + return null; + } + + public boolean getAllowClosures() { + return allowClosures; + } + + public PerBlock setAllowClosures(boolean allow) { + this.allowClosures = allow; + return this; + } + + public int getMaxBlockSize() { + return maxBlockSize; + } + + public PerBlock setMaxBlockSize(int max) { + this.maxBlockSize = nonNegative(max); + return this; + } + + public int getMaxFacts() { + return maxFacts; + } + + public PerBlock setMaxFacts(int max) { + this.maxFacts = nonNegative(max); + return this; + } + + public int getMaxRules() { + return maxRules; + } + + public PerBlock setMaxRules(int max) { + this.maxRules = nonNegative(max); + return this; + } + + public int getMaxChecks() { + return maxChecks; + } + + public PerBlock setMaxChecks(int max) { + this.maxChecks = nonNegative(max); + return this; + } + + public int getMaxSymbols() { + return maxSymbols; + } + + public PerBlock setMaxSymbols(int max) { + this.maxSymbols = nonNegative(max); + return this; + } + + public int getMaxPublicKeys() { + return maxPublicKeys; + } + + public PerBlock setMaxPublicKeys(int max) { + this.maxPublicKeys = nonNegative(max); + return this; + } + + public int getMaxContextLength() { + return maxContextLength; + } + + public PerBlock setMaxContextLength(int max) { + this.maxContextLength = nonNegative(max); + return this; + } + + public int getMaxQueriesPerCheck() { + return maxQueriesPerCheck; + } + + public PerBlock setMaxQueriesPerCheck(int max) { + this.maxQueriesPerCheck = nonNegative(max); + return this; + } + + public int getMaxPredicatesPerBody() { + return maxPredicatesPerBody; + } + + public PerBlock setMaxPredicatesPerBody(int max) { + this.maxPredicatesPerBody = nonNegative(max); + return this; + } + + public int getMaxExpressionsPerBody() { + return maxExpressionsPerBody; + } + + public PerBlock setMaxExpressionsPerBody(int max) { + this.maxExpressionsPerBody = nonNegative(max); + return this; + } + + public int getMaxOpsPerExpression() { + return maxOpsPerExpression; + } + + public PerBlock setMaxOpsPerExpression(int max) { + this.maxOpsPerExpression = nonNegative(max); + return this; + } + + public int getMaxTermsPerPredicate() { + return maxTermsPerPredicate; + } + + public PerBlock setMaxTermsPerPredicate(int max) { + this.maxTermsPerPredicate = nonNegative(max); + return this; + } + + public int getMaxNameLength() { + return maxNameLength; + } + + public PerBlock setMaxNameLength(int max) { + this.maxNameLength = nonNegative(max); + return this; + } + + public int getMaxBytesLength() { + return maxBytesLength; + } + + public PerBlock setMaxBytesLength(int max) { + this.maxBytesLength = nonNegative(max); + return this; + } + + public int getMaxStringLength() { + return maxStringLength; + } + + public PerBlock setMaxStringLength(int max) { + this.maxStringLength = nonNegative(max); + return this; + } + + public int getMaxSetLength() { + return maxSetLength; + } + + public PerBlock setMaxSetLength(int max) { + this.maxSetLength = nonNegative(max); + return this; + } + + public int getMaxArrayLength() { + return maxArrayLength; + } + + public PerBlock setMaxArrayLength(int max) { + this.maxArrayLength = nonNegative(max); + return this; + } + + public int getMaxMapLength() { + return maxMapLength; + } + + public PerBlock setMaxMapLength(int max) { + this.maxMapLength = nonNegative(max); + return this; + } + + public Set getAllowedBinaryOps() { + return allowedBinaryOps; + } + + public PerBlock setAllowedBinaryOps(Set ops) { + this.allowedBinaryOps = copy(ops); + return this; + } + + public Set getAllowedUnaryOps() { + return allowedUnaryOps; + } + + public PerBlock setAllowedUnaryOps(Set ops) { + this.allowedUnaryOps = copy(ops); + return this; + } + + public Set getAllowedUnaryExternalFunctions() { + return allowedUnaryExternalFunctions; + } + + public PerBlock setAllowedUnaryExternalFunctions(Set names) { + this.allowedUnaryExternalFunctions = copy(names); + return this; + } + + public Set getAllowedBinaryExternalFunctions() { + return allowedBinaryExternalFunctions; + } + + public PerBlock setAllowedBinaryExternalFunctions(Set names) { + this.allowedBinaryExternalFunctions = copy(names); + return this; + } + + public Set getAllowedTermTypes() { + return allowedTermTypes; + } + + public PerBlock setAllowedTermTypes(Set types) { + this.allowedTermTypes = copy(types); + return this; + } + + public Set getAllowedMapKeyTypes() { + return allowedMapKeyTypes; + } + + public PerBlock setAllowedMapKeyTypes(Set types) { + this.allowedMapKeyTypes = copy(types); + return this; + } + + public Set getAllowedTrustingScopes() { + return allowedTrustingScopes; + } + + public PerBlock setAllowedTrustingScopes(Set scopes) { + this.allowedTrustingScopes = copy(scopes); + return this; + } + + public Set getAllowedCheckKinds() { + return allowedCheckKinds; + } + + public PerBlock setAllowedCheckKinds(Set kinds) { + this.allowedCheckKinds = copy(kinds); + return this; + } + + private Object[] state() { + return new Object[] { + allowClosures, + maxBlockSize, + maxFacts, + maxRules, + maxChecks, + maxSymbols, + maxPublicKeys, + maxContextLength, + maxQueriesPerCheck, + maxPredicatesPerBody, + maxExpressionsPerBody, + maxOpsPerExpression, + maxTermsPerPredicate, + maxNameLength, + maxBytesLength, + maxStringLength, + maxSetLength, + maxArrayLength, + maxMapLength, + allowedBinaryOps, + allowedUnaryOps, + allowedUnaryExternalFunctions, + allowedBinaryExternalFunctions, + allowedTermTypes, + allowedMapKeyTypes, + allowedTrustingScopes, + allowedCheckKinds + }; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return Arrays.equals(state(), ((PerBlock) o).state()); + } + + @Override + public int hashCode() { + return Arrays.hashCode(state()); + } + } +} diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/token/UnverifiedBiscuit.java b/biscuit-core/src/main/java/org/eclipse/biscuit/token/UnverifiedBiscuit.java index e7e5cbea..7413b9fa 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/token/UnverifiedBiscuit.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/token/UnverifiedBiscuit.java @@ -57,7 +57,23 @@ public class UnverifiedBiscuit { * @return Biscuit */ public static UnverifiedBiscuit fromBase64Url(String data) throws Error { - return UnverifiedBiscuit.fromBytes(Base64.getUrlDecoder().decode(data)); + return UnverifiedBiscuit.fromBase64Url(data, DeserializationLimit.allowEverything()); + } + + /** + * Deserializes a Biscuit token from a base64 url (RFC4648_URLSAFE) string, rejecting it if it + * contains features which are not permitted by the deserializationLimit + * + *

This method uses the default symbol table + * + * @param data + * @param deserializationLimit the features the token is allowed to contain + * @return Biscuit + * @throws Error.FormatError.DeserializationLimitError if the token violates the deserializationLimit + */ + public static UnverifiedBiscuit fromBase64Url( + String data, DeserializationLimit deserializationLimit) throws Error { + return UnverifiedBiscuit.fromBytes(Base64.getUrlDecoder().decode(data), deserializationLimit); } /** @@ -69,7 +85,23 @@ public static UnverifiedBiscuit fromBase64Url(String data) throws Error { * @return */ public static UnverifiedBiscuit fromBytes(byte[] data) throws Error { - return UnverifiedBiscuit.fromBytesWithSymbols(data, defaultSymbolTable()); + return UnverifiedBiscuit.fromBytes(data, DeserializationLimit.allowEverything()); + } + + /** + * Deserializes a Biscuit token from a byte array, rejecting it if it contains features which + * are not permitted by the deserializationLimit + * + *

This method uses the default symbol table + * + * @param data + * @param deserializationLimit the features the token is allowed to contain + * @return + * @throws Error.FormatError.DeserializationLimitError if the token violates the deserializationLimit + */ + public static UnverifiedBiscuit fromBytes(byte[] data, DeserializationLimit deserializationLimit) + throws Error { + return UnverifiedBiscuit.fromBytesWithSymbols(data, defaultSymbolTable(), deserializationLimit); } /** @@ -80,8 +112,26 @@ public static UnverifiedBiscuit fromBytes(byte[] data) throws Error { */ public static UnverifiedBiscuit fromBytesWithSymbols(byte[] data, SymbolTable symbolTable) throws Error { - SerializedBiscuit ser = SerializedBiscuit.deserializeUnsafe(data); - return UnverifiedBiscuit.fromSerializedBiscuit(ser, symbolTable); + return fromBytesWithSymbols(data, symbolTable, DeserializationLimit.allowEverything()); + } + + /** + * Deserializes a UnverifiedBiscuit from a byte array, rejecting it if it contains features which + * are not permitted by the deserializationLimit + * + *

This method does not verify the signatures. + * + * @param data + * @param symbolTable + * @param deserializationLimit the features the token is allowed to contain + * @return UnverifiedBiscuit + * @throws Error.FormatError.DeserializationLimitError if the token violates the deserializationLimit + */ + public static UnverifiedBiscuit fromBytesWithSymbols( + byte[] data, SymbolTable symbolTable, DeserializationLimit deserializationLimit) + throws Error { + SerializedBiscuit ser = SerializedBiscuit.deserializeUnsafe(data, deserializationLimit); + return UnverifiedBiscuit.fromSerializedBiscuit(ser, symbolTable, deserializationLimit); } /** @@ -90,8 +140,9 @@ public static UnverifiedBiscuit fromBytesWithSymbols(byte[] data, SymbolTable sy * @return UnverifiedBiscuit */ private static UnverifiedBiscuit fromSerializedBiscuit( - SerializedBiscuit ser, SymbolTable symbolTable) throws Error { - var t = ser.extractBlocks(symbolTable); + SerializedBiscuit ser, SymbolTable symbolTable, DeserializationLimit deserializationLimit) + throws Error { + var t = ser.extractBlocks(symbolTable, deserializationLimit); return new UnverifiedBiscuit(t._1, t._2, symbolTable, ser); } diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/token/format/DeserializationLimitChecker.java b/biscuit-core/src/main/java/org/eclipse/biscuit/token/format/DeserializationLimitChecker.java new file mode 100644 index 00000000..12a1e0e4 --- /dev/null +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/token/format/DeserializationLimitChecker.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2019 Geoffroy Couprie and Contributors to the Eclipse Foundation. + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.eclipse.biscuit.token.format; + +import biscuit.format.schema.Schema; +import java.util.Set; +import org.eclipse.biscuit.error.Error; +import org.eclipse.biscuit.error.Error.FormatError.DeserializationLimitError.Reason; +import org.eclipse.biscuit.token.DeserializationLimit; + +/** + * Checks the settings of a {@link DeserializationLimit} which apply to the token as a whole. + * + *

These are checked on the protobuf message before any signature is verified. The limits within + * each block are checked while the block is deserialized, see {@link + * org.eclipse.biscuit.token.Block#deserialize}. + */ +final class DeserializationLimitChecker { + private DeserializationLimitChecker() {} + + /** Checks the size of the serialized token, before it is parsed */ + static void checkTokenSize(byte[] slice, DeserializationLimit deserializationLimit) + throws Error.FormatError { + require(slice.length <= deserializationLimit.getMaxTokenSize(), Reason.TOKEN_TOO_LARGE); + } + + /** + * Checks the number of blocks and whether the token is sealed, before the root key is looked up + * and before the blocks are examined + */ + static void checkToken(Schema.Biscuit data, DeserializationLimit deserializationLimit) + throws Error.FormatError { + // the authority block counts towards the maximum + require(data.getBlocksCount() < deserializationLimit.getMaxBlocks(), Reason.TOO_MANY_BLOCKS); + if (data.getProof().hasFinalSignature()) { + require(deserializationLimit.getAllowSealedTokens(), Reason.SEALED_TOKENS_NOT_ALLOWED); + } else if (data.getProof().hasNextSecret()) { + require(deserializationLimit.getAllowUnsealedTokens(), Reason.UNSEALED_TOKENS_NOT_ALLOWED); + } + } + + /** + * Checks the settings of each signed block: the signing algorithms, the signature version, and + * whether attenuations may have external signatures + */ + static void checkSignedBlocks(Schema.Biscuit data, DeserializationLimit deserializationLimit) + throws Error.FormatError { + checkSignedBlock(data.getAuthority(), false, deserializationLimit); + for (Schema.SignedBlock block : data.getBlocksList()) { + checkSignedBlock(block, true, deserializationLimit); + } + } + + private static void checkSignedBlock( + Schema.SignedBlock block, boolean attenuation, DeserializationLimit deserializationLimit) + throws Error.FormatError { + // this is the same condition SerializedBiscuit uses to decide that a block is third party + boolean external = + attenuation + && block.hasExternalSignature() + && block.getExternalSignature().hasPublicKey() + && block.getExternalSignature().hasSignature(); + if (attenuation) { + if (external) { + require( + deserializationLimit.getAllowAttenuationsWithExternalSignatures(), + Reason.ATTENUATIONS_WITH_EXTERNAL_SIGNATURES_NOT_ALLOWED); + } else { + require( + deserializationLimit.getAllowAttenuationsWithoutExternalSignatures(), + Reason.ATTENUATIONS_WITHOUT_EXTERNAL_SIGNATURES_NOT_ALLOWED); + } + } + + Set internalAlgorithms = + deserializationLimit.getAllowedInternalSigningAlgorithms(); + if (internalAlgorithms != null) { + require( + internalAlgorithms.contains(block.getNextKey().getAlgorithm()), + Reason.INTERNAL_SIGNING_ALGORITHM_NOT_ALLOWED); + } + // a block without a version uses version 0 signatures + require( + block.getVersion() >= deserializationLimit.getMinSignatureVersion(), + Reason.SIGNATURE_VERSION_TOO_LOW); + + Set externalAlgorithms = + deserializationLimit.getAllowedExternalSigningAlgorithms(); + if (external && externalAlgorithms != null) { + require( + externalAlgorithms.contains(block.getExternalSignature().getPublicKey().getAlgorithm()), + Reason.EXTERNAL_SIGNING_ALGORITHM_NOT_ALLOWED); + } + } + + private static void require(boolean condition, Reason reason) throws Error.FormatError { + if (!condition) { + throw new Error.FormatError.DeserializationLimitError(reason); + } + } +} diff --git a/biscuit-core/src/main/java/org/eclipse/biscuit/token/format/SerializedBiscuit.java b/biscuit-core/src/main/java/org/eclipse/biscuit/token/format/SerializedBiscuit.java index 62a2f8a0..29dd94e9 100644 --- a/biscuit-core/src/main/java/org/eclipse/biscuit/token/format/SerializedBiscuit.java +++ b/biscuit-core/src/main/java/org/eclipse/biscuit/token/format/SerializedBiscuit.java @@ -27,6 +27,7 @@ import org.eclipse.biscuit.error.Error; import org.eclipse.biscuit.error.Result; import org.eclipse.biscuit.token.Block; +import org.eclipse.biscuit.token.DeserializationLimit; /** Intermediate representation of a token before full serialization */ public final class SerializedBiscuit { @@ -55,10 +56,28 @@ public final class SerializedBiscuit { */ public static SerializedBiscuit fromBytes(byte[] slice, PublicKey root) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { + return fromBytes(slice, root, DeserializationLimit.allowEverything()); + } + + /** + * Deserializes a SerializedBiscuit from a byte array + * + *

The deserializationLimit is checked before the signatures are verified + * + * @param slice + * @param root + * @param deserializationLimit the features the token is allowed to contain + * @return + */ + public static SerializedBiscuit fromBytes( + byte[] slice, PublicKey root, DeserializationLimit deserializationLimit) + throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { try { + DeserializationLimitChecker.checkTokenSize(slice, deserializationLimit); Schema.Biscuit data = Schema.Biscuit.parseFrom(slice); + DeserializationLimitChecker.checkToken(data, deserializationLimit); - return fromBytesInner(data, root); + return fromBytesInner(data, root, deserializationLimit); } catch (InvalidProtocolBufferException e) { throw new Error.FormatError.DeserializationError(e.toString()); } @@ -72,8 +91,27 @@ public static SerializedBiscuit fromBytes(byte[] slice, PublicKey root) */ public static SerializedBiscuit fromBytes(byte[] slice, KeyDelegate delegate) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { + return fromBytes(slice, delegate, DeserializationLimit.allowEverything()); + } + + /** + * Deserializes a SerializedBiscuit from a byte array + * + *

The deserializationLimit is checked before the root key is looked up and before the signatures are + * verified + * + * @param slice + * @param delegate + * @param deserializationLimit the features the token is allowed to contain + * @return + */ + public static SerializedBiscuit fromBytes( + byte[] slice, KeyDelegate delegate, DeserializationLimit deserializationLimit) + throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { try { + DeserializationLimitChecker.checkTokenSize(slice, deserializationLimit); Schema.Biscuit data = Schema.Biscuit.parseFrom(slice); + DeserializationLimitChecker.checkToken(data, deserializationLimit); Optional rootKeyId = Optional.empty(); if (data.hasRootKeyId()) { @@ -85,19 +123,19 @@ public static SerializedBiscuit fromBytes(byte[] slice, KeyDelegate delegate) throw new InvalidKeyException("unknown root key id"); } - return fromBytesInner(data, root.get()); + return fromBytesInner(data, root.get(), deserializationLimit); } catch (InvalidProtocolBufferException e) { throw new Error.FormatError.DeserializationError(e.toString()); } } - static SerializedBiscuit fromBytesInner(Schema.Biscuit data, PublicKey root) + static SerializedBiscuit fromBytesInner( + Schema.Biscuit data, PublicKey root, DeserializationLimit deserializationLimit) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error { - SerializedBiscuit b = SerializedBiscuit.deserialize(data); + SerializedBiscuit b = SerializedBiscuit.deserialize(data, deserializationLimit); if (data.hasRootKeyId()) { b.rootKeyId = Optional.of(data.getRootKeyId()); } - var res = b.verify(root); if (res.isErr()) { throw res.getErr(); @@ -114,9 +152,24 @@ static SerializedBiscuit fromBytesInner(Schema.Biscuit data, PublicKey root) * @throws Error.FormatError */ public static SerializedBiscuit deserializeUnsafe(byte[] slice) throws Error.FormatError { + return deserializeUnsafe(slice, DeserializationLimit.allowEverything()); + } + + /** + * Warning: this deserializes without verifying the signature + * + * @param slice + * @param deserializationLimit the features the token is allowed to contain + * @return SerializedBiscuit + * @throws Error.FormatError + */ + public static SerializedBiscuit deserializeUnsafe( + byte[] slice, DeserializationLimit deserializationLimit) throws Error.FormatError { try { + DeserializationLimitChecker.checkTokenSize(slice, deserializationLimit); Schema.Biscuit data = Schema.Biscuit.parseFrom(slice); - return SerializedBiscuit.deserialize(data); + DeserializationLimitChecker.checkToken(data, deserializationLimit); + return SerializedBiscuit.deserialize(data, deserializationLimit); } catch (InvalidProtocolBufferException e) { throw new Error.FormatError.DeserializationError(e.toString()); } @@ -126,10 +179,14 @@ public static SerializedBiscuit deserializeUnsafe(byte[] slice) throws Error.For * Warning: this deserializes without verifying the signature * * @param data + * @param deserializationLimit the features the token is allowed to contain * @return SerializedBiscuit * @throws Error.FormatError */ - private static SerializedBiscuit deserialize(Schema.Biscuit data) throws Error.FormatError { + private static SerializedBiscuit deserialize( + Schema.Biscuit data, DeserializationLimit deserializationLimit) throws Error.FormatError { + DeserializationLimitChecker.checkSignedBlocks(data, deserializationLimit); + if (data.getAuthority().hasExternalSignature()) { throw new Error.FormatError.DeserializationError( "the authority block must not contain an external signature"); @@ -458,18 +515,21 @@ static Result verifyBlockSignature( } public Pair> extractBlocks(SymbolTable symbolTable) throws Error { - var authRes = Block.fromBytes(this.authority.getBlock(), Optional.empty()); + return extractBlocks(symbolTable, DeserializationLimit.allowEverything()); + } + + public Pair> extractBlocks( + SymbolTable symbolTable, DeserializationLimit deserializationLimit) throws Error { + var authRes = + Block.fromBytes( + this.authority.getBlock(), + Optional.empty(), + deserializationLimit.getAuthority(), + symbolTable); if (authRes.isErr()) { throw authRes.getErr(); } Block authority = authRes.getOk(); - for (org.eclipse.biscuit.crypto.PublicKey pk : authority.getPublicKeys()) { - symbolTable.insert(pk); - } - - for (String s : authority.getSymbolTable().symbols()) { - symbolTable.add(s); - } ArrayList blocks = new ArrayList<>(); for (SignedBlock bdata : this.blocks) { @@ -477,25 +537,17 @@ public Pair> extractBlocks(SymbolTable symbolTable) throws Er if (bdata.getExternalSignature().isPresent()) { externalKey = Optional.of(bdata.getExternalSignature().get().getKey()); } - var blockRes = Block.fromBytes(bdata.getBlock(), externalKey); + // blocks with external signatures keep their own symbol table + var blockRes = + Block.fromBytes( + bdata.getBlock(), + externalKey, + deserializationLimit.getAttenuations(), + externalKey.isPresent() ? new SymbolTable() : symbolTable); if (blockRes.isErr()) { throw blockRes.getErr(); } - Block block = blockRes.getOk(); - - // blocks with external signatures keep their own symbol table - if (bdata.getExternalSignature().isPresent()) { - // symbolTable.insert(bdata.externalSignature.get().key); - } else { - for (String s : block.getSymbolTable().symbols()) { - symbolTable.add(s); - } - for (PublicKey pk : block.getPublicKeys()) { - symbolTable.insert(pk); - } - } - - blocks.add(block); + blocks.add(blockRes.getOk()); } return new Pair<>(authority, Collections.unmodifiableList(blocks)); diff --git a/biscuit/src/test/java/org/eclipse/biscuit/token/DeserializationLimitsTest.java b/biscuit/src/test/java/org/eclipse/biscuit/token/DeserializationLimitsTest.java new file mode 100644 index 00000000..9a38236b --- /dev/null +++ b/biscuit/src/test/java/org/eclipse/biscuit/token/DeserializationLimitsTest.java @@ -0,0 +1,963 @@ +/* + * Copyright (c) 2019 Geoffroy Couprie and Contributors to the Eclipse Foundation. + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.eclipse.biscuit.token; + +import static org.junit.jupiter.api.Assertions.*; + +import biscuit.format.schema.Schema; +import biscuit.format.schema.Schema.PublicKey.Algorithm; +import com.google.protobuf.ByteString; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.security.SecureRandom; +import java.util.EnumSet; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import org.eclipse.biscuit.crypto.KeyDelegate; +import org.eclipse.biscuit.crypto.KeyPair; +import org.eclipse.biscuit.datalog.Check; +import org.eclipse.biscuit.datalog.expressions.Op; +import org.eclipse.biscuit.error.Error; +import org.eclipse.biscuit.error.Error.FormatError.DeserializationLimitError.Reason; +import org.eclipse.biscuit.token.DeserializationLimit.MapKeyType; +import org.eclipse.biscuit.token.DeserializationLimit.PerBlock; +import org.eclipse.biscuit.token.DeserializationLimit.TermType; +import org.eclipse.biscuit.token.DeserializationLimit.TrustedScopeKind; +import org.eclipse.biscuit.token.builder.Block; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class DeserializationLimitsTest { + /** Fills in a block with the features that a test wants the block to contain */ + private interface BlockSetup { + void apply(Block block) throws Exception; + } + + private SecureRandom rng; + private KeyPair root; + + @BeforeEach + public void setUp() throws Exception { + byte[] seed = {0, 0, 0, 0}; + rng = SecureRandom.getInstance("SHA1PRNG"); + rng.setSeed(seed); + root = KeyPair.generate(Algorithm.Ed25519, rng); + } + + // Every setting must be at its most restrictive value in allowNothing, including settings added + // in the future, so this checks each field by reflection rather than by name + @Test + public void testAllowNothingAllowsNothing() throws Exception { + assertAllowsNothing(DeserializationLimit.allowNothing(), "allowNothing"); + } + + @Test + public void testPerBlockAllowNothingAllowsNothing() throws Exception { + assertAllowsNothing(PerBlock.allowNothing(), "PerBlock.allowNothing"); + } + + private void assertAllowsNothing(Object value, String path) throws Exception { + int checked = 0; + for (Field field : value.getClass().getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) { + continue; + } + checked++; + field.setAccessible(true); + Object fieldValue = field.get(value); + String fieldPath = path + "." + field.getName(); + if (field.getType() == boolean.class) { + assertFalse((boolean) fieldValue, fieldPath + " should be false"); + } else if (field.getType() == int.class && field.getName().equals("minSignatureVersion")) { + assertEquals(1, fieldValue, fieldPath + " should be the highest supported version"); + } else if (field.getType() == int.class) { + assertEquals(0, fieldValue, fieldPath + " should be 0"); + } else if (Set.class.isAssignableFrom(field.getType())) { + // null would allow anything + assertNotNull(fieldValue, fieldPath + " should be an empty set, not null"); + assertTrue(((Set) fieldValue).isEmpty(), fieldPath + " should be empty"); + } else if (field.getType() == PerBlock.class) { + assertAllowsNothing(fieldValue, fieldPath); + } else { + throw new AssertionError(fieldPath + " has a type this test doesn't know how to check"); + } + } + assertTrue(checked > 0, path + " has no fields to check"); + } + + @Test + public void testAllowNothingRejectsAToken() throws Exception { + byte[] token = authority(b -> b.addFact("a(1)")).serialize(); + assertRejected(Reason.TOKEN_TOO_LARGE, token, DeserializationLimit.allowNothing()); + } + + // these are the messages that biscuit-swift's DeserializationLimitError uses + @Test + public void testErrorMessagesMatchBiscuitSwift() throws Exception { + byte[] token = authority(b -> b.addFact("a(1)")).serialize(); + Error.FormatError.DeserializationLimitError tooLarge = + assertThrows( + Error.FormatError.DeserializationLimitError.class, + () -> + Biscuit.fromBytes( + token, + root.getPublicKey(), + DeserializationLimit.allowEverything().setMaxTokenSize(0))); + assertEquals("Biscuit is too large", tooLarge.getMessage()); + assertEquals("Biscuit Datalog block is too large", Reason.BLOCK_TOO_LARGE.description()); + assertEquals("Biscuit block contains too many facts", Reason.TOO_MANY_FACTS.description()); + assertEquals( + "Biscuit contains attenuations without external signatures, which are not allowed", + Reason.ATTENUATIONS_WITHOUT_EXTERNAL_SIGNATURES_NOT_ALLOWED.description()); + } + + @Test + public void testAllowEverythingAcceptsAToken() throws Exception { + Biscuit token = + authority( + b -> { + b.addFact("a(1)"); + b.addCheck("check if [1, 2].all($x -> $x > 0)"); + }) + .attenuate(new Block().addCheck("check if a(1)"), Algorithm.Ed25519); + byte[] bytes = token.serialize(); + + assertEquals( + token.print(), + Biscuit.fromBytes(bytes, root.getPublicKey(), DeserializationLimit.allowEverything()) + .print()); + } + + @Test + public void testMaxTokenSize() throws Exception { + byte[] token = authority(b -> b.addFact("a(1)")).serialize(); + assertAccepted(token, DeserializationLimit.allowEverything().setMaxTokenSize(token.length)); + assertRejected( + Reason.TOKEN_TOO_LARGE, + token, + DeserializationLimit.allowEverything().setMaxTokenSize(token.length - 1)); + } + + @Test + public void testMaxBlocks() throws Exception { + byte[] token = + authority(b -> b.addFact("a(1)")) + .attenuate(new Block().addCheck("check if a(1)"), Algorithm.Ed25519) + .serialize(); + assertAccepted(token, DeserializationLimit.allowEverything().setMaxBlocks(2)); + assertRejected( + Reason.TOO_MANY_BLOCKS, token, DeserializationLimit.allowEverything().setMaxBlocks(1)); + } + + @Test + public void testSealedAndUnsealedTokens() throws Exception { + Biscuit unsealed = authority(b -> b.addFact("a(1)")); + byte[] unsealedBytes = unsealed.serialize(); + Biscuit sealed = Biscuit.fromBytes(unsealedBytes, root.getPublicKey()); + assertTrue(sealed.serializedBiscuit.seal().isOk()); + byte[] sealedBytes = sealed.serialize(); + + DeserializationLimit noSealed = + DeserializationLimit.allowEverything().setAllowSealedTokens(false); + DeserializationLimit noUnsealed = + DeserializationLimit.allowEverything().setAllowUnsealedTokens(false); + assertAccepted(unsealedBytes, noSealed); + assertAccepted(sealedBytes, noUnsealed); + assertRejected(Reason.SEALED_TOKENS_NOT_ALLOWED, sealedBytes, noSealed); + assertRejected(Reason.UNSEALED_TOKENS_NOT_ALLOWED, unsealedBytes, noUnsealed); + } + + @Test + public void testAttenuationsWithAndWithoutExternalSignatures() throws Exception { + KeyPair external = KeyPair.generate(Algorithm.Ed25519, rng); + Biscuit plain = authority(b -> b.addFact("a(1)")); + byte[] withoutExternal = + plain.attenuate(new Block().addCheck("check if a(1)"), Algorithm.Ed25519).serialize(); + byte[] withExternal = thirdPartyToken(plain, external).serialize(); + + DeserializationLimit noExternal = + DeserializationLimit.allowEverything().setAllowAttenuationsWithExternalSignatures(false); + DeserializationLimit onlyExternal = + DeserializationLimit.allowEverything().setAllowAttenuationsWithoutExternalSignatures(false); + + assertAccepted(withoutExternal, noExternal); + assertAccepted(withExternal, onlyExternal); + assertRejected( + Reason.ATTENUATIONS_WITH_EXTERNAL_SIGNATURES_NOT_ALLOWED, withExternal, noExternal); + assertRejected( + Reason.ATTENUATIONS_WITHOUT_EXTERNAL_SIGNATURES_NOT_ALLOWED, withoutExternal, onlyExternal); + // the authority block is not an attenuation + assertAccepted(plain.serialize(), onlyExternal); + } + + @Test + public void testInternalSigningAlgorithms() throws Exception { + KeyPair secp = KeyPair.generate(Algorithm.SECP256R1, rng); + byte[] ed25519Token = authority(b -> b.addFact("a(1)")).serialize(); + byte[] secpToken = authorityWith(secp, b -> b.addFact("a(1)")).serialize(); + + DeserializationLimit onlyEd25519 = + DeserializationLimit.allowEverything() + .setAllowedInternalSigningAlgorithms(Set.of(Algorithm.Ed25519)); + DeserializationLimit onlySecp = + DeserializationLimit.allowEverything() + .setAllowedInternalSigningAlgorithms(Set.of(Algorithm.SECP256R1)); + + assertAccepted(ed25519Token, root, onlyEd25519); + assertAccepted(secpToken, secp, onlySecp); + assertRejected(Reason.INTERNAL_SIGNING_ALGORITHM_NOT_ALLOWED, ed25519Token, root, onlySecp); + assertRejected(Reason.INTERNAL_SIGNING_ALGORITHM_NOT_ALLOWED, secpToken, secp, onlyEd25519); + } + + @Test + public void testExternalSigningAlgorithms() throws Exception { + KeyPair secp = KeyPair.generate(Algorithm.SECP256R1, rng); + Biscuit plain = authority(b -> b.addFact("a(1)")); + byte[] token = thirdPartyToken(plain, secp).serialize(); + + assertAccepted( + token, + DeserializationLimit.allowEverything() + .setAllowedExternalSigningAlgorithms(Set.of(Algorithm.SECP256R1))); + assertRejected( + Reason.EXTERNAL_SIGNING_ALGORITHM_NOT_ALLOWED, + token, + DeserializationLimit.allowEverything() + .setAllowedExternalSigningAlgorithms(Set.of(Algorithm.Ed25519))); + // the internal algorithms don't restrict the third party keys + assertAccepted( + token, + DeserializationLimit.allowEverything() + .setAllowedInternalSigningAlgorithms(Set.of(Algorithm.Ed25519))); + } + + @Test + public void testMinSignatureVersion() throws Exception { + KeyPair secp = KeyPair.generate(Algorithm.SECP256R1, rng); + // blocks using only Ed25519 and old datalog features use version 0 signatures + byte[] version0 = authority(b -> b.addFact("a(1)")).serialize(); + byte[] version1 = authorityWith(secp, b -> b.addFact("a(1)")).serialize(); + + DeserializationLimit atLeast1 = + DeserializationLimit.allowEverything().setMinSignatureVersion(1); + assertAccepted(version0, DeserializationLimit.allowEverything().setMinSignatureVersion(0)); + assertAccepted(version1, secp, atLeast1); + assertRejected(Reason.SIGNATURE_VERSION_TOO_LOW, version0, atLeast1); + } + + @Test + public void testMinSignatureVersionAboveTheHighestSupportedIsRejected() { + assertThrows( + IllegalArgumentException.class, + () -> DeserializationLimit.allowEverything().setMinSignatureVersion(2)); + assertDoesNotThrow(() -> DeserializationLimit.allowEverything().setMinSignatureVersion(1)); + } + + @Test + public void testDeserializationLimitEqualsAndHashCode() { + DeserializationLimit everything = DeserializationLimit.allowEverything(); + assertEquals(everything, DeserializationLimit.allowEverything()); + assertEquals(everything.hashCode(), DeserializationLimit.allowEverything().hashCode()); + assertEquals(DeserializationLimit.allowNothing(), DeserializationLimit.allowNothing()); + assertNotEquals(everything, DeserializationLimit.allowNothing()); + assertNotEquals(null, everything); + assertNotEquals("not a limit", everything); + + // each kind of setting takes part in the comparison, including the nested per block limits + DeserializationLimit changed = DeserializationLimit.allowEverything().setMaxBlocks(1); + assertNotEquals(everything, changed); + changed = DeserializationLimit.allowEverything().setAllowSealedTokens(false); + assertNotEquals(everything, changed); + changed = + DeserializationLimit.allowEverything() + .setAllowedInternalSigningAlgorithms(Set.of(Algorithm.Ed25519)); + assertNotEquals(everything, changed); + changed = DeserializationLimit.allowEverything(); + changed.getAuthority().setMaxFacts(1); + assertNotEquals(everything, changed); + changed = DeserializationLimit.allowEverything(); + changed.getAttenuations().setAllowClosures(false); + assertNotEquals(everything, changed); + + // and equal limits built in different ways are equal + DeserializationLimit rebuilt = DeserializationLimit.allowEverything().setMaxBlocks(1); + rebuilt.setMaxBlocks(Integer.MAX_VALUE); + assertEquals(everything, rebuilt); + assertEquals(everything.hashCode(), rebuilt.hashCode()); + } + + // equals and hashCode compare a list of the fields, so a field which is left out of that list + // would + // silently stop taking part in equality; this checks each field by reflection, so that includes + // fields added in the future + @Test + public void testEveryFieldTakesPartInEquality() throws Exception { + // for each class: a limit to change, an untouched limit to compare it to, and a source of + // values + Object[][] limits = { + { + DeserializationLimit.allowNothing(), + DeserializationLimit.allowNothing(), + DeserializationLimit.allowEverything() + }, + {PerBlock.allowNothing(), PerBlock.allowNothing(), PerBlock.allowEverything()} + }; + + for (Object[] limit : limits) { + Object changed = limit[0]; + Object untouched = limit[1]; + Object everything = limit[2]; + + for (Field field : changed.getClass().getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) { + continue; + } + field.setAccessible(true); + String name = changed.getClass().getSimpleName() + "." + field.getName(); + + Object nothingValue = field.get(changed); + Object everythingValue = field.get(everything); + assertNotEquals( + nothingValue, + everythingValue, + name + " is the same in allowNothing and allowEverything, so this test can't use it"); + + // change only this field, and the limits must no longer be equal + field.set(changed, everythingValue); + assertNotEquals(untouched, changed, name + " is not used by equals"); + field.set(changed, nothingValue); + } + assertEquals(untouched, changed, "every field was put back"); + } + } + + @Test + public void testDeserializingABlockAddsItsSymbolsAndKeysToTheSymbolTable() throws Exception { + KeyPair key = KeyPair.generate(Algorithm.Ed25519, rng); + Block builder = new Block(); + builder.addFact("a(\"hello\")"); + builder.addCheck("check if b(1) trusting ed25519/" + key.getPublicKey().toHex()); + byte[] bytes = builder.build().toBytes().getOk(); + + org.eclipse.biscuit.datalog.SymbolTable symbols = new org.eclipse.biscuit.datalog.SymbolTable(); + org.eclipse.biscuit.token.Block.fromBytes( + bytes, Optional.empty(), PerBlock.allowEverything(), symbols) + .getOk(); + + assertTrue(symbols.symbols().contains("hello")); + assertEquals(java.util.List.of(key.getPublicKey()), symbols.getPublicKeys()); + } + + @Test + public void testOnlyBlocksWithoutExternalSignaturesAddToTheSharedSymbolTable() throws Exception { + KeyPair external = KeyPair.generate(Algorithm.Ed25519, rng); + Biscuit authority = authority(b -> b.addFact("authorityname(1)")); + Biscuit attenuated = + authority.attenuate(new Block().addFact("attenuationname(1)"), Algorithm.Ed25519); + + Block thirdParty = new Block(); + thirdParty.addFact("thirdpartyname(1)"); + ThirdPartyBlockContents contents = + attenuated.thirdPartyRequest().createBlock(external, thirdParty).getOk(); + byte[] token = attenuated.appendThirdPartyBlock(external.getPublicKey(), contents).serialize(); + + org.eclipse.biscuit.datalog.SymbolTable symbols = new org.eclipse.biscuit.datalog.SymbolTable(); + UnverifiedBiscuit.fromBytesWithSymbols(token, symbols); + + assertTrue(symbols.symbols().contains("authorityname")); + assertTrue(symbols.symbols().contains("attenuationname")); + // a third party block keeps its own symbols + assertFalse(symbols.symbols().contains("thirdpartyname")); + } + + @Test + public void testTrustedScopeKindsAreComparedByTheirAlgorithm() { + TrustedScopeKind ed25519 = TrustedScopeKind.publicKey(Algorithm.Ed25519); + assertEquals(ed25519, TrustedScopeKind.publicKey(Algorithm.Ed25519)); + assertEquals(ed25519.hashCode(), TrustedScopeKind.publicKey(Algorithm.Ed25519).hashCode()); + assertFalse(ed25519.equals(TrustedScopeKind.publicKey(Algorithm.SECP256R1))); + assertFalse(ed25519.equals(TrustedScopeKind.AUTHORITY)); + assertFalse(TrustedScopeKind.AUTHORITY.equals(TrustedScopeKind.PREVIOUS)); + assertTrue(Set.of(ed25519).contains(TrustedScopeKind.publicKey(Algorithm.Ed25519))); + assertFalse(Set.of(ed25519).contains(TrustedScopeKind.publicKey(Algorithm.SECP256R1))); + // every algorithm the protobuf defines has a kind, without this class having to list them + for (Algorithm algorithm : Algorithm.values()) { + assertNotNull(TrustedScopeKind.publicKey(algorithm)); + } + } + + @Test + public void testATermWithNoContentIsRejectedWithItsKindInTheMessage() { + var result = + org.eclipse.biscuit.datalog.Term.deserializeEnumV2( + Schema.TermV2.getDefaultInstance(), + PerBlock.allowEverything(), + new org.eclipse.biscuit.datalog.SymbolTable()); + + assertTrue(result.isErr()); + assertEquals( + new Error.FormatError.DeserializationError("invalid Term kind: CONTENT_NOT_SET"), + result.getErr()); + } + + @Test + public void testNegativeLimitsAreRejected() { + DeserializationLimit limit = DeserializationLimit.allowEverything(); + assertThrows(IllegalArgumentException.class, () -> limit.setMaxTokenSize(-1)); + assertThrows(IllegalArgumentException.class, () -> limit.setMaxBlocks(-1)); + assertThrows(IllegalArgumentException.class, () -> limit.setMinSignatureVersion(-1)); + assertThrows(IllegalArgumentException.class, () -> limit.getAuthority().setMaxFacts(-1)); + assertThrows(IllegalArgumentException.class, () -> limit.getAttenuations().setMaxBlockSize(-1)); + assertDoesNotThrow(() -> limit.setMaxBlocks(0)); + } + + @Test + public void testTokenLevelLimitsAreCheckedBeforeSignatures() throws Exception { + Biscuit token = + authority(b -> b.addFact("a(1)")).attenuate(new Block().addFact("b(1)"), Algorithm.Ed25519); + Schema.Biscuit.Builder tampered = Schema.Biscuit.parseFrom(token.serialize()).toBuilder(); + byte[] signature = tampered.getAuthority().getSignature().toByteArray(); + signature[0] ^= 1; + tampered.getAuthorityBuilder().setSignature(ByteString.copyFrom(signature)); + byte[] bytes = tampered.build().toByteArray(); + + // the tampering is noticed... + assertThrows( + Error.FormatError.Signature.class, + () -> + Biscuit.fromBytes(bytes, root.getPublicKey(), DeserializationLimit.allowEverything())); + // ...unless the token violates a token level setting, which is checked first + assertRejected( + Reason.TOO_MANY_BLOCKS, bytes, DeserializationLimit.allowEverything().setMaxBlocks(1)); + } + + @Test + public void testDeserializationLimitIsCheckedBeforeLookingUpTheRootKey() throws Exception { + byte[] token = authority(b -> b.addFact("a(1)")).serialize(); + AtomicInteger lookups = new AtomicInteger(); + KeyDelegate delegate = + keyId -> { + lookups.incrementAndGet(); + return Optional.of(root.getPublicKey()); + }; + + assertThrows( + Error.FormatError.DeserializationLimitError.class, + () -> + Biscuit.fromBytes( + token, delegate, DeserializationLimit.allowEverything().setMaxBlocks(0))); + assertEquals(0, lookups.get()); + Biscuit.fromBytes(token, delegate, DeserializationLimit.allowEverything()); + assertEquals(1, lookups.get()); + } + + @Test + public void testUnverifiedBiscuitChecksTheDeserializationLimit() throws Exception { + byte[] token = authority(b -> b.addFact("a(1)")).serialize(); + String base64 = Biscuit.fromBytes(token, root.getPublicKey()).serializeBase64Url(); + + DeserializationLimit noFacts = DeserializationLimit.allowEverything(); + noFacts.getAuthority().setMaxFacts(0); + assertThrows( + Error.FormatError.DeserializationLimitError.class, + () -> UnverifiedBiscuit.fromBytes(token, noFacts)); + assertThrows( + Error.FormatError.DeserializationLimitError.class, + () -> UnverifiedBiscuit.fromBase64Url(base64, noFacts)); + assertThrows( + Error.FormatError.DeserializationLimitError.class, + () -> Biscuit.fromBase64Url(base64, root.getPublicKey(), noFacts)); + assertDoesNotThrow( + () -> UnverifiedBiscuit.fromBytes(token, DeserializationLimit.allowEverything())); + } + + @Test + public void testAuthorityAndAttenuationsHaveSeparateLimits() throws Exception { + byte[] token = + authority(b -> b.addFact("a(1)").addFact("a(2)")) + .attenuate(new Block().addFact("b(1)").addFact("b(2)"), Algorithm.Ed25519) + .serialize(); + + DeserializationLimit limitsAuthority = DeserializationLimit.allowEverything(); + limitsAuthority.getAuthority().setMaxFacts(1); + DeserializationLimit limitsAttenuations = DeserializationLimit.allowEverything(); + limitsAttenuations.getAttenuations().setMaxFacts(1); + DeserializationLimit limitsNeither = DeserializationLimit.allowEverything(); + limitsNeither.getAuthority().setMaxFacts(2); + limitsNeither.getAttenuations().setMaxFacts(2); + + assertRejected(Reason.TOO_MANY_FACTS, token, limitsAuthority); + assertRejected(Reason.TOO_MANY_FACTS, token, limitsAttenuations); + assertAccepted(token, limitsNeither); + } + + @Test + public void testMaxBlockSize() throws Exception { + assertBlockLimit( + Reason.BLOCK_TOO_LARGE, + b -> b.addFact("a(\"a string that makes the block larger than the limit\")"), + p -> p.setMaxBlockSize(30)); + } + + @Test + public void testMaxFacts() throws Exception { + assertBlockLimit( + Reason.TOO_MANY_FACTS, b -> b.addFact("a(1)").addFact("a(2)"), p -> p.setMaxFacts(1)); + } + + @Test + public void testMaxRules() throws Exception { + assertBlockLimit( + Reason.TOO_MANY_RULES, + b -> b.addRule("r($x) <- f($x)").addRule("s($x) <- f($x)"), + p -> p.setMaxRules(1)); + } + + @Test + public void testMaxChecks() throws Exception { + assertBlockLimit( + Reason.TOO_MANY_CHECKS, + b -> b.addCheck("check if a(1)").addCheck("reject if b(1)"), + p -> p.setMaxChecks(1)); + } + + @Test + public void testMaxSymbols() throws Exception { + assertBlockLimit( + Reason.TOO_MANY_SYMBOLS, + b -> b.addFact("a(\"one\", \"two\", \"three\")"), + p -> p.setMaxSymbols(2)); + } + + @Test + public void testMaxPublicKeys() throws Exception { + KeyPair key = KeyPair.generate(Algorithm.Ed25519, rng); + assertBlockLimit( + Reason.TOO_MANY_PUBLIC_KEYS, + b -> b.addCheck("check if a(1) trusting ed25519/" + key.getPublicKey().toHex()), + p -> p.setMaxPublicKeys(0)); + } + + @Test + public void testMaxContextLength() throws Exception { + assertBlockLimit( + Reason.CONTEXT_TOO_LONG, b -> b.setContext("four"), p -> p.setMaxContextLength(3)); + } + + @Test + public void testMaxQueriesPerCheck() throws Exception { + assertBlockLimit( + Reason.TOO_MANY_QUERIES, + b -> b.addCheck("check if a(1) or b(1)"), + p -> p.setMaxQueriesPerCheck(1)); + } + + @Test + public void testMaxPredicatesPerBody() throws Exception { + assertBlockLimit( + Reason.TOO_MANY_PREDICATES, + b -> b.addCheck("check if a(1), b(1)"), + p -> p.setMaxPredicatesPerBody(1)); + assertBlockLimit( + Reason.TOO_MANY_PREDICATES, + b -> b.addRule("r($x) <- a($x), b($x)"), + p -> p.setMaxPredicatesPerBody(1)); + } + + @Test + public void testMaxExpressionsPerBody() throws Exception { + assertBlockLimit( + Reason.TOO_MANY_EXPRESSIONS, + b -> b.addCheck("check if a($x), $x > 1, $x < 5"), + p -> p.setMaxExpressionsPerBody(1)); + assertBlockLimit( + Reason.TOO_MANY_EXPRESSIONS, + b -> b.addRule("r($x) <- a($x), $x > 1, $x < 5"), + p -> p.setMaxExpressionsPerBody(1)); + } + + @Test + public void testMaxOpsPerExpression() throws Exception { + // 1 2 + 3 + 5 > is seven ops + BlockSetup sevenOps = b -> b.addCheck("check if 1 + 2 + 3 > 5"); + assertBlockLimit(Reason.TOO_MANY_OPS, sevenOps, p -> p.setMaxOpsPerExpression(6)); + assertAccepted( + authority(sevenOps).serialize(), authorityLimits(p -> p.setMaxOpsPerExpression(7))); + } + + @Test + public void testOpsInClosuresCountTowardsTheirExpression() throws Exception { + // [1] (closure: $x 0 >) all is six ops once the closure's own ops are counted + BlockSetup closure = b -> b.addCheck("check if [1].all($x -> $x > 0)"); + assertBlockLimit(Reason.TOO_MANY_OPS, closure, p -> p.setMaxOpsPerExpression(5)); + assertAccepted( + authority(closure).serialize(), authorityLimits(p -> p.setMaxOpsPerExpression(6))); + } + + @Test + public void testMaxTermsPerPredicate() throws Exception { + assertBlockLimit( + Reason.TOO_MANY_TERMS, b -> b.addFact("a(1, 2, 3)"), p -> p.setMaxTermsPerPredicate(2)); + assertBlockLimit( + Reason.TOO_MANY_TERMS, + b -> b.addCheck("check if a(1, 2, 3)"), + p -> p.setMaxTermsPerPredicate(2)); + } + + @Test + public void testMaxNameLength() throws Exception { + // predicate names + assertBlockLimit( + Reason.NAME_TOO_LONG, b -> b.addFact("long_name(1)"), p -> p.setMaxNameLength(5)); + // variable names + assertBlockLimit( + Reason.NAME_TOO_LONG, + b -> b.addCheck("check if a($long_name)"), + p -> p.setMaxNameLength(5)); + // closure parameter names + assertBlockLimit( + Reason.NAME_TOO_LONG, + b -> b.addCheck("check if [1].all($a -> $a > 0) or [1].all($long_name -> $long_name > 0)"), + p -> p.setMaxNameLength(5)); + // string values are not names + assertAccepted( + authority(b -> b.addFact("a(\"long string\")")).serialize(), + authorityLimits(p -> p.setMaxNameLength(5))); + } + + @Test + public void testMaxStringLengthIsMeasuredInBytes() throws Exception { + // each of these characters is two bytes in UTF-8 + BlockSetup string = b -> b.addFact("a(\"\u00e9\u00e9\u00e9\")"); + assertBlockLimit(Reason.STRING_TOO_LONG, string, p -> p.setMaxStringLength(5)); + assertAccepted(authority(string).serialize(), authorityLimits(p -> p.setMaxStringLength(6))); + } + + @Test + public void testNamesDefinedInEarlierBlocksAreChecked() throws Exception { + byte[] token = + authority(b -> b.addFact("long_name(1)")) + .attenuate(new Block().addCheck("check if long_name(1)"), Algorithm.Ed25519) + .serialize(); + // the attenuation refers to a symbol from the authority block + DeserializationLimit limitsAttenuations = DeserializationLimit.allowEverything(); + limitsAttenuations.getAttenuations().setMaxNameLength(5); + assertRejected(Reason.NAME_TOO_LONG, token, limitsAttenuations); + DeserializationLimit limitsAuthority = DeserializationLimit.allowEverything(); + limitsAuthority.getAuthority().setMaxNameLength(5); + assertRejected(Reason.NAME_TOO_LONG, token, limitsAuthority); + } + + @Test + public void testMaxStringLength() throws Exception { + assertBlockLimit( + Reason.STRING_TOO_LONG, b -> b.addFact("a(\"abcd\")"), p -> p.setMaxStringLength(3)); + assertBlockLimit( + Reason.STRING_TOO_LONG, b -> b.addFact("a({\"abcd\": 1})"), p -> p.setMaxStringLength(3)); + // names are not strings + assertAccepted( + authority(b -> b.addFact("long_name(1)")).serialize(), + authorityLimits(p -> p.setMaxStringLength(3))); + } + + @Test + public void testMaxBytesLength() throws Exception { + assertBlockLimit( + Reason.BYTES_TOO_LONG, b -> b.addFact("a(hex:010203)"), p -> p.setMaxBytesLength(2)); + } + + @Test + public void testMaxCollectionLengths() throws Exception { + assertBlockLimit( + Reason.SET_TOO_LONG, b -> b.addFact("a({1, 2, 3})"), p -> p.setMaxSetLength(2)); + assertBlockLimit( + Reason.ARRAY_TOO_LONG, b -> b.addFact("a([1, 2, 3])"), p -> p.setMaxArrayLength(2)); + assertBlockLimit( + Reason.MAP_TOO_LONG, b -> b.addFact("a({1: 1, 2: 2, 3: 3})"), p -> p.setMaxMapLength(2)); + // the limits only apply to their own kind of collection + assertAccepted( + authority(b -> b.addFact("a([1, 2, 3])")).serialize(), + authorityLimits(p -> p.setMaxSetLength(0).setMaxMapLength(0))); + } + + @Test + public void testNestedCollectionsAreChecked() throws Exception { + assertBlockLimit( + Reason.ARRAY_TOO_LONG, + b -> b.addFact("a({\"k\": [1, 2, 3]})"), + p -> p.setMaxArrayLength(2)); + } + + @Test + public void testClosures() throws Exception { + assertBlockLimit( + Reason.CLOSURES_NOT_ALLOWED, + b -> b.addCheck("check if [1].all($x -> $x > 0)"), + p -> p.setAllowClosures(false)); + assertAccepted( + authority(b -> b.addCheck("check if 1 > 0")).serialize(), + authorityLimits(p -> p.setAllowClosures(false))); + } + + @Test + public void testBinaryOperations() throws Exception { + Set allButRegex = EnumSet.complementOf(EnumSet.of(Op.BinaryOp.Regex)); + assertBlockLimit( + Reason.BINARY_OPERATION_NOT_ALLOWED, + b -> b.addCheck("check if \"abc\".matches(\"a+\")"), + p -> p.setAllowedBinaryOps(allButRegex)); + assertAccepted( + authority(b -> b.addCheck("check if \"abc\".starts_with(\"a\")")).serialize(), + authorityLimits(p -> p.setAllowedBinaryOps(allButRegex))); + assertBlockLimit( + Reason.BINARY_OPERATION_NOT_ALLOWED, + b -> b.addCheck("check if 1 + 2 > 0"), + p -> p.setAllowedBinaryOps(Set.of(Op.BinaryOp.Add))); + } + + @Test + public void testUnaryOperations() throws Exception { + assertBlockLimit( + Reason.UNARY_OPERATION_NOT_ALLOWED, + b -> b.addCheck("check if !false"), + p -> p.setAllowedUnaryOps(Set.of(Op.UnaryOp.Length))); + assertAccepted( + authority(b -> b.addCheck("check if \"abc\".length() > 1")).serialize(), + authorityLimits( + p -> + p.setAllowedUnaryOps(Set.of(Op.UnaryOp.Length)) + .setAllowedBinaryOps(Set.of(Op.BinaryOp.GreaterThan)))); + } + + @Test + public void testTermTypes() throws Exception { + Set onlyIntegers = Set.of(TermType.INTEGER); + assertBlockLimit( + Reason.TERM_TYPE_NOT_ALLOWED, + b -> b.addFact("a(\"string\")"), + p -> p.setAllowedTermTypes(onlyIntegers)); + // types of terms inside collections and expressions are checked too + assertBlockLimit( + Reason.TERM_TYPE_NOT_ALLOWED, + b -> b.addFact("a([true])"), + p -> p.setAllowedTermTypes(Set.of(TermType.ARRAY, TermType.INTEGER))); + assertBlockLimit( + Reason.TERM_TYPE_NOT_ALLOWED, + b -> b.addCheck("check if 1 < 2 || null == null"), + p -> p.setAllowedTermTypes(onlyIntegers)); + // variables are not values + assertAccepted( + authority(b -> b.addCheck("check if a($x), $x > 0")).serialize(), + authorityLimits(p -> p.setAllowedTermTypes(onlyIntegers))); + } + + @Test + public void testMapKeyTypes() throws Exception { + assertBlockLimit( + Reason.MAP_KEY_TYPE_NOT_ALLOWED, + b -> b.addFact("a({\"key\": 1})"), + p -> p.setAllowedMapKeyTypes(Set.of(MapKeyType.INTEGER))); + assertAccepted( + authority(b -> b.addFact("a({1: 1})")).serialize(), + authorityLimits(p -> p.setAllowedMapKeyTypes(Set.of(MapKeyType.INTEGER)))); + } + + @Test + public void testCheckKinds() throws Exception { + Set onlyOne = Set.of(Check.Kind.ONE); + assertBlockLimit( + Reason.CHECK_KIND_NOT_ALLOWED, + b -> b.addCheck("check all a($x), $x > 0"), + p -> p.setAllowedCheckKinds(onlyOne)); + assertBlockLimit( + Reason.CHECK_KIND_NOT_ALLOWED, + b -> b.addCheck("reject if a(1)"), + p -> p.setAllowedCheckKinds(onlyOne)); + assertAccepted( + authority(b -> b.addCheck("check if a(1)")).serialize(), + authorityLimits(p -> p.setAllowedCheckKinds(onlyOne))); + } + + @Test + public void testTrustedScopes() throws Exception { + KeyPair key = KeyPair.generate(Algorithm.Ed25519, rng); + String publicKey = "ed25519/" + key.getPublicKey().toHex(); + Set onlyAuthority = Set.of(TrustedScopeKind.AUTHORITY); + + // scopes of a check query, of a rule and of the block itself + assertBlockLimit( + Reason.TRUSTED_SCOPE_NOT_ALLOWED, + b -> b.addCheck("check if a(1) trusting previous"), + p -> p.setAllowedTrustingScopes(onlyAuthority)); + assertBlockLimit( + Reason.TRUSTED_SCOPE_NOT_ALLOWED, + b -> b.addRule("r($x) <- a($x) trusting previous"), + p -> p.setAllowedTrustingScopes(onlyAuthority)); + assertBlockLimit( + Reason.TRUSTED_SCOPE_NOT_ALLOWED, + b -> b.addScope(org.eclipse.biscuit.token.builder.Scope.previous()), + p -> p.setAllowedTrustingScopes(onlyAuthority)); + assertAccepted( + authority(b -> b.addCheck("check if a(1) trusting authority")).serialize(), + authorityLimits(p -> p.setAllowedTrustingScopes(onlyAuthority))); + + // the algorithm of a public key is looked up in the block's public keys + BlockSetup trustsKey = b -> b.addCheck("check if a(1) trusting " + publicKey); + assertBlockLimit( + Reason.TRUSTED_SCOPE_NOT_ALLOWED, + trustsKey, + p -> + p.setAllowedTrustingScopes( + Set.of( + TrustedScopeKind.AUTHORITY, + TrustedScopeKind.PREVIOUS, + TrustedScopeKind.publicKey(Algorithm.SECP256R1)))); + assertAccepted( + authority(trustsKey).serialize(), + authorityLimits( + p -> + p.setAllowedTrustingScopes(Set.of(TrustedScopeKind.publicKey(Algorithm.Ed25519))))); + } + + @Test + public void testPublicKeysFromEarlierBlocksCanBeTrusted() throws Exception { + KeyPair key = KeyPair.generate(Algorithm.Ed25519, rng); + String publicKey = "ed25519/" + key.getPublicKey().toHex(); + // the attenuation refers to the key through the authority block's public key table + byte[] token = + authority(b -> b.addCheck("check if a(1) trusting " + publicKey)) + .attenuate( + new Block().addCheck("check if b(1) trusting " + publicKey), Algorithm.Ed25519) + .serialize(); + + DeserializationLimit onlyEd25519 = DeserializationLimit.allowEverything(); + onlyEd25519 + .getAuthority() + .setAllowedTrustingScopes(Set.of(TrustedScopeKind.publicKey(Algorithm.Ed25519))); + onlyEd25519 + .getAttenuations() + .setAllowedTrustingScopes(Set.of(TrustedScopeKind.publicKey(Algorithm.Ed25519))); + DeserializationLimit onlyAuthority = DeserializationLimit.allowEverything(); + onlyAuthority.getAttenuations().setAllowedTrustingScopes(Set.of(TrustedScopeKind.AUTHORITY)); + + assertAccepted(token, onlyEd25519); + assertRejected(Reason.TRUSTED_SCOPE_NOT_ALLOWED, token, onlyAuthority); + } + + @Test + public void testThirdPartyBlocksAreChecked() throws Exception { + KeyPair external = KeyPair.generate(Algorithm.Ed25519, rng); + byte[] token = thirdPartyToken(authority(b -> b.addFact("a(1)")), external).serialize(); + + // thirdPartyToken's block has two facts and uses its own symbol table + DeserializationLimit limitsFacts = DeserializationLimit.allowEverything(); + limitsFacts.getAttenuations().setMaxFacts(1); + DeserializationLimit limitsNames = DeserializationLimit.allowEverything(); + limitsNames.getAttenuations().setMaxNameLength(3); + assertRejected(Reason.TOO_MANY_FACTS, token, limitsFacts); + assertRejected(Reason.NAME_TOO_LONG, token, limitsNames); + limitsFacts.getAttenuations().setMaxFacts(2); + limitsNames.getAttenuations().setMaxNameLength(5); + assertAccepted(token, limitsFacts); + assertAccepted(token, limitsNames); + } + + @Test + public void testSettersCopyTheirSets() { + Set kinds = EnumSet.of(Check.Kind.ONE); + PerBlock perBlock = PerBlock.allowEverything().setAllowedCheckKinds(kinds); + kinds.add(Check.Kind.ALL); + assertEquals(Set.of(Check.Kind.ONE), perBlock.getAllowedCheckKinds()); + assertNull(PerBlock.allowEverything().getAllowedCheckKinds()); + assertEquals(PerBlock.allowEverything(), PerBlock.allowEverything()); + assertFalse(PerBlock.allowEverything().equals(PerBlock.allowNothing())); + } + + /** + * Checks that a limit applies to the authority block and to attenuations, and only to the block + * it is set for + */ + private void assertBlockLimit(Reason reason, BlockSetup setup, Consumer restrict) + throws Exception { + // in the authority block + byte[] authorityToken = authority(setup).serialize(); + assertRejected(reason, authorityToken, authorityLimits(restrict)); + assertAccepted(authorityToken, attenuationLimits(restrict)); + + // in an attenuation block + Block attenuation = new Block(); + setup.apply(attenuation); + byte[] attenuatedToken = + authority(b -> b.addFact("base(1)")).attenuate(attenuation, Algorithm.Ed25519).serialize(); + assertRejected(reason, attenuatedToken, attenuationLimits(restrict)); + assertAccepted(attenuatedToken, authorityLimits(restrict)); + } + + private static DeserializationLimit authorityLimits(Consumer restrict) { + DeserializationLimit deserializationLimit = DeserializationLimit.allowEverything(); + restrict.accept(deserializationLimit.getAuthority()); + return deserializationLimit; + } + + private static DeserializationLimit attenuationLimits(Consumer restrict) { + DeserializationLimit deserializationLimit = DeserializationLimit.allowEverything(); + restrict.accept(deserializationLimit.getAttenuations()); + return deserializationLimit; + } + + private Biscuit authority(BlockSetup setup) throws Exception { + return authorityWith(root, setup); + } + + private Biscuit authorityWith(KeyPair key, BlockSetup setup) throws Exception { + Block block = new Block(); + setup.apply(block); + return Biscuit.make(rng, key, block.build()); + } + + /** Appends a block with two facts, signed by the external key, to the token */ + private Biscuit thirdPartyToken(Biscuit token, KeyPair external) throws Exception { + Block block = new Block(); + block.addFact("group(\"admin\")"); + block.addFact("other(1)"); + ThirdPartyBlockContents contents = + token.thirdPartyRequest().createBlock(external, block).getOk(); + return token.appendThirdPartyBlock(external.getPublicKey(), contents); + } + + private void assertAccepted(byte[] token, DeserializationLimit deserializationLimit) + throws Exception { + assertAccepted(token, root, deserializationLimit); + } + + private void assertAccepted( + byte[] token, KeyPair rootKey, DeserializationLimit deserializationLimit) throws Exception { + assertDoesNotThrow( + () -> Biscuit.fromBytes(token, rootKey.getPublicKey(), deserializationLimit)); + assertDoesNotThrow(() -> UnverifiedBiscuit.fromBytes(token, deserializationLimit)); + } + + private void assertRejected( + Reason reason, byte[] token, DeserializationLimit deserializationLimit) { + assertRejected(reason, token, root, deserializationLimit); + } + + private void assertRejected( + Reason reason, byte[] token, KeyPair rootKey, DeserializationLimit deserializationLimit) { + Error.FormatError.DeserializationLimitError verified = + assertThrows( + Error.FormatError.DeserializationLimitError.class, + () -> Biscuit.fromBytes(token, rootKey.getPublicKey(), deserializationLimit)); + assertEquals(reason, verified.getReason()); + Error.FormatError.DeserializationLimitError unverified = + assertThrows( + Error.FormatError.DeserializationLimitError.class, + () -> UnverifiedBiscuit.fromBytes(token, deserializationLimit)); + assertEquals(reason, unverified.getReason()); + } +}