World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#13719] feat(policy): add restricted Rego parser for read restrictions (#13478)
roryqibd301d1bb3e7
diff --git a/api/src/main/java/org/apache/gravitino/policy/PolicyContents.java b/api/src/main/java/org/apache/gravitino/policy/PolicyContents.javaindex 8ca63b1f85..b7e92193f6 100644--- a/api/src/main/java/org/apache/gravitino/policy/PolicyContents.java+++ b/api/src/main/java/org/apache/gravitino/policy/PolicyContents.java@@ -189,8 +189,14 @@ public class PolicyContents {/*** Creates a row-filter policy for tagged tables.*- * @param expression row-filter expression- * @return validated read-restriction policy content+ * <p>The expression must be a complete {@code restricted-rego-v1} program beginning with {@code+ * filter :=}. The server performs grammar and semantic validation when the policy is created or+ * updated.+ *+ * @param expression complete row-filter program+ * @return structurally validated read-restriction policy content+ * @throws IllegalArgumentException if the expression is blank or exceeds {@link+ * ReadRestrictionContent#MAX_SOURCE_LENGTH_BYTES}*/public static RowFilterContent rowFilter(String expression) {return new RowFilterContent(expression);@@ -199,8 +205,14 @@ public class PolicyContents {/*** Creates a column-mask policy for tagged tables or columns.*- * @param expression column-mask expression- * @return validated read-restriction policy content+ * <p>The expression must be a complete {@code restricted-rego-v1} program beginning with {@code+ * mask := action(...)}. The server performs grammar and semantic validation when the policy is+ * created or updated.+ *+ * @param expression complete column-mask program+ * @return structurally validated read-restriction policy content+ * @throws IllegalArgumentException if the expression is blank or exceeds {@link+ * ReadRestrictionContent#MAX_SOURCE_LENGTH_BYTES}*/public static ColumnMaskContent columnMask(String expression) {return new ColumnMaskContent(expression);diff --git a/api/src/test/java/org/apache/gravitino/policy/TestReadRestrictionContent.java b/api/src/test/java/org/apache/gravitino/policy/TestReadRestrictionContent.javaindex 4939291249..02f0ea5e4d 100644--- a/api/src/test/java/org/apache/gravitino/policy/TestReadRestrictionContent.java+++ b/api/src/test/java/org/apache/gravitino/policy/TestReadRestrictionContent.java@@ -61,7 +61,8 @@ public class TestReadRestrictionContent {Assertions.assertNotEquals(PolicyContents.rowFilter(expression), PolicyContents.rowFilter("filter := true"));Assertions.assertNotEquals(- PolicyContents.rowFilter(expression), PolicyContents.columnMask(expression));+ PolicyContents.rowFilter(expression),+ PolicyContents.columnMask("mask := action(\"replace-with-null\")"));}@Test@@ -76,14 +77,21 @@ public class TestReadRestrictionContent {void testValidatesUtf8ExpressionLength() {Assertions.assertEquals(16 * 1024, ReadRestrictionContent.MAX_SOURCE_LENGTH_BYTES);- String maximumLength = "é".repeat(ReadRestrictionContent.MAX_SOURCE_LENGTH_BYTES / 2);- String tooLong = maximumLength + "a";+ String rowFilterPrefix = "filter := true";+ String maximumRowFilter =+ rowFilterPrefix+ + " ".repeat(ReadRestrictionContent.MAX_SOURCE_LENGTH_BYTES - rowFilterPrefix.length());+ String columnMaskPrefix = "mask := action(\"replace-with-null\")";+ String maximumColumnMask =+ columnMaskPrefix+ + " "+ .repeat(ReadRestrictionContent.MAX_SOURCE_LENGTH_BYTES - columnMaskPrefix.length());- Assertions.assertDoesNotThrow(() -> PolicyContents.rowFilter(maximumLength));- Assertions.assertDoesNotThrow(() -> PolicyContents.columnMask(maximumLength));+ Assertions.assertDoesNotThrow(() -> PolicyContents.rowFilter(maximumRowFilter));+ Assertions.assertDoesNotThrow(() -> PolicyContents.columnMask(maximumColumnMask));Assertions.assertThrows(- IllegalArgumentException.class, () -> PolicyContents.rowFilter(tooLong));+ IllegalArgumentException.class, () -> PolicyContents.rowFilter(maximumRowFilter + "é"));Assertions.assertThrows(- IllegalArgumentException.class, () -> PolicyContents.columnMask(tooLong));+ IllegalArgumentException.class, () -> PolicyContents.columnMask(maximumColumnMask + "é"));}}diff --git a/core/build.gradle.kts b/core/build.gradle.ktsindex 7d88be97a0..bdd8cbbfc1 100644--- a/core/build.gradle.kts+++ b/core/build.gradle.kts@@ -106,6 +106,10 @@ artifacts {}tasks.test {+ val policiesDocument = rootProject.file("docs/policies.md")+ inputs.file(policiesDocument)+ systemProperty("gravitino.repositoryRoot", rootProject.projectDir.path)+val testMode = project.properties["testMode"] as? String ?: "embedded"if (testMode == "embedded") {environment("GRAVITINO_HOME", project.rootDir.path)diff --git a/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java b/core/src/main/java/org/apache/gravitino/policy/PolicyManager.javaindex 5c10ac000e..db194dd0b3 100644--- a/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java+++ b/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java@@ -39,6 +39,7 @@ import org.apache.gravitino.exceptions.NoSuchPolicyException;import org.apache.gravitino.exceptions.PolicyAlreadyExistsException;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.PolicyEntity;+import org.apache.gravitino.policy.rego.RestrictedRegoExpressionParserFacade;import org.apache.gravitino.storage.IdGenerator;import org.apache.gravitino.utils.MetadataObjectUtil;import org.apache.gravitino.utils.NameIdentifierUtil;@@ -116,6 +117,7 @@ public class PolicyManager implements PolicyDispatcher {NameIdentifier metalakeIdent = NameIdentifierUtil.ofMetalake(metalake);checkMetalake(metalakeIdent, entityStore);content.validate();+ validateReadRestrictionContent(type, content);PolicyEntity policyEntity =PolicyEntity.builder()@@ -335,6 +337,7 @@ public class PolicyManager implements PolicyDispatcher {}newContent = updateContent.getContent();+ validateReadRestrictionContent(policyType, newContent);} else {throw new IllegalArgumentException("Unsupported policy change: " + change);}@@ -349,4 +352,16 @@ public class PolicyManager implements PolicyDispatcher {return builder.build();}++ private static void validateReadRestrictionContent(+ Policy.BuiltInType policyType, PolicyContent content) {+ if (policyType == Policy.BuiltInType.ROW_FILTER && content instanceof RowFilterContent) {+ RestrictedRegoExpressionParserFacade.validateRowFilter(+ ((RowFilterContent) content).expression());+ } else if (policyType == Policy.BuiltInType.COLUMN_MASK+ && content instanceof ColumnMaskContent) {+ RestrictedRegoExpressionParserFacade.validateColumnMask(+ ((ColumnMaskContent) content).expression());+ }+ }}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/CanonicalExpression.java b/core/src/main/java/org/apache/gravitino/policy/rego/CanonicalExpression.javanew file mode 100644index 0000000000..4272b8081d--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/CanonicalExpression.java@@ -0,0 +1,49 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++/**+ * A node in an unresolved {@code restricted-rego-v1} expression tree.+ *+ * <p>The tree contains only the source constructs allowlisted by the read-restriction contract.+ * Column and context references remain symbolic until the effective-policy resolver binds them to a+ * table schema and request context.+ */+interface CanonicalExpression {++ /**+ * Validates this expression node and all of its children.+ *+ * @throws IllegalArgumentException if the expression is malformed or outside the allowlisted+ * source profile+ */+ void validate() throws IllegalArgumentException;++ /**+ * Returns the operation depth defined by {@code restricted-rego-v1}.+ *+ * <p>Value leaves such as a column, string, or number have depth 0. Atomic predicates such as a+ * comparison, Boolean literal, or group-membership check have depth 1. Negation and a logical+ * expression add one to their deepest operand. A consecutive n-ary logical chain counts as one+ * operation, so {@code true and false and true} has depth 2.+ *+ * @return expression operation depth+ */+ int depth();+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/Column.java b/core/src/main/java/org/apache/gravitino/policy/rego/Column.javanew file mode 100644index 0000000000..e173b00e02--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/Column.java@@ -0,0 +1,65 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import com.google.common.base.Preconditions;+import java.util.Objects;++/** A symbolic top-level column reference. */+final class Column implements CanonicalExpression {+ private final String name;++ Column(String name) {+ this.name = name;+ }++ String name() {+ return name;+ }++ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(name != null && !name.isEmpty(), "column name cannot be empty");+ ExpressionValidator.validateUnicodeScalars(name, "column name");+ }++ @Override+ public int depth() {+ return 0;+ }++ @Override+ public boolean equals(Object other) {+ if (!(other instanceof Column)) {+ return false;+ }+ Column that = (Column) other;+ return Objects.equals(name, that.name);+ }++ @Override+ public int hashCode() {+ return Objects.hash(name);+ }++ @Override+ public String toString() {+ return "Column{" + "name='" + name + '\'' + '}';+ }+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/Comparison.java b/core/src/main/java/org/apache/gravitino/policy/rego/Comparison.javanew file mode 100644index 0000000000..d8f32ae688--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/Comparison.java@@ -0,0 +1,119 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import com.google.common.base.Preconditions;+import java.util.Objects;++/** A binary comparison operation. */+final class Comparison implements CanonicalExpression {+ private final ComparisonOperator operator;+ private final CanonicalExpression left;+ private final CanonicalExpression right;++ Comparison(ComparisonOperator operator, CanonicalExpression left, CanonicalExpression right) {+ this.operator = operator;+ this.left = left;+ this.right = right;+ }++ ComparisonOperator operator() {+ return operator;+ }++ CanonicalExpression left() {+ return left;+ }++ CanonicalExpression right() {+ return right;+ }++ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(operator != null, "comparison operator cannot be null");+ Preconditions.checkArgument(+ left != null && right != null, "comparison operands cannot be null");+ left.validate();+ right.validate();+ try {+ ExpressionValidator.validateComparison(operator, left, right);+ } catch (IllegalArgumentException exception) {+ throw new IllegalArgumentException(+ String.format(+ "%s; operator '%s' with left=%s and right=%s",+ exception.getMessage(),+ operator.sourceToken(),+ operandKind(left),+ operandKind(right)),+ exception);+ }+ }++ private static String operandKind(CanonicalExpression expression) {+ if (expression instanceof Literal) {+ return "literal(" + ((Literal) expression).literalType() + ")";+ }+ if (expression instanceof LiteralArray) {+ return "literal-array(" + ((LiteralArray) expression).elementType() + ")";+ }+ if (expression instanceof Column) {+ return "column";+ }+ if (expression instanceof SessionUser) {+ return "session-user";+ }+ if (expression instanceof GroupMembership) {+ return "group-membership";+ }+ if (expression instanceof Not) {+ return "not";+ }+ if (expression instanceof LogicalExpression) {+ return "logical(" + ((LogicalExpression) expression).operator().sourceToken() + ")";+ }+ return expression.getClass().getSimpleName();+ }++ @Override+ public int depth() {+ return 1;+ }++ @Override+ public boolean equals(Object other) {+ if (!(other instanceof Comparison)) {+ return false;+ }+ Comparison that = (Comparison) other;+ return operator == that.operator+ && Objects.equals(left, that.left)+ && Objects.equals(right, that.right);+ }++ @Override+ public int hashCode() {+ return Objects.hash(operator, left, right);+ }++ @Override+ public String toString() {+ return "Comparison{" + "operator=" + operator + ", left=" + left + ", right=" + right + '}';+ }+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/ComparisonOperator.java b/core/src/main/java/org/apache/gravitino/policy/rego/ComparisonOperator.javanew file mode 100644index 0000000000..f5bceb7f69--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/ComparisonOperator.java@@ -0,0 +1,71 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import com.google.common.base.Preconditions;++/** Comparison operators supported by {@code restricted-rego-v1}. */+enum ComparisonOperator {+ /** Equality comparison. */+ EQ("=="),+ /** Inequality comparison. */+ NEQ("!="),+ /** Less-than comparison. */+ LT("<"),+ /** Less-than-or-equal comparison. */+ LTE("<="),+ /** Greater-than comparison. */+ GT(">"),+ /** Greater-than-or-equal comparison. */+ GTE(">="),+ /** Literal-array membership comparison. */+ IN("in");++ private final String sourceToken;++ ComparisonOperator(String sourceToken) {+ this.sourceToken = sourceToken;+ }++ static ComparisonOperator fromSourceToken(String token) {+ Preconditions.checkArgument(token != null && !token.isEmpty(), "operator cannot be empty");+ switch (token) {+ case "==":+ return EQ;+ case "!=":+ return NEQ;+ case "<":+ return LT;+ case "<=":+ return LTE;+ case ">":+ return GT;+ case ">=":+ return GTE;+ case "in":+ return IN;+ default:+ throw new IllegalArgumentException("Unsupported restricted-rego-v1 operator: " + token);+ }+ }++ String sourceToken() {+ return sourceToken;+ }+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/ExpressionValidator.java b/core/src/main/java/org/apache/gravitino/policy/rego/ExpressionValidator.javanew file mode 100644index 0000000000..9d5c8bb9f2--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/ExpressionValidator.java@@ -0,0 +1,146 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import com.google.common.base.Preconditions;++/** Semantic validation helpers for unresolved restricted Rego expressions. */+final class ExpressionValidator {+ private ExpressionValidator() {}++ static boolean isPredicate(CanonicalExpression expression) {+ if (expression instanceof Comparison+ || expression instanceof Not+ || expression instanceof LogicalExpression+ || expression instanceof GroupMembership) {+ return true;+ }+ return expression instanceof Literal+ && ((Literal) expression).literalType() == LiteralType.BOOLEAN;+ }++ static boolean isContextOnly(CanonicalExpression expression) {+ if (expression instanceof Column) {+ return false;+ }+ if (expression instanceof Comparison) {+ Comparison comparison = (Comparison) expression;+ return isContextOnly(comparison.left()) && isContextOnly(comparison.right());+ }+ if (expression instanceof Not) {+ return isContextOnly(((Not) expression).operand());+ }+ if (expression instanceof LogicalExpression) {+ for (CanonicalExpression child : ((LogicalExpression) expression).operands()) {+ if (!isContextOnly(child)) {+ return false;+ }+ }+ }+ return true;+ }++ static void validateComparison(+ ComparisonOperator operator, CanonicalExpression left, CanonicalExpression right) {+ if (operator == ComparisonOperator.IN) {+ Preconditions.checkArgument(+ right instanceof LiteralArray, "right operand of in must be a literal array");+ Preconditions.checkArgument(+ left instanceof Column || left instanceof SessionUser,+ "left operand of in must be col(...) or session_user()");+ if (left instanceof SessionUser) {+ LiteralArray array = (LiteralArray) right;+ Preconditions.checkArgument(+ array.elementType() == LiteralType.STRING,+ "session_user() can only be tested against a string array");+ }+ return;+ }++ Preconditions.checkArgument(+ !(left instanceof LiteralArray) && !(right instanceof LiteralArray),+ "%s does not support array operands",+ operator.sourceToken());++ boolean equality = operator == ComparisonOperator.EQ || operator == ComparisonOperator.NEQ;+ if (isColumnLiteralPair(left, right)) {+ Literal literal = left instanceof Literal ? (Literal) left : (Literal) right;+ Preconditions.checkArgument(+ literal.literalType() != LiteralType.NULL || equality, "null supports only == and !=");+ Preconditions.checkArgument(+ literal.literalType() != LiteralType.BOOLEAN || equality,+ "boolean literal supports only == and !=");+ return;+ }++ if (isColumnSessionUserPair(left, right)) {+ Preconditions.checkArgument(equality, "session_user() supports only == and !=");+ return;+ }++ if (isSessionUserStringPair(left, right)) {+ Preconditions.checkArgument(equality, "session_user() supports only == and !=");+ return;+ }++ throw new IllegalArgumentException(+ String.format("Unsupported operands for %s in restricted-rego-v1", operator.sourceToken()));+ }++ static void validateUnicodeScalars(String value, String description) {+ for (int index = 0; index < value.length(); index++) {+ char current = value.charAt(index);+ Preconditions.checkArgument(current != '\0', "%s cannot contain NUL", description);+ if (Character.isHighSurrogate(current)) {+ Preconditions.checkArgument(+ index + 1 < value.length() && Character.isLowSurrogate(value.charAt(index + 1)),+ "%s cannot contain an isolated surrogate",+ description);+ index++;+ } else {+ Preconditions.checkArgument(+ !Character.isLowSurrogate(current),+ "%s cannot contain an isolated surrogate",+ description);+ }+ }+ }++ private static boolean isColumnLiteralPair(CanonicalExpression left, CanonicalExpression right) {+ return (left instanceof Column && right instanceof Literal)+ || (right instanceof Column && left instanceof Literal);+ }++ private static boolean isColumnSessionUserPair(+ CanonicalExpression left, CanonicalExpression right) {+ return (left instanceof Column && right instanceof SessionUser)+ || (right instanceof Column && left instanceof SessionUser);+ }++ private static boolean isSessionUserStringPair(+ CanonicalExpression left, CanonicalExpression right) {+ if (left instanceof SessionUser && right instanceof Literal) {+ return ((Literal) right).literalType() == LiteralType.STRING;+ }+ if (right instanceof SessionUser && left instanceof Literal) {+ return ((Literal) left).literalType() == LiteralType.STRING;+ }+ return false;+ }+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/GroupMembership.java b/core/src/main/java/org/apache/gravitino/policy/rego/GroupMembership.javanew file mode 100644index 0000000000..cd3159f863--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/GroupMembership.java@@ -0,0 +1,65 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import com.google.common.base.Preconditions;+import java.util.Objects;++/** A request-context group-membership predicate. */+final class GroupMembership implements CanonicalExpression {+ private final String group;++ GroupMembership(String group) {+ this.group = group;+ }++ String group() {+ return group;+ }++ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(group != null && !group.isEmpty(), "group name cannot be empty");+ ExpressionValidator.validateUnicodeScalars(group, "group name");+ }++ @Override+ public int depth() {+ return 1;+ }++ @Override+ public boolean equals(Object other) {+ if (!(other instanceof GroupMembership)) {+ return false;+ }+ GroupMembership that = (GroupMembership) other;+ return Objects.equals(group, that.group);+ }++ @Override+ public int hashCode() {+ return Objects.hash(group);+ }++ @Override+ public String toString() {+ return "GroupMembership{" + "group='" + group + '\'' + '}';+ }+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/Literal.java b/core/src/main/java/org/apache/gravitino/policy/rego/Literal.javanew file mode 100644index 0000000000..166583b1af--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/Literal.java@@ -0,0 +1,120 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import com.google.common.base.Preconditions;+import java.math.BigDecimal;+import java.util.Objects;++/** A decoded source literal. */+final class Literal implements CanonicalExpression {+ private final LiteralType literalType;+ private final Object value;+ private final boolean negativeZero;++ Literal(LiteralType literalType, Object value) {+ this(literalType, value, false);+ }++ Literal(LiteralType literalType, Object value, boolean negativeZero) {+ this.literalType = literalType;+ this.value = value;+ this.negativeZero = negativeZero;+ }++ LiteralType literalType() {+ return literalType;+ }++ Object value() {+ return value;+ }++ boolean negativeZero() {+ return negativeZero;+ }++ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(literalType != null, "literalType cannot be null");+ switch (literalType) {+ case STRING:+ Preconditions.checkArgument(value instanceof String, "string literal must be a string");+ Preconditions.checkArgument(!negativeZero, "string literal cannot be negative zero");+ ExpressionValidator.validateUnicodeScalars((String) value, "string literal");+ break;+ case NUMBER:+ Preconditions.checkArgument(+ value instanceof BigDecimal, "number literal must be an exact decimal");+ Preconditions.checkArgument(+ !negativeZero || ((BigDecimal) value).signum() == 0,+ "negative-zero marker requires a zero value");+ break;+ case BOOLEAN:+ Preconditions.checkArgument(value instanceof Boolean, "boolean literal must be boolean");+ Preconditions.checkArgument(!negativeZero, "boolean literal cannot be negative zero");+ break;+ case NULL:+ Preconditions.checkArgument(value == null, "null literal cannot contain a value");+ Preconditions.checkArgument(!negativeZero, "null literal cannot be negative zero");+ break;+ default:+ throw new IllegalArgumentException("Unsupported literal type: " + literalType);+ }+ }++ @Override+ public int depth() {+ return literalType == LiteralType.BOOLEAN ? 1 : 0;+ }++ @Override+ public boolean equals(Object other) {+ if (!(other instanceof Literal)) {+ return false;+ }+ Literal that = (Literal) other;+ if (literalType != that.literalType || negativeZero != that.negativeZero) {+ return false;+ }+ if (literalType == LiteralType.NUMBER) {+ return ((BigDecimal) value).compareTo((BigDecimal) that.value) == 0;+ }+ return Objects.equals(value, that.value);+ }++ @Override+ public int hashCode() {+ Object normalizedValue =+ literalType == LiteralType.NUMBER ? ((BigDecimal) value).stripTrailingZeros() : value;+ return Objects.hash(literalType, normalizedValue, negativeZero);+ }++ @Override+ public String toString() {+ return "Literal{"+ + "literalType="+ + literalType+ + ", value="+ + value+ + ", negativeZero="+ + negativeZero+ + '}';+ }+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/LiteralArray.java b/core/src/main/java/org/apache/gravitino/policy/rego/LiteralArray.javanew file mode 100644index 0000000000..35f124e4bc--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/LiteralArray.java@@ -0,0 +1,83 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import com.google.common.base.Preconditions;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;+import java.util.Objects;++/** A non-empty homogeneous array of non-null source literals. */+final class LiteralArray implements CanonicalExpression {+ private final LiteralType elementType;+ private final List<Literal> values;++ LiteralArray(LiteralType elementType, List<Literal> values) {+ this.elementType = elementType;+ this.values = values == null ? null : Collections.unmodifiableList(new ArrayList<>(values));+ }++ LiteralType elementType() {+ return elementType;+ }++ List<Literal> values() {+ return values;+ }++ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(+ elementType != null && elementType != LiteralType.NULL,+ "array element type must be non-null");+ Preconditions.checkArgument(values != null && !values.isEmpty(), "array cannot be empty");+ for (Literal value : values) {+ Preconditions.checkArgument(value != null, "array cannot contain a null node");+ value.validate();+ Preconditions.checkArgument(+ value.literalType() == elementType,+ "array literals must have one homogeneous non-null type");+ }+ }++ @Override+ public int depth() {+ return 0;+ }++ @Override+ public boolean equals(Object other) {+ if (!(other instanceof LiteralArray)) {+ return false;+ }+ LiteralArray that = (LiteralArray) other;+ return elementType == that.elementType && Objects.equals(values, that.values);+ }++ @Override+ public int hashCode() {+ return Objects.hash(elementType, values);+ }++ @Override+ public String toString() {+ return "LiteralArray{" + "elementType=" + elementType + ", values=" + values + '}';+ }+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/LiteralType.java b/core/src/main/java/org/apache/gravitino/policy/rego/LiteralType.javanew file mode 100644index 0000000000..5c87ff64df--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/LiteralType.java@@ -0,0 +1,31 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++/** Source literal types supported by {@code restricted-rego-v1}. */+enum LiteralType {+ /** String literal. */+ STRING,+ /** Exact base-10 numeric literal. */+ NUMBER,+ /** Boolean literal. */+ BOOLEAN,+ /** Null literal. */+ NULL+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/LogicalExpression.java b/core/src/main/java/org/apache/gravitino/policy/rego/LogicalExpression.javanew file mode 100644index 0000000000..d24ef6dea8--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/LogicalExpression.java@@ -0,0 +1,112 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import com.google.common.base.Preconditions;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;+import java.util.Objects;++/** An n-ary Boolean conjunction or disjunction. */+final class LogicalExpression implements CanonicalExpression {+ private final LogicalOperator operator;+ private final List<CanonicalExpression> operands;++ LogicalExpression(LogicalOperator operator, List<CanonicalExpression> operands) {+ this.operator = operator;+ this.operands =+ operands == null ? null : Collections.unmodifiableList(new ArrayList<>(operands));+ }++ static CanonicalExpression of(LogicalOperator operator, List<CanonicalExpression> operands) {+ if (operands == null) {+ return new LogicalExpression(operator, null);+ }++ List<CanonicalExpression> flattened = new ArrayList<>();+ for (CanonicalExpression operand : operands) {+ if (operand instanceof LogicalExpression+ && ((LogicalExpression) operand).operator() == operator) {+ flattened.addAll(((LogicalExpression) operand).operands());+ } else {+ flattened.add(operand);+ }+ }+ return flattened.size() == 1 ? flattened.get(0) : new LogicalExpression(operator, flattened);+ }++ LogicalOperator operator() {+ return operator;+ }++ List<CanonicalExpression> operands() {+ return operands;+ }++ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(operator != null, "logical expression operator cannot be null");+ Preconditions.checkArgument(+ operands != null && operands.size() >= 2,+ "%s requires at least two operands",+ operator.sourceToken());+ for (CanonicalExpression child : operands) {+ Preconditions.checkArgument(+ child != null, "%s operand cannot be null", operator.sourceToken());+ child.validate();+ Preconditions.checkArgument(+ ExpressionValidator.isPredicate(child),+ "%s operands must be boolean predicates",+ operator.sourceToken());+ }+ }++ @Override+ public int depth() {+ int childDepth = 0;+ if (operands != null) {+ for (CanonicalExpression child : operands) {+ if (child != null) {+ childDepth = Math.max(childDepth, child.depth());+ }+ }+ }+ return 1 + childDepth;+ }++ @Override+ public boolean equals(Object other) {+ if (!(other instanceof LogicalExpression)) {+ return false;+ }+ LogicalExpression that = (LogicalExpression) other;+ return operator == that.operator && Objects.equals(operands, that.operands);+ }++ @Override+ public int hashCode() {+ return Objects.hash(operator, operands);+ }++ @Override+ public String toString() {+ return "LogicalExpression{" + "operator=" + operator + ", operands=" + operands + '}';+ }+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/LogicalOperator.java b/core/src/main/java/org/apache/gravitino/policy/rego/LogicalOperator.javanew file mode 100644index 0000000000..81523c851e--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/LogicalOperator.java@@ -0,0 +1,37 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++/** N-ary logical operators supported by {@code restricted-rego-v1}. */+enum LogicalOperator {+ /** Boolean conjunction. */+ AND("and"),+ /** Boolean disjunction. */+ OR("or");++ private final String sourceToken;++ LogicalOperator(String sourceToken) {+ this.sourceToken = sourceToken;+ }++ String sourceToken() {+ return sourceToken;+ }+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/Not.java b/core/src/main/java/org/apache/gravitino/policy/rego/Not.javanew file mode 100644index 0000000000..678f292471--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/Not.java@@ -0,0 +1,67 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import com.google.common.base.Preconditions;+import java.util.Objects;++/** A Boolean negation operation. */+final class Not implements CanonicalExpression {+ private final CanonicalExpression operand;++ Not(CanonicalExpression operand) {+ this.operand = operand;+ }++ static CanonicalExpression negate(CanonicalExpression operand) {+ return operand instanceof Not ? ((Not) operand).operand() : new Not(operand);+ }++ CanonicalExpression operand() {+ return operand;+ }++ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(operand != null, "not requires an operand");+ operand.validate();+ Preconditions.checkArgument(+ ExpressionValidator.isPredicate(operand), "not operand must be a boolean predicate");+ }++ @Override+ public int depth() {+ return 1 + (operand == null ? 0 : operand.depth());+ }++ @Override+ public boolean equals(Object other) {+ return other instanceof Not && Objects.equals(operand, ((Not) other).operand);+ }++ @Override+ public int hashCode() {+ return Objects.hash(operand);+ }++ @Override+ public String toString() {+ return "Not{" + "operand=" + operand + '}';+ }+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoExpressionParserFacade.java b/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoExpressionParserFacade.javanew file mode 100644index 0000000000..17da825077--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoExpressionParserFacade.java@@ -0,0 +1,105 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import com.google.common.base.Preconditions;+import java.nio.charset.StandardCharsets;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.policy.ReadRestrictionContent;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.ColumnMask;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.RowFilter;++/** Validates complete programs in the {@code restricted-rego-v1} source dialect. */+public final class RestrictedRegoExpressionParserFacade {++ private RestrictedRegoExpressionParserFacade() {}++ /**+ * Validates one complete {@code filter := ...} program.+ *+ * @param source row-filter program in {@code restricted-rego-v1}+ * @throws IllegalArgumentException if syntax or semantics are invalid or the rule head is not+ * {@code filter}+ */+ public static void validateRowFilter(String source) {+ parseRowFilter(source);+ }++ /**+ * Validates one complete {@code mask := action(...)} program.+ *+ * @param source column-mask program in {@code restricted-rego-v1}+ * @throws IllegalArgumentException if syntax or semantics are invalid or the rule head is not+ * {@code mask}+ */+ public static void validateColumnMask(String source) {+ parseColumnMask(source);+ }++ /**+ * Parses and validates one complete row-filter or column-mask program.+ *+ * @param source program in {@code restricted-rego-v1}+ * @return validated unresolved program+ * @throws IllegalArgumentException if syntax or semantics are invalid+ */+ static RestrictedRegoProgram parse(String source) {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(source), "restricted-rego-v1 program cannot be blank");+ Preconditions.checkArgument(+ source.getBytes(StandardCharsets.UTF_8).length+ <= ReadRestrictionContent.MAX_SOURCE_LENGTH_BYTES,+ "restricted-rego-v1 source must not exceed %s UTF-8 bytes",+ ReadRestrictionContent.MAX_SOURCE_LENGTH_BYTES);++ RestrictedRegoProgram program = new RestrictedRegoSourceParser(source).parseProgram();+ RestrictedRegoSourceValidator.validate(program);+ return program;+ }++ /**+ * Parses and validates one complete {@code filter := ...} program.+ *+ * @param source row-filter program in {@code restricted-rego-v1}+ * @return validated unresolved row-filter rule+ * @throws IllegalArgumentException if syntax or semantics are invalid or the rule head is not+ * {@code filter}+ */+ static RowFilter parseRowFilter(String source) {+ RestrictedRegoProgram program = parse(source);+ Preconditions.checkArgument(+ program instanceof RowFilter, "row-filter program must declare a filter rule");+ return (RowFilter) program;+ }++ /**+ * Parses and validates one complete {@code mask := action(...)} program.+ *+ * @param source column-mask program in {@code restricted-rego-v1}+ * @return validated unresolved column-mask rule+ * @throws IllegalArgumentException if syntax or semantics are invalid or the rule head is not+ * {@code mask}+ */+ static ColumnMask parseColumnMask(String source) {+ RestrictedRegoProgram program = parse(source);+ Preconditions.checkArgument(+ program instanceof ColumnMask, "column-mask program must declare a mask rule");+ return (ColumnMask) program;+ }+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoLexer.java b/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoLexer.javanew file mode 100644index 0000000000..c0918cf0d8--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoLexer.java@@ -0,0 +1,322 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++/** Converts {@code restricted-rego-v1} source text into tokens. */+final class RestrictedRegoLexer {+ private final String source;+ private int offset;+ private int line = 1;+ private int column = 1;++ RestrictedRegoLexer(String source) {+ this.source = source;+ }++ Token nextToken() {+ skipWhitespace();+ int tokenOffset = offset;+ int tokenLine = line;+ int tokenColumn = column;+ if (atEnd()) {+ return new Token(TokenType.EOF, "", tokenLine, tokenColumn);+ }++ char current = peek();+ if (current == '"') {+ scanString(tokenLine, tokenColumn);+ return token(TokenType.STRING, tokenOffset, tokenLine, tokenColumn);+ }+ if (isIdentifierStart(current)) {+ do {+ advance();+ } while (!atEnd() && isIdentifierPart(peek()));+ String text = source.substring(tokenOffset, offset);+ return new Token(keywordType(text, tokenLine, tokenColumn), text, tokenLine, tokenColumn);+ }+ if (isDigit(current) || (current == '-' && isDigit(peekNext()))) {+ scanNumber(tokenLine, tokenColumn);+ if (offset - tokenOffset > RestrictedRegoLimits.MAX_NUMERIC_LITERAL_BYTES) {+ throw lexicalError(+ tokenLine,+ tokenColumn,+ "numeric literal must not exceed "+ + RestrictedRegoLimits.MAX_NUMERIC_LITERAL_BYTES+ + " bytes");+ }+ if (!atEnd() && isIdentifierStart(peek())) {+ throw lexicalError(+ tokenLine, tokenColumn, "numeric literal must be separated from identifiers");+ }+ return token(TokenType.NUMBER, tokenOffset, tokenLine, tokenColumn);+ }++ advance();+ switch (current) {+ case ':':+ return symbol(TokenType.ASSIGN, '=', tokenOffset, tokenLine, tokenColumn);+ case '=':+ return symbol(TokenType.EQ, '=', tokenOffset, tokenLine, tokenColumn);+ case '!':+ return symbol(TokenType.NEQ, '=', tokenOffset, tokenLine, tokenColumn);+ case '<':+ return optionalEquals(TokenType.LT, TokenType.LTE, tokenOffset, tokenLine, tokenColumn);+ case '>':+ return optionalEquals(TokenType.GT, TokenType.GTE, tokenOffset, tokenLine, tokenColumn);+ case '(':+ return token(TokenType.LPAREN, tokenOffset, tokenLine, tokenColumn);+ case ')':+ return token(TokenType.RPAREN, tokenOffset, tokenLine, tokenColumn);+ case '[':+ return token(TokenType.LBRACKET, tokenOffset, tokenLine, tokenColumn);+ case ']':+ return token(TokenType.RBRACKET, tokenOffset, tokenLine, tokenColumn);+ case ',':+ return token(TokenType.COMMA, tokenOffset, tokenLine, tokenColumn);+ default:+ throw lexicalError(tokenLine, tokenColumn, "unsupported character " + current);+ }+ }++ private void scanString(int tokenLine, int tokenColumn) {+ advance();+ while (!atEnd()) {+ char current = advance();+ if (current == '"') {+ return;+ }+ if (current < 0x20) {+ throw lexicalError(tokenLine, tokenColumn, "unescaped control character in string");+ }+ if (current != '\\') {+ continue;+ }+ if (atEnd()) {+ break;+ }+ char escaped = advance();+ if (escaped == 'u') {+ for (int index = 0; index < 4; index++) {+ if (atEnd() || !isAsciiHexDigit(advance())) {+ throw lexicalError(tokenLine, tokenColumn, "invalid Unicode escape in string");+ }+ }+ } else if ("\"\\/bfnrt".indexOf(escaped) < 0) {+ throw lexicalError(tokenLine, tokenColumn, "unsupported string escape");+ }+ }+ throw lexicalError(tokenLine, tokenColumn, "unterminated string");+ }++ private void scanNumber(int tokenLine, int tokenColumn) {+ if (peek() == '-') {+ advance();+ }+ if (peek() == '0') {+ advance();+ if (!atEnd() && isDigit(peek())) {+ throw lexicalError(tokenLine, tokenColumn, "numeric literals cannot contain leading zeros");+ }+ } else {+ while (!atEnd() && isDigit(peek())) {+ advance();+ }+ }+ if (!atEnd() && peek() == '.' && isDigit(peekNext())) {+ advance();+ while (!atEnd() && isDigit(peek())) {+ advance();+ }+ }+ }++ private Token symbol(+ TokenType type, char second, int tokenOffset, int tokenLine, int tokenColumn) {+ if (atEnd() || peek() != second) {+ throw lexicalError(tokenLine, tokenColumn, "unsupported operator");+ }+ advance();+ return token(type, tokenOffset, tokenLine, tokenColumn);+ }++ private Token optionalEquals(+ TokenType single, TokenType withEquals, int tokenOffset, int tokenLine, int tokenColumn) {+ TokenType type = single;+ if (!atEnd() && peek() == '=') {+ advance();+ type = withEquals;+ }+ return token(type, tokenOffset, tokenLine, tokenColumn);+ }++ private Token token(TokenType type, int tokenOffset, int tokenLine, int tokenColumn) {+ return new Token(type, source.substring(tokenOffset, offset), tokenLine, tokenColumn);+ }++ private void skipWhitespace() {+ while (!atEnd()) {+ char current = peek();+ if (current != ' ' && current != '\t' && current != '\r' && current != '\n') {+ return;+ }+ advance();+ }+ }++ private char advance() {+ char current = source.charAt(offset++);+ if (current == '\n') {+ line++;+ column = 1;+ } else {+ column++;+ }+ return current;+ }++ private char peek() {+ return source.charAt(offset);+ }++ private char peekNext() {+ return offset + 1 < source.length() ? source.charAt(offset + 1) : '\0';+ }++ private boolean atEnd() {+ return offset >= source.length();+ }++ private static TokenType keywordType(String text, int line, int column) {+ switch (text) {+ case "filter":+ return TokenType.FILTER;+ case "mask":+ return TokenType.MASK;+ case "if":+ return TokenType.IF;+ case "else":+ return TokenType.ELSE;+ case "or":+ return TokenType.OR;+ case "and":+ return TokenType.AND;+ case "not":+ return TokenType.NOT;+ case "in":+ return TokenType.IN;+ case "col":+ return TokenType.COL;+ case "session_user":+ return TokenType.SESSION_USER;+ case "is_group_member":+ return TokenType.IS_GROUP_MEMBER;+ case "action":+ return TokenType.ACTION;+ case "true":+ return TokenType.TRUE;+ case "false":+ return TokenType.FALSE;+ case "null":+ return TokenType.NULL;+ default:+ throw lexicalError(line, column, "unsupported identifier " + text);+ }+ }++ private static boolean isIdentifierStart(char value) {+ return (value >= 'a' && value <= 'z') || (value >= 'A' && value <= 'Z') || value == '_';+ }++ private static boolean isIdentifierPart(char value) {+ return isIdentifierStart(value) || isDigit(value);+ }++ private static boolean isDigit(char value) {+ return value >= '0' && value <= '9';+ }++ static boolean isAsciiHexDigit(char value) {+ return (value >= '0' && value <= '9')+ || (value >= 'a' && value <= 'f')+ || (value >= 'A' && value <= 'F');+ }++ static int asciiHexValue(char value) {+ if (value >= '0' && value <= '9') {+ return value - '0';+ }+ if (value >= 'a' && value <= 'f') {+ return value - 'a' + 10;+ }+ return value - 'A' + 10;+ }++ private static IllegalArgumentException lexicalError(int line, int column, String message) {+ return new IllegalArgumentException(+ String.format(+ "Invalid restricted-rego-v1 program at line %s, column %s: %s", line, column, message));+ }++ enum TokenType {+ FILTER,+ MASK,+ IF,+ ELSE,+ OR,+ AND,+ NOT,+ IN,+ COL,+ SESSION_USER,+ IS_GROUP_MEMBER,+ ACTION,+ TRUE,+ FALSE,+ NULL,+ ASSIGN,+ EQ,+ NEQ,+ LTE,+ LT,+ GTE,+ GT,+ LPAREN,+ RPAREN,+ LBRACKET,+ RBRACKET,+ COMMA,+ NUMBER,+ STRING,+ EOF+ }++ static final class Token {+ final TokenType type;+ final String text;+ final int line;+ final int column;++ private Token(TokenType type, String text, int line, int column) {+ this.type = type;+ this.text = text;+ this.line = line;+ this.column = column;+ }+ }+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoLimits.java b/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoLimits.javanew file mode 100644index 0000000000..40d7726322--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoLimits.java@@ -0,0 +1,32 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++/** Resource limits for {@code restricted-rego-v1} source programs. */+final class RestrictedRegoLimits {+ static final int MAX_SOURCE_DEPTH = 8;+ static final int MAX_AST_NODES = 256;+ static final int MAX_STRING_BYTES = 4 * 1024;+ static final int MAX_ARRAY_ELEMENTS = 256;+ static final int MAX_TOTAL_ARRAY_ELEMENTS = 256;+ static final int MAX_NUMERIC_LITERAL_BYTES = 256;+ static final int MAX_PARENTHESIS_NESTING = 256;++ private RestrictedRegoLimits() {}+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoProgram.java b/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoProgram.javanew file mode 100644index 0000000000..046b654a70--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoProgram.java@@ -0,0 +1,410 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import com.google.common.base.Preconditions;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;+import java.util.Objects;++/** A parsed, unresolved program in the {@code restricted-rego-v1} source dialect. */+interface RestrictedRegoProgram {++ /**+ * Returns the rule type declared by this program.+ *+ * @return rule type+ */+ RuleType ruleType();++ /**+ * Validates the rule and every expression it contains.+ *+ * @throws IllegalArgumentException if the rule is malformed+ */+ void validate() throws IllegalArgumentException;++ /** Rule heads supported by {@code restricted-rego-v1}. */+ enum RuleType {+ /** A row-filter rule. */+ FILTER,+ /** A column-mask rule. */+ MASK+ }++ /** Logical column-mask actions supported by the first restricted profile. */+ enum MaskAction {+ /** Mask alphanumeric characters. */+ MASK_ALPHANUM("mask-alphanum"),+ /** Replace the value with the action's fixed value. */+ MASK_TO_FIXED_VALUE("mask-to-fixed-value"),+ /** Replace the value with null. */+ REPLACE_WITH_NULL("replace-with-null"),+ /** Preserve only the first four characters. */+ SHOW_FIRST_4("show-first-4"),+ /** Preserve only the last four characters. */+ SHOW_LAST_4("show-last-4"),+ /** Truncate a temporal value to its year. */+ TRUNCATE_TO_YEAR("truncate-to-year"),+ /** Truncate a temporal value to its month. */+ TRUNCATE_TO_MONTH("truncate-to-month"),+ /** Apply a global SHA-256 mask. */+ SHA_256_GLOBAL("sha-256-global"),+ /** Apply a query-local SHA-256 mask. */+ SHA_256_QUERY_LOCAL("sha-256-query-local");++ private final String value;++ MaskAction(String value) {+ this.value = value;+ }++ /**+ * Parses a mask-action value.+ *+ * @param value source action value+ * @return parsed action+ * @throws IllegalArgumentException if the action is not allowlisted+ */+ public static MaskAction fromValue(String value) {+ Preconditions.checkArgument(value != null && !value.isEmpty(), "mask action cannot be empty");+ for (MaskAction action : values()) {+ if (action.value.equals(value)) {+ return action;+ }+ }+ throw new IllegalArgumentException("Unsupported restricted-rego-v1 mask action: " + value);+ }++ /**+ * Returns the source action value.+ *+ * @return source action value+ */+ public String value() {+ return value;+ }+ }++ /** One guarded result in a conditional row-filter rule. */+ final class FilterBranch {+ private final CanonicalExpression result;+ private final CanonicalExpression condition;++ FilterBranch(CanonicalExpression result, CanonicalExpression condition) {+ this.result = result;+ this.condition = condition;+ }++ /**+ * Returns the Boolean result selected by this branch.+ *+ * @return unresolved Boolean result+ */+ public CanonicalExpression result() {+ return result;+ }++ /**+ * Returns this branch's Boolean condition.+ *+ * @return unresolved Boolean condition+ */+ public CanonicalExpression condition() {+ return condition;+ }++ /**+ * Validates the branch.+ *+ * @throws IllegalArgumentException if its result or condition is not Boolean+ */+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(result != null, "filter branch result cannot be null");+ Preconditions.checkArgument(condition != null, "filter branch condition cannot be null");+ result.validate();+ condition.validate();+ Preconditions.checkArgument(+ ExpressionValidator.isPredicate(result), "filter branch result must be Boolean");+ Preconditions.checkArgument(+ ExpressionValidator.isPredicate(condition), "filter branch condition must be Boolean");+ }++ @Override+ public boolean equals(Object other) {+ if (!(other instanceof FilterBranch)) {+ return false;+ }+ FilterBranch that = (FilterBranch) other;+ return Objects.equals(result, that.result) && Objects.equals(condition, that.condition);+ }++ @Override+ public int hashCode() {+ return Objects.hash(result, condition);+ }++ @Override+ public String toString() {+ return "FilterBranch{" + "result=" + result + ", condition=" + condition + '}';+ }+ }++ /** A complete {@code filter := ...} row-filter rule. */+ final class RowFilter implements RestrictedRegoProgram {+ private final List<FilterBranch> branches;+ private final CanonicalExpression fallback;++ RowFilter(List<FilterBranch> branches, CanonicalExpression fallback) {+ this.branches =+ branches == null ? null : Collections.unmodifiableList(new ArrayList<>(branches));+ this.fallback = fallback;+ }++ @Override+ public RuleType ruleType() {+ return RuleType.FILTER;+ }++ /**+ * Returns the guarded results in source order.+ *+ * @return immutable branches, or an empty list for an unconditional rule+ */+ public List<FilterBranch> branches() {+ return branches;+ }++ /**+ * Returns the unconditional result or final {@code else} result.+ *+ * @return unresolved Boolean fallback+ */+ public CanonicalExpression fallback() {+ return fallback;+ }++ /**+ * Returns whether this rule contains at least one conditional branch.+ *+ * @return {@code true} for a conditional rule+ */+ public boolean isConditional() {+ return branches != null && !branches.isEmpty();+ }++ /**+ * Lowers the ordered branches to one Boolean predicate with first-match semantics.+ *+ * <p>The returned predicate remains unresolved. Context and column binding can be applied to it+ * by a later resolver.+ *+ * @return lowered unresolved predicate+ */+ public CanonicalExpression lower() {+ validate();+ if (branches.isEmpty()) {+ return fallback;+ }++ CanonicalExpression lowered = fallback;+ for (int index = branches.size() - 1; index >= 0; index--) {+ FilterBranch branch = branches.get(index);+ CanonicalExpression selected =+ LogicalExpression.of(LogicalOperator.AND, List.of(branch.condition(), branch.result()));+ CanonicalExpression remaining =+ LogicalExpression.of(+ LogicalOperator.AND, List.of(Not.negate(branch.condition()), lowered));+ lowered = LogicalExpression.of(LogicalOperator.OR, List.of(selected, remaining));+ }+ lowered.validate();+ return lowered;+ }++ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(branches != null, "filter branches cannot be null");+ Preconditions.checkArgument(fallback != null, "filter fallback cannot be null");+ for (FilterBranch branch : branches) {+ Preconditions.checkArgument(branch != null, "filter branch cannot be null");+ branch.validate();+ }+ fallback.validate();+ Preconditions.checkArgument(+ ExpressionValidator.isPredicate(fallback), "filter fallback must be Boolean");+ }++ @Override+ public boolean equals(Object other) {+ if (!(other instanceof RowFilter)) {+ return false;+ }+ RowFilter that = (RowFilter) other;+ return Objects.equals(branches, that.branches) && Objects.equals(fallback, that.fallback);+ }++ @Override+ public int hashCode() {+ return Objects.hash(branches, fallback);+ }++ @Override+ public String toString() {+ return "RowFilter{" + "branches=" + branches + ", fallback=" + fallback + '}';+ }+ }++ /** One guarded action in a conditional column-mask rule. */+ final class MaskBranch {+ private final MaskAction action;+ private final CanonicalExpression condition;++ MaskBranch(MaskAction action, CanonicalExpression condition) {+ this.action = action;+ this.condition = condition;+ }++ /**+ * Returns the action selected by this branch.+ *+ * @return mask action+ */+ public MaskAction action() {+ return action;+ }++ /**+ * Returns this branch's context-only condition.+ *+ * @return unresolved Boolean condition+ */+ public CanonicalExpression condition() {+ return condition;+ }++ /**+ * Validates the branch.+ *+ * @throws IllegalArgumentException if the action or condition is invalid+ */+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(action != null, "mask branch action cannot be null");+ Preconditions.checkArgument(condition != null, "mask branch condition cannot be null");+ condition.validate();+ Preconditions.checkArgument(+ ExpressionValidator.isPredicate(condition), "mask branch condition must be Boolean");+ Preconditions.checkArgument(+ ExpressionValidator.isContextOnly(condition),+ "column-mask condition cannot contain col(...)");+ }++ @Override+ public boolean equals(Object other) {+ if (!(other instanceof MaskBranch)) {+ return false;+ }+ MaskBranch that = (MaskBranch) other;+ return action == that.action && Objects.equals(condition, that.condition);+ }++ @Override+ public int hashCode() {+ return Objects.hash(action, condition);+ }++ @Override+ public String toString() {+ return "MaskBranch{" + "action=" + action + ", condition=" + condition + '}';+ }+ }++ /** A complete {@code mask := action(...)} column-mask rule. */+ final class ColumnMask implements RestrictedRegoProgram {+ private final List<MaskBranch> branches;+ private final MaskAction fallback;++ ColumnMask(List<MaskBranch> branches, MaskAction fallback) {+ this.branches =+ branches == null ? null : Collections.unmodifiableList(new ArrayList<>(branches));+ this.fallback = fallback;+ }++ @Override+ public RuleType ruleType() {+ return RuleType.MASK;+ }++ /**+ * Returns the guarded actions in source order.+ *+ * @return immutable branches, or an empty list for an unconditional rule+ */+ public List<MaskBranch> branches() {+ return branches;+ }++ /**+ * Returns the unconditional action or final {@code else} action.+ *+ * @return fallback mask action+ */+ public MaskAction fallback() {+ return fallback;+ }++ /**+ * Returns whether this rule contains at least one conditional branch.+ *+ * @return {@code true} for a conditional rule+ */+ public boolean isConditional() {+ return branches != null && !branches.isEmpty();+ }++ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(branches != null, "mask branches cannot be null");+ Preconditions.checkArgument(fallback != null, "mask fallback cannot be null");+ for (MaskBranch branch : branches) {+ Preconditions.checkArgument(branch != null, "mask branch cannot be null");+ branch.validate();+ }+ }++ @Override+ public boolean equals(Object other) {+ if (!(other instanceof ColumnMask)) {+ return false;+ }+ ColumnMask that = (ColumnMask) other;+ return Objects.equals(branches, that.branches) && fallback == that.fallback;+ }++ @Override+ public int hashCode() {+ return Objects.hash(branches, fallback);+ }++ @Override+ public String toString() {+ return "ColumnMask{" + "branches=" + branches + ", fallback=" + fallback + '}';+ }+ }+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoSourceParser.java b/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoSourceParser.javanew file mode 100644index 0000000000..6fb02f4790--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoSourceParser.java@@ -0,0 +1,358 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import java.math.BigDecimal;+import java.nio.charset.StandardCharsets;+import java.util.ArrayList;+import java.util.List;+import org.apache.gravitino.policy.rego.RestrictedRegoLexer.Token;+import org.apache.gravitino.policy.rego.RestrictedRegoLexer.TokenType;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.ColumnMask;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.FilterBranch;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.MaskAction;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.MaskBranch;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.RowFilter;++/** Builds a {@code restricted-rego-v1} program from lexer tokens. */+final class RestrictedRegoSourceParser {+ private final RestrictedRegoLexer lexer;+ private Token current;+ private int parenthesisNesting;++ RestrictedRegoSourceParser(String source) {+ this.lexer = new RestrictedRegoLexer(source);+ this.current = lexer.nextToken();+ }++ RestrictedRegoProgram parseProgram() {+ RestrictedRegoProgram program;+ if (check(TokenType.FILTER)) {+ program = parseRowFilter();+ } else if (check(TokenType.MASK)) {+ program = parseColumnMask();+ } else {+ throw error("expected filter or mask rule");+ }+ expect(TokenType.EOF, "expected end of program");+ return program;+ }++ private RowFilter parseRowFilter() {+ expect(TokenType.FILTER, "expected filter");+ expect(TokenType.ASSIGN, "expected := after filter");+ CanonicalExpression result = parseExpression();+ if (!match(TokenType.IF)) {+ return new RowFilter(new ArrayList<>(), result);+ }++ List<FilterBranch> branches = new ArrayList<>();+ branches.add(new FilterBranch(result, parseExpression()));+ while (true) {+ expect(TokenType.ELSE, "expected final else branch");+ expect(TokenType.ASSIGN, "expected := after else");+ CanonicalExpression nextResult = parseExpression();+ if (!match(TokenType.IF)) {+ return new RowFilter(branches, nextResult);+ }+ branches.add(new FilterBranch(nextResult, parseExpression()));+ }+ }++ private ColumnMask parseColumnMask() {+ expect(TokenType.MASK, "expected mask");+ expect(TokenType.ASSIGN, "expected := after mask");+ MaskAction action = parseMaskAction();+ if (!match(TokenType.IF)) {+ return new ColumnMask(new ArrayList<>(), action);+ }++ List<MaskBranch> branches = new ArrayList<>();+ branches.add(new MaskBranch(action, parseExpression()));+ while (true) {+ expect(TokenType.ELSE, "expected final else branch");+ expect(TokenType.ASSIGN, "expected := after else");+ MaskAction nextAction = parseMaskAction();+ if (!match(TokenType.IF)) {+ return new ColumnMask(branches, nextAction);+ }+ branches.add(new MaskBranch(nextAction, parseExpression()));+ }+ }++ private MaskAction parseMaskAction() {+ expect(TokenType.ACTION, "expected action");+ expect(TokenType.LPAREN, "expected ( after action");+ Token actionToken = expect(TokenType.STRING, "expected mask action string");+ String action = decodeString(actionToken);+ expect(TokenType.RPAREN, "expected ) after mask action");+ try {+ return MaskAction.fromValue(action);+ } catch (IllegalArgumentException exception) {+ throw error(actionToken, exception.getMessage());+ }+ }++ private CanonicalExpression parseExpression() {+ return parseOrExpression();+ }++ private CanonicalExpression parseOrExpression() {+ List<CanonicalExpression> operands = new ArrayList<>();+ operands.add(parseAndExpression());+ while (match(TokenType.OR)) {+ operands.add(parseAndExpression());+ }+ return LogicalExpression.of(LogicalOperator.OR, operands);+ }++ private CanonicalExpression parseAndExpression() {+ List<CanonicalExpression> operands = new ArrayList<>();+ operands.add(parseNotExpression());+ while (match(TokenType.AND)) {+ operands.add(parseNotExpression());+ }+ return LogicalExpression.of(LogicalOperator.AND, operands);+ }++ private CanonicalExpression parseNotExpression() {+ int notCount = 0;+ while (match(TokenType.NOT)) {+ notCount++;+ if (notCount >= RestrictedRegoLimits.MAX_SOURCE_DEPTH) {+ throw error(+ "restricted-rego-v1 source depth must not exceed "+ + RestrictedRegoLimits.MAX_SOURCE_DEPTH);+ }+ }++ CanonicalExpression result = parseComparisonExpression();+ for (int index = 0; index < notCount; index++) {+ result = new Not(result);+ }+ return result;+ }++ private CanonicalExpression parseComparisonExpression() {+ CanonicalExpression left = parsePrimary();+ if (!isComparisonOperator(current.type)) {+ return left;+ }++ ComparisonOperator operator = ComparisonOperator.fromSourceToken(advance().text);+ CanonicalExpression right = parsePrimary();+ if (isComparisonOperator(current.type)) {+ throw error("chained comparisons are not supported");+ }+ return new Comparison(operator, left, right);+ }++ private CanonicalExpression parsePrimary() {+ if (match(TokenType.COL)) {+ expect(TokenType.LPAREN, "expected ( after col");+ String column = decodeString(expect(TokenType.STRING, "expected column name string"));+ expect(TokenType.RPAREN, "expected ) after column name");+ return new Column(column);+ }+ if (match(TokenType.SESSION_USER)) {+ expect(TokenType.LPAREN, "expected ( after session_user");+ expect(TokenType.RPAREN, "expected ) after session_user(");+ return new SessionUser();+ }+ if (match(TokenType.IS_GROUP_MEMBER)) {+ expect(TokenType.LPAREN, "expected ( after is_group_member");+ String group = decodeString(expect(TokenType.STRING, "expected group name string"));+ expect(TokenType.RPAREN, "expected ) after group name");+ return new GroupMembership(group);+ }+ if (isLiteral(current.type)) {+ return parseLiteral();+ }+ if (match(TokenType.LBRACKET)) {+ return parseLiteralArray();+ }+ if (match(TokenType.LPAREN)) {+ parenthesisNesting++;+ if (parenthesisNesting > RestrictedRegoLimits.MAX_PARENTHESIS_NESTING) {+ throw error(+ "parenthesis nesting must not exceed " + RestrictedRegoLimits.MAX_PARENTHESIS_NESTING);+ }+ CanonicalExpression expression = parseExpression();+ expect(TokenType.RPAREN, "expected ) after expression");+ parenthesisNesting--;+ return expression;+ }+ throw error("expected expression");+ }++ private Literal parseLiteral() {+ Token token = advance();+ switch (token.type) {+ case STRING:+ return new Literal(LiteralType.STRING, decodeString(token));+ case NUMBER:+ BigDecimal value = new BigDecimal(token.text);+ return new Literal(+ LiteralType.NUMBER, value, token.text.startsWith("-") && value.signum() == 0);+ case TRUE:+ return new Literal(LiteralType.BOOLEAN, true);+ case FALSE:+ return new Literal(LiteralType.BOOLEAN, false);+ case NULL:+ return new Literal(LiteralType.NULL, null);+ default:+ throw error(token, "expected literal");+ }+ }++ private LiteralArray parseLiteralArray() {+ List<Literal> values = new ArrayList<>();+ LiteralType elementType = null;+ do {+ if (values.size() >= RestrictedRegoLimits.MAX_ARRAY_ELEMENTS) {+ throw error(+ "array literal must not exceed "+ + RestrictedRegoLimits.MAX_ARRAY_ELEMENTS+ + " elements");+ }+ if (!isLiteral(current.type)) {+ throw error("expected a literal array element");+ }+ Literal literal = parseLiteral();+ if (elementType == null) {+ elementType = literal.literalType();+ }+ values.add(literal);+ } while (match(TokenType.COMMA));+ expect(TokenType.RBRACKET, "expected ] after array literal");+ return new LiteralArray(elementType, values);+ }++ private boolean match(TokenType type) {+ if (!check(type)) {+ return false;+ }+ advance();+ return true;+ }++ private boolean check(TokenType type) {+ return current.type == type;+ }++ private Token expect(TokenType type, String message) {+ if (!check(type)) {+ throw error(message);+ }+ return advance();+ }++ private Token advance() {+ Token previous = current;+ current = lexer.nextToken();+ return previous;+ }++ private IllegalArgumentException error(String message) {+ return error(current, message);+ }++ private static IllegalArgumentException error(Token token, String message) {+ return new IllegalArgumentException(+ String.format(+ "Invalid restricted-rego-v1 program at line %s, column %s: %s",+ token.line, token.column, message));+ }++ private static boolean isComparisonOperator(TokenType type) {+ return type == TokenType.EQ+ || type == TokenType.NEQ+ || type == TokenType.LT+ || type == TokenType.LTE+ || type == TokenType.GT+ || type == TokenType.GTE+ || type == TokenType.IN;+ }++ private static boolean isLiteral(TokenType type) {+ return type == TokenType.STRING+ || type == TokenType.NUMBER+ || type == TokenType.TRUE+ || type == TokenType.FALSE+ || type == TokenType.NULL;+ }++ private static String decodeString(Token token) {+ StringBuilder result = new StringBuilder();+ for (int index = 1; index < token.text.length() - 1; index++) {+ char current = token.text.charAt(index);+ if (current != '\\') {+ result.append(current);+ continue;+ }++ char escaped = token.text.charAt(++index);+ switch (escaped) {+ case '"':+ case '\\':+ case '/':+ result.append(escaped);+ break;+ case 'b':+ result.append('\b');+ break;+ case 'f':+ result.append('\f');+ break;+ case 'n':+ result.append('\n');+ break;+ case 'r':+ result.append('\r');+ break;+ case 't':+ result.append('\t');+ break;+ case 'u':+ int codeUnit = 0;+ for (int digitIndex = index + 1; digitIndex < index + 5; digitIndex++) {+ char digit = token.text.charAt(digitIndex);+ if (!RestrictedRegoLexer.isAsciiHexDigit(digit)) {+ throw error(token, "invalid Unicode escape in string");+ }+ codeUnit = codeUnit * 16 + RestrictedRegoLexer.asciiHexValue(digit);+ }+ result.append((char) codeUnit);+ index += 4;+ break;+ default:+ throw error(token, "unsupported string escape: \\" + escaped);+ }+ }+ String decoded = result.toString();+ if (decoded.getBytes(StandardCharsets.UTF_8).length > RestrictedRegoLimits.MAX_STRING_BYTES) {+ throw error(+ token,+ "decoded string literal must not exceed "+ + RestrictedRegoLimits.MAX_STRING_BYTES+ + " UTF-8 bytes");+ }+ return decoded;+ }+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoSourceValidator.java b/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoSourceValidator.javanew file mode 100644index 0000000000..2714b5a8ee--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoSourceValidator.java@@ -0,0 +1,113 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import com.google.common.base.Preconditions;+import java.util.ArrayList;+import java.util.List;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.ColumnMask;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.FilterBranch;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.MaskBranch;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.RowFilter;++/** Applies resource limits to a parsed {@code restricted-rego-v1} source program. */+final class RestrictedRegoSourceValidator {++ private RestrictedRegoSourceValidator() {}++ static void validate(RestrictedRegoProgram program) {+ program.validate();+ List<CanonicalExpression> expressions = expressions(program);+ int nodeCount = 0;+ int arrayElementCount = 0;+ for (CanonicalExpression expression : expressions) {+ Preconditions.checkArgument(+ expression.depth() <= RestrictedRegoLimits.MAX_SOURCE_DEPTH,+ "restricted-rego-v1 source depth must not exceed %s",+ RestrictedRegoLimits.MAX_SOURCE_DEPTH);+ nodeCount += countNodes(expression);+ arrayElementCount += countArrayElements(expression);+ }+ Preconditions.checkArgument(+ nodeCount <= RestrictedRegoLimits.MAX_AST_NODES,+ "restricted-rego-v1 AST must not exceed %s nodes",+ RestrictedRegoLimits.MAX_AST_NODES);+ Preconditions.checkArgument(+ arrayElementCount <= RestrictedRegoLimits.MAX_TOTAL_ARRAY_ELEMENTS,+ "restricted-rego-v1 literal arrays must not contain more than %s total elements",+ RestrictedRegoLimits.MAX_TOTAL_ARRAY_ELEMENTS);+ }++ private static List<CanonicalExpression> expressions(RestrictedRegoProgram program) {+ List<CanonicalExpression> expressions = new ArrayList<>();+ if (program instanceof RowFilter) {+ RowFilter filter = (RowFilter) program;+ for (FilterBranch branch : filter.branches()) {+ expressions.add(branch.result());+ expressions.add(branch.condition());+ }+ expressions.add(filter.fallback());+ } else {+ ColumnMask mask = (ColumnMask) program;+ for (MaskBranch branch : mask.branches()) {+ expressions.add(branch.condition());+ }+ }+ return expressions;+ }++ private static int countNodes(CanonicalExpression expression) {+ if (expression instanceof Comparison) {+ Comparison comparison = (Comparison) expression;+ return 1 + countNodes(comparison.left()) + countNodes(comparison.right());+ }+ if (expression instanceof Not) {+ return 1 + countNodes(((Not) expression).operand());+ }+ if (expression instanceof LogicalExpression) {+ int count = 1;+ for (CanonicalExpression child : ((LogicalExpression) expression).operands()) {+ count += countNodes(child);+ }+ return count;+ }+ return 1;+ }++ private static int countArrayElements(CanonicalExpression expression) {+ if (expression instanceof Comparison) {+ Comparison comparison = (Comparison) expression;+ return countArrayElements(comparison.left()) + countArrayElements(comparison.right());+ }+ if (expression instanceof Not) {+ return countArrayElements(((Not) expression).operand());+ }+ if (expression instanceof LogicalExpression) {+ int count = 0;+ for (CanonicalExpression child : ((LogicalExpression) expression).operands()) {+ count += countArrayElements(child);+ }+ return count;+ }+ if (expression instanceof LiteralArray) {+ return ((LiteralArray) expression).values().size();+ }+ return 0;+ }+}diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/SessionUser.java b/core/src/main/java/org/apache/gravitino/policy/rego/SessionUser.javanew file mode 100644index 0000000000..73ad898d1a--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/policy/rego/SessionUser.java@@ -0,0 +1,47 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++/** A symbolic reference to the trusted effective session user. */+final class SessionUser implements CanonicalExpression {+ SessionUser() {}++ @Override+ public void validate() throws IllegalArgumentException {}++ @Override+ public int depth() {+ return 0;+ }++ @Override+ public boolean equals(Object other) {+ return other instanceof SessionUser;+ }++ @Override+ public int hashCode() {+ return SessionUser.class.hashCode();+ }++ @Override+ public String toString() {+ return "SessionUser{}";+ }+}diff --git a/core/src/test/java/org/apache/gravitino/meta/TestPolicyEntity.java b/core/src/test/java/org/apache/gravitino/meta/TestPolicyEntity.javaindex 3ee2fa2ed2..2be5f4517b 100644--- a/core/src/test/java/org/apache/gravitino/meta/TestPolicyEntity.java+++ b/core/src/test/java/org/apache/gravitino/meta/TestPolicyEntity.java@@ -171,6 +171,12 @@ public class TestPolicyEntity {Assertions.assertThrows(IllegalArgumentException.class,() -> readRestrictionPolicy(Policy.BuiltInType.COLUMN_MASK, rowFilter));++ Assertions.assertDoesNotThrow(+ () ->+ readRestrictionPolicy(+ Policy.BuiltInType.ROW_FILTER,+ PolicyContents.rowFilter("previously-stored-expression")));}private static PolicyEntity readRestrictionPolicy(diff --git a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.javaindex e7933b9fa2..5b2f956a6c 100644--- a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java+++ b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java@@ -101,6 +101,7 @@ import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.tag.TagManager;import org.apache.gravitino.tag.TagValue;import org.apache.gravitino.utils.NameIdentifierUtil;+import org.apache.gravitino.utils.NamespaceUtil;import org.apache.gravitino.utils.RaceTestUtils;import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.AfterEach;@@ -495,6 +496,106 @@ public class TestPolicyManager {Assertions.assertEquals(updatedContent, updated.content());Assertions.assertEquals(updatedContent, policyManager.getPolicy(METALAKE, policyName).content());++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ policyManager.createPolicy(+ METALAKE,+ "invalid_" + policyName,+ Policy.BuiltInType.ROW_FILTER,+ null,+ true,+ PolicyContents.rowFilter("filter := col(\"region\")")));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ policyManager.alterPolicy(+ METALAKE,+ policyName,+ PolicyChange.updateContent(+ "system_row_filter",+ PolicyContents.rowFilter("mask := action(\"replace-with-null\")"))));+ Assertions.assertEquals(+ updatedContent, policyManager.getPolicy(METALAKE, policyName).content());+ }++ @Test+ public void testRenameAndCommentUpdateDoNotRevalidateStoredRowFilter() throws IOException {+ String policyName = "legacy_row_filter_" + UUID.randomUUID().toString().replace("-", "");+ PolicyContent legacyContent = PolicyContents.rowFilter("filter := col(\"region\")");+ PolicyEntity legacyPolicy =+ PolicyEntity.builder()+ .withId(new RandomIdGenerator().nextId())+ .withName(policyName)+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE))+ .withPolicyType(Policy.BuiltInType.ROW_FILTER)+ .withEnabled(true)+ .withContent(legacyContent)+ .withAuditInfo(+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .build();+ entityStore.put(legacyPolicy, false /* overwritten */);++ String newName = "renamed_" + policyName;+ PolicyEntity renamed =+ Assertions.assertDoesNotThrow(+ () -> policyManager.alterPolicy(METALAKE, policyName, PolicyChange.rename(newName)));+ PolicyEntity commented =+ Assertions.assertDoesNotThrow(+ () ->+ policyManager.alterPolicy(+ METALAKE, newName, PolicyChange.updateComment("legacy policy")));++ Assertions.assertEquals(newName, commented.name());+ Assertions.assertEquals("legacy policy", commented.comment());+ Assertions.assertEquals(legacyContent, renamed.content());+ Assertions.assertEquals(legacyContent, commented.content());+ }++ @Test+ public void testCreateUpdateAndGetColumnMaskPolicy() {+ String policyName = "column_mask_" + UUID.randomUUID().toString().replace("-", "");+ PolicyContent originalContent = PolicyContents.columnMask("mask := action(\"show-last-4\")");++ PolicyEntity created =+ policyManager.createPolicy(+ METALAKE, policyName, Policy.BuiltInType.COLUMN_MASK, null, true, originalContent);++ Assertions.assertEquals(originalContent, created.content());+ Assertions.assertEquals(+ originalContent, policyManager.getPolicy(METALAKE, policyName).content());++ PolicyContent updatedContent =+ PolicyContents.columnMask("mask := action(\"replace-with-null\")");+ PolicyEntity updated =+ policyManager.alterPolicy(+ METALAKE, policyName, PolicyChange.updateContent("system_column_mask", updatedContent));++ Assertions.assertEquals(updatedContent, updated.content());+ Assertions.assertEquals(+ updatedContent, policyManager.getPolicy(METALAKE, policyName).content());++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ policyManager.createPolicy(+ METALAKE,+ "invalid_" + policyName,+ Policy.BuiltInType.COLUMN_MASK,+ null,+ true,+ PolicyContents.columnMask("mask := action(\"unknown\")")));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ policyManager.alterPolicy(+ METALAKE,+ policyName,+ PolicyChange.updateContent(+ "system_column_mask", PolicyContents.columnMask("filter := true"))));+ Assertions.assertEquals(+ updatedContent, policyManager.getPolicy(METALAKE, policyName).content());}@Testdiff --git a/core/src/test/java/org/apache/gravitino/policy/rego/RestrictedRegoTestUtils.java b/core/src/test/java/org/apache/gravitino/policy/rego/RestrictedRegoTestUtils.javanew file mode 100644index 0000000000..a9caa483b5--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/RestrictedRegoTestUtils.java@@ -0,0 +1,117 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import java.util.List;++/** Shared builders and counters for restricted Rego tests. */+final class RestrictedRegoTestUtils {++ private RestrictedRegoTestUtils() {}++ static CanonicalExpression parseFilterExpression(String expression) {+ return RestrictedRegoExpressionParserFacade.parseRowFilter("filter := " + expression)+ .fallback();+ }++ static String literalArray(int elementCount) {+ StringBuilder result = new StringBuilder("[");+ for (int index = 0; index < elementCount; index++) {+ if (index > 0) {+ result.append(',');+ }+ result.append(index);+ }+ return result.append(']').toString();+ }++ static String balancedAndExpression(int start, int end) {+ if (end - start == 1) {+ return "col(\"column_" + start + "\") == " + start;+ }++ int middle = start + (end - start) / 2;+ return "("+ + balancedAndExpression(start, middle)+ + " and "+ + balancedAndExpression(middle, end)+ + ")";+ }++ static String conditionalFilterWithBranches(int branchCount) {+ StringBuilder source = new StringBuilder();+ for (int index = 0; index < branchCount; index++) {+ source+ .append(index == 0 ? "filter := " : " else := ")+ .append("true if col(\"c")+ .append(index)+ .append("\") == 1");+ }+ return source.append(" else := false").toString();+ }++ static String unicodeEscape(int first, int second, int third, int fourth) {+ return "\\u"+ + new String(new char[] {(char) first, (char) second, (char) third, (char) fourth});+ }++ static List<String> invalidUnicodeEscapes() {+ return List.of(+ unicodeEscape(0x0660, 0x0660, 0x0664, 0x0661),+ unicodeEscape(0xFF10, 0xFF10, 0xFF14, 0xFF11),+ unicodeEscape(0x0966, 0x0966, 0x096A, 0x0967),+ unicodeEscape('0', '0', 0x0664, 0x0661));+ }++ static int countExpressionNodes(CanonicalExpression expression) {+ if (expression instanceof Comparison) {+ Comparison comparison = (Comparison) expression;+ return 1 + countExpressionNodes(comparison.left()) + countExpressionNodes(comparison.right());+ }+ if (expression instanceof Not) {+ return 1 + countExpressionNodes(((Not) expression).operand());+ }+ if (expression instanceof LogicalExpression) {+ int count = 1;+ for (CanonicalExpression operand : ((LogicalExpression) expression).operands()) {+ count += countExpressionNodes(operand);+ }+ return count;+ }+ return 1;+ }++ static int countArrayElements(CanonicalExpression expression) {+ if (expression instanceof Comparison) {+ Comparison comparison = (Comparison) expression;+ return countArrayElements(comparison.left()) + countArrayElements(comparison.right());+ }+ if (expression instanceof Not) {+ return countArrayElements(((Not) expression).operand());+ }+ if (expression instanceof LogicalExpression) {+ int count = 0;+ for (CanonicalExpression operand : ((LogicalExpression) expression).operands()) {+ count += countArrayElements(operand);+ }+ return count;+ }+ return expression instanceof LiteralArray ? ((LiteralArray) expression).values().size() : 0;+ }+}diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestColumn.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestColumn.javanew file mode 100644index 0000000000..5fccffff92--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/TestColumn.java@@ -0,0 +1,36 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Tests for {@link Column}. */+public class TestColumn {++ @Test+ void testValidationAndValueSemantics() {+ Column column = new Column("owner");+ Assertions.assertDoesNotThrow(column::validate);+ Assertions.assertEquals("owner", column.name());+ Assertions.assertEquals(0, column.depth());+ Assertions.assertEquals(column, new Column("owner"));+ Assertions.assertThrows(IllegalArgumentException.class, () -> new Column("").validate());+ }+}diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestComparison.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestComparison.javanew file mode 100644index 0000000000..775bf647a3--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/TestComparison.java@@ -0,0 +1,54 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Tests for {@link Comparison}. */+public class TestComparison {++ @Test+ void testValidationAndStructuralEquality() {+ Comparison comparison =+ new Comparison(+ ComparisonOperator.EQ, new Column("owner"), new Literal(LiteralType.STRING, "alice"));+ Comparison equal =+ new Comparison(+ ComparisonOperator.EQ, new Column("owner"), new Literal(LiteralType.STRING, "alice"));++ Assertions.assertDoesNotThrow(comparison::validate);+ Assertions.assertEquals(1, comparison.depth());+ Assertions.assertEquals(comparison, equal);+ Assertions.assertEquals(comparison.hashCode(), equal.hashCode());+ }++ @Test+ void testCompactSemanticError() {+ Comparison invalid =+ new Comparison(+ ComparisonOperator.LT, new Column("active"), new Literal(LiteralType.BOOLEAN, true));++ IllegalArgumentException error =+ Assertions.assertThrows(IllegalArgumentException.class, invalid::validate);+ Assertions.assertTrue(error.getMessage().contains("left=column"));+ Assertions.assertTrue(error.getMessage().contains("right=literal(BOOLEAN)"));+ Assertions.assertFalse(error.getMessage().contains("value=true"));+ }+}diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestComparisonOperator.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestComparisonOperator.javanew file mode 100644index 0000000000..d8c263b7f1--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/TestComparisonOperator.java@@ -0,0 +1,35 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Tests for {@link ComparisonOperator}. */+public class TestComparisonOperator {++ @Test+ void testParsesEverySourceToken() {+ for (ComparisonOperator operator : ComparisonOperator.values()) {+ Assertions.assertEquals(operator, ComparisonOperator.fromSourceToken(operator.sourceToken()));+ }+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> ComparisonOperator.fromSourceToken("eq"));+ }+}diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestGroupMembership.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestGroupMembership.javanew file mode 100644index 0000000000..76751be333--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/TestGroupMembership.java@@ -0,0 +1,37 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Tests for {@link GroupMembership}. */+public class TestGroupMembership {++ @Test+ void testValidationAndValueSemantics() {+ GroupMembership membership = new GroupMembership("auditors");+ Assertions.assertDoesNotThrow(membership::validate);+ Assertions.assertEquals("auditors", membership.group());+ Assertions.assertEquals(1, membership.depth());+ Assertions.assertEquals(membership, new GroupMembership("auditors"));+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> new GroupMembership("").validate());+ }+}diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestLiteral.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestLiteral.javanew file mode 100644index 0000000000..de4f4a81e8--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/TestLiteral.java@@ -0,0 +1,48 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import java.math.BigDecimal;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Tests for {@link Literal}. */+public class TestLiteral {++ @Test+ void testValidatesSupportedLiteralTypes() {+ Assertions.assertDoesNotThrow(() -> new Literal(LiteralType.STRING, "value").validate());+ Assertions.assertDoesNotThrow(+ () -> new Literal(LiteralType.NUMBER, new BigDecimal("1.0")).validate());+ Assertions.assertDoesNotThrow(() -> new Literal(LiteralType.BOOLEAN, true).validate());+ Assertions.assertDoesNotThrow(() -> new Literal(LiteralType.NULL, null).validate());+ }++ @Test+ void testExactNumberValueSemantics() {+ Literal one = new Literal(LiteralType.NUMBER, new BigDecimal("1"));+ Literal onePointZero = new Literal(LiteralType.NUMBER, new BigDecimal("1.00"));+ Literal negativeZero = new Literal(LiteralType.NUMBER, new BigDecimal("0.00"), true);++ Assertions.assertEquals(one, onePointZero);+ Assertions.assertEquals(one.hashCode(), onePointZero.hashCode());+ Assertions.assertTrue(negativeZero.negativeZero());+ Assertions.assertNotEquals(negativeZero, new Literal(LiteralType.NUMBER, BigDecimal.ZERO));+ }+}diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestLiteralArray.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestLiteralArray.javanew file mode 100644index 0000000000..f0d831b786--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/TestLiteralArray.java@@ -0,0 +1,55 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import java.math.BigDecimal;+import java.util.List;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Tests for {@link LiteralArray}. */+public class TestLiteralArray {++ @Test+ void testValidationAndImmutableValues() {+ Literal value = new Literal(LiteralType.STRING, "US");+ LiteralArray array = new LiteralArray(LiteralType.STRING, List.of(value));++ Assertions.assertDoesNotThrow(array::validate);+ Assertions.assertEquals(LiteralType.STRING, array.elementType());+ Assertions.assertEquals(List.of(value), array.values());+ Assertions.assertThrows(UnsupportedOperationException.class, () -> array.values().add(value));+ }++ @Test+ void testRejectsEmptyAndHeterogeneousArrays() {+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> new LiteralArray(LiteralType.STRING, List.of()).validate());+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ new LiteralArray(+ LiteralType.STRING,+ List.of(+ new Literal(LiteralType.STRING, "US"),+ new Literal(LiteralType.NUMBER, BigDecimal.ONE)))+ .validate());+ }+}diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestLogicalExpression.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestLogicalExpression.javanew file mode 100644index 0000000000..76fc9523d1--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/TestLogicalExpression.java@@ -0,0 +1,65 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import java.util.List;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Tests for {@link LogicalExpression}. */+public class TestLogicalExpression {++ @Test+ void testFlattensAssociativeBooleanChains() {+ Literal value = new Literal(LiteralType.BOOLEAN, true);+ CanonicalExpression nested = LogicalExpression.of(LogicalOperator.AND, List.of(value, value));+ LogicalExpression flattened =+ (LogicalExpression) LogicalExpression.of(LogicalOperator.AND, List.of(value, nested));++ Assertions.assertEquals(3, flattened.operands().size());+ Assertions.assertEquals(2, flattened.depth());+ Assertions.assertDoesNotThrow(flattened::validate);+ Assertions.assertEquals("and", flattened.operator().sourceToken());+ }++ @Test+ void testReturnsSingleOperandWithoutWrapper() {+ Literal value = new Literal(LiteralType.BOOLEAN, true);+ Assertions.assertSame(value, LogicalExpression.of(LogicalOperator.OR, List.of(value)));+ }++ @Test+ void testRejectsInvalidOperands() {+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ new LogicalExpression(+ LogicalOperator.OR, List.of(new Literal(LiteralType.BOOLEAN, true)))+ .validate());+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ new LogicalExpression(+ LogicalOperator.OR,+ List.of(+ new Literal(LiteralType.BOOLEAN, true),+ new Literal(LiteralType.STRING, "not a predicate")))+ .validate());+ }+}diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestNot.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestNot.javanew file mode 100644index 0000000000..839e9e8412--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/TestNot.java@@ -0,0 +1,44 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Tests for {@link Not}. */+public class TestNot {++ @Test+ void testValidationDepthAndDoubleNegation() {+ GroupMembership membership = new GroupMembership("auditors");+ Not not = new Not(membership);++ Assertions.assertDoesNotThrow(not::validate);+ Assertions.assertEquals(2, not.depth());+ Assertions.assertEquals(membership, Not.negate(not));+ Assertions.assertEquals(not, Not.negate(membership));+ }++ @Test+ void testRejectsNonPredicateOperand() {+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> new Not(new Literal(LiteralType.STRING, "not a predicate")).validate());+ }+}diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoExpressionParserFacade.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoExpressionParserFacade.javanew file mode 100644index 0000000000..4e81d84177--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoExpressionParserFacade.java@@ -0,0 +1,126 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import java.nio.charset.StandardCharsets;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.ColumnMask;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.MaskAction;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.RowFilter;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.RuleType;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++/** Tests for {@link RestrictedRegoExpressionParserFacade}. */+public class TestRestrictedRegoExpressionParserFacade {++ @Test+ void testParsesTypedRules() {+ Assertions.assertDoesNotThrow(+ () ->+ RestrictedRegoExpressionParserFacade.validateRowFilter(+ "filter := col(\"owner\") == session_user()"));+ Assertions.assertDoesNotThrow(+ () ->+ RestrictedRegoExpressionParserFacade.validateColumnMask(+ "mask := action(\"show-last-4\")"));++ RowFilter filter =+ RestrictedRegoExpressionParserFacade.parseRowFilter(+ "filter := col(\"owner\") == session_user()");+ Assertions.assertEquals(RuleType.FILTER, filter.ruleType());+ Assertions.assertFalse(filter.isConditional());+ Assertions.assertInstanceOf(Comparison.class, filter.fallback());++ ColumnMask mask =+ RestrictedRegoExpressionParserFacade.parseColumnMask("mask := action(\"show-last-4\")");+ Assertions.assertEquals(RuleType.MASK, mask.ruleType());+ Assertions.assertFalse(mask.isConditional());+ Assertions.assertEquals(MaskAction.SHOW_LAST_4, mask.fallback());++ Assertions.assertInstanceOf(+ RowFilter.class, RestrictedRegoExpressionParserFacade.parse("filter := true"));+ Assertions.assertInstanceOf(+ ColumnMask.class,+ RestrictedRegoExpressionParserFacade.parse("mask := action(\"mask-alphanum\")"));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ RestrictedRegoExpressionParserFacade.parseRowFilter("mask := action(\"show-last-4\")"));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> RestrictedRegoExpressionParserFacade.parseColumnMask("filter := true"));+ }++ @Test+ void testEnforcesSourceLength() {+ String sourcePrefix = "filter := true";+ String maximumSource =+ sourcePrefix + " ".repeat(16 * 1024 - sourcePrefix.getBytes(StandardCharsets.UTF_8).length);++ Assertions.assertDoesNotThrow(+ () -> RestrictedRegoExpressionParserFacade.parseRowFilter(maximumSource));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> RestrictedRegoExpressionParserFacade.parseRowFilter(maximumSource + " "));+ }++ @Test+ void testRejectsInvalidUnicodeEscapeDigitsThroughFacade() {+ for (String invalidEscape : RestrictedRegoTestUtils.invalidUnicodeEscapes()) {+ IllegalArgumentException error =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ RestrictedRegoExpressionParserFacade.validateRowFilter(+ "filter := col(\"" + invalidEscape + "\") == \"x\""));+ Assertions.assertTrue(error.getMessage().contains("invalid Unicode escape"));+ }+ }++ @ParameterizedTest+ @ValueSource(+ strings = {+ "",+ " ",+ "true",+ "result := true",+ "package restrictions",+ "import data.rules",+ "filter := true filter := false",+ "filter := true { true }",+ "filter := true # comment",+ "filter := true if is_group_member(\"a\")",+ "filter := true if true else := false if false",+ "filter := true then false else := false",+ "filter := \"not-boolean\"",+ "mask := \"show-last-4\"",+ "mask := action(\"unknown\")",+ "mask := action(\"show-last-4\") if true",+ "mask := action(\"show-last-4\") if col(\"region\") == \"US\" else := action(\"mask-alphanum\")",+ "mask := action(\"show-last-4\") if true else := action(\"mask-alphanum\") if col(\"x\") == 1 else := action(\"replace-with-null\")",+ "mask := true",+ "filter := action(\"show-last-4\")"+ })+ void testRejectsUnsupportedOrMalformedPrograms(String source) {+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> RestrictedRegoExpressionParserFacade.parse(source));+ }+}diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoGoldenFile.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoGoldenFile.javanew file mode 100644index 0000000000..1cec255da9--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoGoldenFile.java@@ -0,0 +1,176 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import java.io.IOException;+import java.io.InputStream;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.ArrayList;+import java.util.List;+import java.util.Optional;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.RowFilter;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Golden-file and documentation-drift tests for {@code restricted-rego-v1}. */+public class TestRestrictedRegoGoldenFile {+ private static final String GOLDEN_CASES_RESOURCE = "/restricted-rego-v1-cases.txt";+ private static final String GOLDEN_FILE =+ "core/src/test/resources/restricted-rego-v1-cases.golden";+ private static final String UPDATE_GOLDEN_ENV = "GRAVITINO_UPDATE_RESTRICTED_REGO_GOLDEN";+ private static final String REPOSITORY_ROOT_PROPERTY = "gravitino.repositoryRoot";+ private static final String GOLDEN_LICENSE_HEADER =+ "# Licensed to the Apache Software Foundation (ASF) under one or more\n"+ + "# contributor license agreements. See the NOTICE file distributed with\n"+ + "# this work for additional information regarding copyright ownership.\n"+ + "# The ASF licenses this file to You under the Apache License, Version 2.0\n"+ + "# (the \"License\"); you may not use this file except in compliance with\n"+ + "# the License. You may obtain a copy of the License at\n"+ + "#\n"+ + "# http://www.apache.org/licenses/LICENSE-2.0\n"+ + "#\n"+ + "# Unless required by applicable law or agreed to in writing, software\n"+ + "# distributed under the License is distributed on an \"AS IS\" BASIS,\n"+ + "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"+ + "# See the License for the specific language governing permissions and\n"+ + "# limitations under the License.\n";++ @Test+ void testRestrictedRegoGoldenFile() throws IOException {+ String actual = renderGoldenResults();+ Path goldenFile = repositoryRoot().resolve(GOLDEN_FILE);+ if (Boolean.parseBoolean(System.getenv(UPDATE_GOLDEN_ENV))) {+ Files.writeString(goldenFile, actual, StandardCharsets.UTF_8);+ }++ String expected = Files.readString(goldenFile, StandardCharsets.UTF_8);+ Assertions.assertEquals(+ expected,+ actual,+ "Golden output changed. Review the parser behavior and regenerate with "+ + UPDATE_GOLDEN_ENV+ + "=true if the change is intentional.");+ }++ @Test+ void testParsesDocumentedPrograms() throws IOException {+ List<String> programs = documentedPrograms(repositoryRoot().resolve("docs/policies.md"));++ Assertions.assertFalse(programs.isEmpty());+ for (String program : programs) {+ Assertions.assertDoesNotThrow(() -> RestrictedRegoExpressionParserFacade.parse(program));+ }+ }++ @Test+ void testFindsRepositoryRootFromChildDirectory() {+ Path expected = repositoryRoot();++ Assertions.assertEquals(+ Optional.of(expected), findRepositoryRoot(expected.resolve("core/src/test")));+ }++ private static String renderGoldenResults() throws IOException {+ StringBuilder result = new StringBuilder(GOLDEN_LICENSE_HEADER);+ List<String> lines;+ try (InputStream input =+ TestRestrictedRegoGoldenFile.class.getResourceAsStream(GOLDEN_CASES_RESOURCE)) {+ Assertions.assertNotNull(input, "restricted Rego golden cases");+ lines = new String(input.readAllBytes(), StandardCharsets.UTF_8).lines().toList();+ }++ for (String line : lines) {+ if (line.isBlank() || line.startsWith("#")) {+ continue;+ }+ String[] fields = line.split("\\t", 2);+ Assertions.assertEquals(2, fields.length, "Invalid restricted Rego golden case: " + line);+ String name = fields[0];+ String source = fields[1];+ result.append('\n').append("=== ").append(name).append(" ===\n");+ result.append("source: ").append(escapeGoldenValue(source)).append('\n');+ try {+ RestrictedRegoProgram program = RestrictedRegoExpressionParserFacade.parse(source);+ result.append("result: ").append(escapeGoldenValue(program.toString())).append('\n');+ if (program instanceof RowFilter && ((RowFilter) program).isConditional()) {+ result+ .append("lowered: ")+ .append(escapeGoldenValue(((RowFilter) program).lower().toString()))+ .append('\n');+ }+ } catch (IllegalArgumentException exception) {+ result.append("error: ").append(escapeGoldenValue(exception.getMessage())).append('\n');+ }+ }+ return result.toString();+ }++ private static String escapeGoldenValue(String value) {+ return value+ .replace("\\", "\\\\")+ .replace("\r", "\\r")+ .replace("\n", "\\n")+ .replace("\t", "\\t");+ }++ private static Path repositoryRoot() {+ String repositoryRoot = System.getProperty(REPOSITORY_ROOT_PROPERTY);+ if (repositoryRoot != null && !repositoryRoot.isBlank()) {+ return Path.of(repositoryRoot).toAbsolutePath().normalize();+ }++ Path workingDirectory = Path.of("").toAbsolutePath().normalize();+ return findRepositoryRoot(workingDirectory)+ .orElseThrow(+ () ->+ new IllegalStateException(+ "Cannot find the repository root from " + workingDirectory));+ }++ private static Optional<Path> findRepositoryRoot(Path start) {+ for (Path current = start.toAbsolutePath().normalize();+ current != null;+ current = current.getParent()) {+ if (Files.isRegularFile(current.resolve("docs/policies.md"))) {+ return Optional.of(current);+ }+ }+ return Optional.empty();+ }++ private static List<String> documentedPrograms(Path policiesDocument) throws IOException {+ List<String> programs = new ArrayList<>();+ StringBuilder current = null;+ for (String line : Files.readAllLines(policiesDocument, StandardCharsets.UTF_8)) {+ if (line.equals("```restricted-rego-v1")) {+ Assertions.assertNull(current, "Nested restricted Rego documentation fence");+ current = new StringBuilder();+ } else if (current != null && line.equals("```")) {+ programs.add(current.toString().stripTrailing());+ current = null;+ } else if (current != null) {+ current.append(line).append('\n');+ }+ }+ Assertions.assertNull(current, "Unclosed restricted Rego documentation fence");+ return programs;+ }+}diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoLexer.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoLexer.javanew file mode 100644index 0000000000..b4a8346b97--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoLexer.java@@ -0,0 +1,81 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import org.apache.gravitino.policy.rego.RestrictedRegoLexer.Token;+import org.apache.gravitino.policy.rego.RestrictedRegoLexer.TokenType;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Tests for {@link RestrictedRegoLexer}. */+public class TestRestrictedRegoLexer {++ @Test+ void testTokenizesSourceWithOneBasedLocations() {+ RestrictedRegoLexer lexer = new RestrictedRegoLexer("filter :=\n col(\"x\") >= -1");++ assertToken(lexer.nextToken(), TokenType.FILTER, "filter", 1, 1);+ assertToken(lexer.nextToken(), TokenType.ASSIGN, ":=", 1, 8);+ assertToken(lexer.nextToken(), TokenType.COL, "col", 2, 2);+ assertToken(lexer.nextToken(), TokenType.LPAREN, "(", 2, 5);+ assertToken(lexer.nextToken(), TokenType.STRING, "\"x\"", 2, 6);+ assertToken(lexer.nextToken(), TokenType.RPAREN, ")", 2, 9);+ assertToken(lexer.nextToken(), TokenType.GTE, ">=", 2, 11);+ assertToken(lexer.nextToken(), TokenType.NUMBER, "-1", 2, 14);+ assertToken(lexer.nextToken(), TokenType.EOF, "", 2, 16);+ }++ @Test+ void testRejectsInvalidUnicodeEscapeDigits() {+ for (String invalidEscape : RestrictedRegoTestUtils.invalidUnicodeEscapes()) {+ IllegalArgumentException error =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> new RestrictedRegoLexer("\"" + invalidEscape + "\"").nextToken());+ Assertions.assertTrue(error.getMessage().contains("invalid Unicode escape"));+ }+ }++ @Test+ void testRejectsMalformedTokensAtTheirStart() {+ IllegalArgumentException identifierError =+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> new RestrictedRegoLexer("region").nextToken());+ Assertions.assertTrue(identifierError.getMessage().contains("line 1, column 1"));+ Assertions.assertTrue(identifierError.getMessage().contains("unsupported identifier region"));++ IllegalArgumentException leadingZeroError =+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> new RestrictedRegoLexer("01").nextToken());+ Assertions.assertTrue(leadingZeroError.getMessage().contains("leading zeros"));++ IllegalArgumentException largeNumberError =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> new RestrictedRegoLexer("1" + "0".repeat(256)).nextToken());+ Assertions.assertTrue(largeNumberError.getMessage().contains("must not exceed 256 bytes"));+ }++ private static void assertToken(Token token, TokenType type, String text, int line, int column) {+ Assertions.assertEquals(type, token.type);+ Assertions.assertEquals(text, token.text);+ Assertions.assertEquals(line, token.line);+ Assertions.assertEquals(column, token.column);+ }+}diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoProgram.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoProgram.javanew file mode 100644index 0000000000..f5a1cee4a5--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoProgram.java@@ -0,0 +1,113 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import org.apache.gravitino.policy.rego.RestrictedRegoProgram.RowFilter;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Tests for {@link RestrictedRegoProgram}. */+public class TestRestrictedRegoProgram {++ @Test+ void testLowersConditionalRowFilterWithFirstMatchSemantics() {+ RowFilter filter =+ RestrictedRegoExpressionParserFacade.parseRowFilter(+ "filter := col(\"tenant\") == session_user() if is_group_member(\"member\") "+ + "else := col(\"public\") == true if session_user() == \"guest\" "+ + "else := false");++ Assertions.assertTrue(filter.isConditional());+ Assertions.assertEquals(2, filter.branches().size());+ Assertions.assertInstanceOf(GroupMembership.class, filter.branches().get(0).condition());+ Assertions.assertEquals(+ ComparisonOperator.EQ, ((Comparison) filter.branches().get(1).condition()).operator());+ Assertions.assertEquals(false, ((Literal) filter.fallback()).value());+ Assertions.assertThrows(UnsupportedOperationException.class, () -> filter.branches().add(null));++ CanonicalExpression expected =+ RestrictedRegoTestUtils.parseFilterExpression(+ "(is_group_member(\"member\") and col(\"tenant\") == session_user()) or "+ + "(not is_group_member(\"member\") and "+ + "((session_user() == \"guest\" and col(\"public\") == true) or "+ + "(not session_user() == \"guest\" and false)))");+ Assertions.assertEquals(expected, filter.lower());+ Assertions.assertEquals(6, filter.lower().depth());+ }++ @Test+ void testDoesNotApplySourceDepthLimitToGeneratedPredicate() {+ RowFilter filter =+ RestrictedRegoExpressionParserFacade.parseRowFilter(+ "filter := true if not not not not not not not col(\"active\") == true "+ + "else := false");++ Assertions.assertTrue(filter.lower().depth() > RestrictedRegoLimits.MAX_SOURCE_DEPTH);+ }++ @Test+ void testFoldsDoubleNegationIntroducedByLowering() {+ RowFilter filter =+ RestrictedRegoExpressionParserFacade.parseRowFilter(+ "filter := true if not is_group_member(\"g\") else := false");++ CanonicalExpression expected =+ RestrictedRegoTestUtils.parseFilterExpression(+ "(not is_group_member(\"g\") and true) or " + "(is_group_member(\"g\") and false)");+ Assertions.assertEquals(expected, filter.lower());+ }++ @Test+ void testLowersConditionalBranchesWithLinearNodeGrowth() {+ RowFilter filter =+ RestrictedRegoExpressionParserFacade.parseRowFilter(+ RestrictedRegoTestUtils.conditionalFilterWithBranches(24));++ Assertions.assertEquals(265, RestrictedRegoTestUtils.countExpressionNodes(filter.lower()));+ }++ @Test+ void testLowersMaximumNumberOfMinimalBranchesWithinSourceNodeLimit() {+ StringBuilder source = new StringBuilder();+ for (int index = 0; index < 127; index++) {+ source.append(index == 0 ? "filter := true if true" : " else := true if true");+ }+ source.append(" else := false");++ RowFilter filter = RestrictedRegoExpressionParserFacade.parseRowFilter(source.toString());+ CanonicalExpression lowered = filter.lower();++ Assertions.assertEquals(127, filter.branches().size());+ Assertions.assertEquals(256, lowered.depth());+ Assertions.assertEquals(890, RestrictedRegoTestUtils.countExpressionNodes(lowered));+ }++ @Test+ void testDoesNotApplySourceArrayLimitToGeneratedPredicate() {+ RowFilter filter =+ Assertions.assertDoesNotThrow(+ () ->+ RestrictedRegoExpressionParserFacade.parseRowFilter(+ "filter := true if col(\"value\") in "+ + RestrictedRegoTestUtils.literalArray(256)+ + " else := true if is_group_member(\"fallback\") else := false"));++ Assertions.assertEquals(512, RestrictedRegoTestUtils.countArrayElements(filter.lower()));+ }+}diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoSourceParser.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoSourceParser.javanew file mode 100644index 0000000000..d6afa5b961--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoSourceParser.java@@ -0,0 +1,256 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import java.math.BigDecimal;+import java.util.List;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.ColumnMask;+import org.apache.gravitino.policy.rego.RestrictedRegoProgram.MaskAction;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++/** Tests for {@link RestrictedRegoSourceParser}. */+public class TestRestrictedRegoSourceParser {++ @Test+ void testParsesContextReferences() {+ Comparison comparison =+ (Comparison)+ RestrictedRegoTestUtils.parseFilterExpression("col(\"owner\") == session_user()");++ Assertions.assertEquals(ComparisonOperator.EQ, comparison.operator());+ Assertions.assertEquals("owner", ((Column) comparison.left()).name());+ Assertions.assertInstanceOf(SessionUser.class, comparison.right());++ GroupMembership membership =+ (GroupMembership)+ RestrictedRegoTestUtils.parseFilterExpression("is_group_member(\"auditors\")");+ Assertions.assertEquals("auditors", membership.group());+ }++ @Test+ void testParsesPrecedenceAndLiteralArray() {+ LogicalExpression or =+ (LogicalExpression)+ RestrictedRegoTestUtils.parseFilterExpression(+ "col(\"region\") in [\"US\", \"CA\"] or "+ + "col(\"level\") >= 3 and not col(\"deleted\") == true");++ Assertions.assertEquals(LogicalOperator.OR, or.operator());+ Assertions.assertEquals(2, or.operands().size());++ Comparison membership = (Comparison) or.operands().get(0);+ Assertions.assertEquals(ComparisonOperator.IN, membership.operator());+ LiteralArray values = (LiteralArray) membership.right();+ Assertions.assertEquals(LiteralType.STRING, values.elementType());+ Assertions.assertEquals(+ List.of("US", "CA"),+ List.of(values.values().get(0).value(), values.values().get(1).value()));++ LogicalExpression and = (LogicalExpression) or.operands().get(1);+ Assertions.assertEquals(LogicalOperator.AND, and.operator());+ Assertions.assertEquals(+ ComparisonOperator.GTE, ((Comparison) and.operands().get(0)).operator());+ Not not = (Not) and.operands().get(1);+ Assertions.assertEquals(ComparisonOperator.EQ, ((Comparison) not.operand()).operator());+ }++ @Test+ void testParsesConditionalColumnMask() {+ ColumnMask mask =+ RestrictedRegoExpressionParserFacade.parseColumnMask(+ "mask := action(\"show-last-4\") if is_group_member(\"support\") "+ + "else := action(\"sha-256-query-local\") if session_user() == \"service\" "+ + "else := action(\"replace-with-null\")");++ Assertions.assertTrue(mask.isConditional());+ Assertions.assertEquals(2, mask.branches().size());+ Assertions.assertEquals(MaskAction.SHOW_LAST_4, mask.branches().get(0).action());+ Assertions.assertEquals(MaskAction.SHA_256_QUERY_LOCAL, mask.branches().get(1).action());+ Assertions.assertEquals(MaskAction.REPLACE_WITH_NULL, mask.fallback());+ Assertions.assertInstanceOf(GroupMembership.class, mask.branches().get(0).condition());+ }++ @ParameterizedTest+ @ValueSource(+ strings = {+ "mask-alphanum",+ "mask-to-fixed-value",+ "replace-with-null",+ "show-first-4",+ "show-last-4",+ "truncate-to-year",+ "truncate-to-month",+ "sha-256-global",+ "sha-256-query-local"+ })+ void testAcceptsAllMaskActions(String action) {+ ColumnMask mask =+ RestrictedRegoExpressionParserFacade.parseColumnMask("mask := action(\"" + action + "\")");+ Assertions.assertEquals(action, mask.fallback().value());+ }++ @Test+ void testRetainsExactNumbersAndNegativeZero() {+ Comparison comparison =+ (Comparison) RestrictedRegoTestUtils.parseFilterExpression("col(\"ratio\") == -0.00");+ Literal literal = (Literal) comparison.right();++ Assertions.assertEquals(new BigDecimal("0.00"), literal.value());+ Assertions.assertTrue(literal.negativeZero());++ Comparison positiveZero =+ (Comparison) RestrictedRegoTestUtils.parseFilterExpression("col(\"ratio\") == 0.00");+ Assertions.assertNotEquals(literal, positiveZero.right());++ Comparison one = (Comparison) RestrictedRegoTestUtils.parseFilterExpression("col(\"x\") == 1");+ Comparison onePointZero =+ (Comparison) RestrictedRegoTestUtils.parseFilterExpression("col(\"x\") == 1.00");+ Assertions.assertEquals(one.right(), onePointZero.right());+ }++ @Test+ void testDecodesJsonStringsWithoutNormalizing() {+ Comparison comparison =+ (Comparison)+ RestrictedRegoTestUtils.parseFilterExpression("col(\"a\\\"b.c\") == \"a'b\\n\"");++ Assertions.assertEquals("a\"b.c", ((Column) comparison.left()).name());+ Assertions.assertEquals("a'b\n", ((Literal) comparison.right()).value());++ String escapedPair = "\\" + "uD83D" + "\\" + "uDE00";+ Comparison unicode =+ (Comparison)+ RestrictedRegoTestUtils.parseFilterExpression(+ "col(\"emoji\") == \"" + escapedPair + "\"");+ Assertions.assertEquals("😀", ((Literal) unicode.right()).value());++ String delEscape = RestrictedRegoTestUtils.unicodeEscape('0', '0', '7', 'f');+ Comparison controls =+ (Comparison)+ RestrictedRegoTestUtils.parseFilterExpression(+ "col(\"line\\nname\") == \"a" + delEscape + "b\"");+ Assertions.assertEquals("line\nname", ((Column) controls.left()).name());+ Assertions.assertEquals("a" + (char) 0x7F + "b", ((Literal) controls.right()).value());++ GroupMembership controlGroup =+ (GroupMembership)+ RestrictedRegoTestUtils.parseFilterExpression("is_group_member(\"a\\tb\")");+ Assertions.assertEquals("a\tb", controlGroup.group());+ }++ @Test+ void testRejectsExcessiveNotDepthDuringParsing() {+ String source = "filter := " + "not ".repeat(4090) + "true";++ IllegalArgumentException error =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> new RestrictedRegoSourceParser(source).parseProgram());++ Assertions.assertTrue(+ error+ .getMessage()+ .contains("source depth must not exceed " + RestrictedRegoLimits.MAX_SOURCE_DEPTH));+ }++ @ParameterizedTest+ @ValueSource(+ strings = {+ "col(\"owner\") == session_user()",+ "session_user() != col(\"owner\")",+ "session_user() == \"alice\"",+ "\"alice\" != session_user()",+ "session_user() in [\"alice\", \"bob\"]",+ "is_group_member(\"auditors\")",+ "col(\"region\") in [\"US\", \"CA\"]",+ "not col(\"deleted\") == true",+ "col(\"level\") >= 3 and col(\"region\") == \"US\"",+ "col(\"nullable\") == null",+ "null != col(\"nullable\")",+ "true",+ "false"+ })+ void testAcceptsAllowlistedExpressions(String expression) {+ Assertions.assertDoesNotThrow(() -> RestrictedRegoTestUtils.parseFilterExpression(expression));+ }++ @ParameterizedTest+ @ValueSource(+ strings = {+ "col(\"owner\")",+ "session_user()",+ "\"alice\"",+ "1",+ "null",+ "[\"US\"]",+ "is_group_member(\"\")",+ "is_group_member(\"auditors\") == true",+ "col(\"left\") == col(\"right\")",+ "1 == 1",+ "col(\"active\") > true",+ "false <= col(\"active\")",+ "session_user() < \"bob\"",+ "session_user() == true",+ "session_user() == session_user()",+ "col(\"region\") in []",+ "col(\"region\") in [\"US\", 1]",+ "col(\"region\") in [\"US\", null]",+ "col(\"region\") == [\"US\"]",+ "col(\"level\") + 1 > 3",+ "col(\"level\") == 1e3",+ "col(\"level\") == +1",+ "col(\"level\") == 01",+ "col(\"a\") < 2 < 3",+ "notcol(\"active\") == true",+ "trueand false",+ "col(\"level\") == 1and col(\"region\") == \"US\"",+ "session_userx() == \"alice\"",+ "col(\"owner\") == \"alice\" trailing",+ "identity(\"user\") == col(\"owner\")",+ "input.user == \"alice\"",+ "col(\"x\") == \"unterminated",+ "col(\"x\") == \"line\nbreak\""+ })+ void testRejectsUnsupportedOrMalformedExpressions(String expression) {+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> RestrictedRegoTestUtils.parseFilterExpression(expression));+ }++ @Test+ void testReportsSpecificOneBasedSyntaxLocations() {+ IllegalArgumentException characterError =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> RestrictedRegoExpressionParserFacade.parseRowFilter("filter := @"));+ Assertions.assertTrue(characterError.getMessage().contains("line 1, column 11"));++ IllegalArgumentException chainedComparisonError =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ RestrictedRegoExpressionParserFacade.parseRowFilter(+ "filter := col(\"x\") == 1 == true"));+ Assertions.assertTrue(+ chainedComparisonError.getMessage().contains("chained comparisons are not supported"));+ }+}diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoSourceValidator.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoSourceValidator.javanew file mode 100644index 0000000000..e4e08bab84--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoSourceValidator.java@@ -0,0 +1,164 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Tests for {@link RestrictedRegoSourceValidator}. */+public class TestRestrictedRegoSourceValidator {++ @Test+ void testSourceDepthLimit() {+ CanonicalExpression depthEight =+ RestrictedRegoTestUtils.parseFilterExpression(+ "not not not not not not not col(\"active\") == true");+ Assertions.assertEquals(RestrictedRegoLimits.MAX_SOURCE_DEPTH, depthEight.depth());++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ RestrictedRegoTestUtils.parseFilterExpression(+ "not not not not not not not not col(\"active\") == true"));+ }++ @Test+ void testSemanticErrorsDescribeOperandKindsWithoutValues() {+ IllegalArgumentException error =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> RestrictedRegoTestUtils.parseFilterExpression("col(\"b\") < true"));++ Assertions.assertTrue(error.getMessage().contains("boolean literal supports only == and !="));+ Assertions.assertTrue(error.getMessage().contains("operator '<'"));+ Assertions.assertTrue(error.getMessage().contains("left=column"));+ Assertions.assertTrue(error.getMessage().contains("right=literal(BOOLEAN)"));++ IllegalArgumentException largeComparisonError =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ RestrictedRegoTestUtils.parseFilterExpression(+ "session_user() in " + RestrictedRegoTestUtils.literalArray(256)));+ Assertions.assertTrue(largeComparisonError.getMessage().length() < 512);+ Assertions.assertFalse(largeComparisonError.getMessage().contains("value=255"));+ }++ @Test+ void testRejectsInvalidUnicodeScalarsAndNul() {+ String isolatedSurrogate = "\\" + "uD800";+ String nul = "\\" + "u0000";+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ RestrictedRegoTestUtils.parseFilterExpression(+ "col(\"" + isolatedSurrogate + "\") == \"x\""));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ RestrictedRegoTestUtils.parseFilterExpression(+ "col(\"x\") == \"" + isolatedSurrogate + "\""));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> RestrictedRegoTestUtils.parseFilterExpression("col(\"" + nul + "\") == \"x\""));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> RestrictedRegoTestUtils.parseFilterExpression("is_group_member(\"" + nul + "\")"));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> RestrictedRegoTestUtils.parseFilterExpression("col(\"x\") == \"" + nul + "\""));+ }++ @Test+ void testStringAndNumericLimits() {+ String maximumString = "a".repeat(RestrictedRegoLimits.MAX_STRING_BYTES);+ Assertions.assertDoesNotThrow(+ () ->+ RestrictedRegoTestUtils.parseFilterExpression(+ "col(\"value\") == \"" + maximumString + "\""));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ RestrictedRegoTestUtils.parseFilterExpression(+ "col(\"value\") == \"" + maximumString + "a\""));++ String maximumUnicodeString = "😀".repeat(RestrictedRegoLimits.MAX_STRING_BYTES / 4);+ Assertions.assertDoesNotThrow(+ () ->+ RestrictedRegoTestUtils.parseFilterExpression(+ "col(\"value\") == \"" + maximumUnicodeString + "\""));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ RestrictedRegoTestUtils.parseFilterExpression(+ "col(\"value\") == \"" + maximumUnicodeString + "😀\""));++ String maximumNumber = "1" + "0".repeat(RestrictedRegoLimits.MAX_NUMERIC_LITERAL_BYTES - 1);+ Assertions.assertDoesNotThrow(+ () -> RestrictedRegoTestUtils.parseFilterExpression("col(\"value\") == " + maximumNumber));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ RestrictedRegoTestUtils.parseFilterExpression(+ "col(\"value\") == " + maximumNumber + "0"));+ }++ @Test+ void testArrayAndAstLimits() {+ Assertions.assertDoesNotThrow(+ () ->+ RestrictedRegoTestUtils.parseFilterExpression(+ "col(\"value\") in "+ + RestrictedRegoTestUtils.literalArray(+ RestrictedRegoLimits.MAX_ARRAY_ELEMENTS)));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ RestrictedRegoTestUtils.parseFilterExpression(+ "col(\"value\") in "+ + RestrictedRegoTestUtils.literalArray(+ RestrictedRegoLimits.MAX_ARRAY_ELEMENTS + 1)));++ Assertions.assertDoesNotThrow(+ () ->+ RestrictedRegoTestUtils.parseFilterExpression(+ "col(\"left\") in "+ + RestrictedRegoTestUtils.literalArray(128)+ + " or col(\"right\") in "+ + RestrictedRegoTestUtils.literalArray(128)));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ RestrictedRegoTestUtils.parseFilterExpression(+ "col(\"left\") in "+ + RestrictedRegoTestUtils.literalArray(128)+ + " or col(\"right\") in "+ + RestrictedRegoTestUtils.literalArray(129)));++ Assertions.assertDoesNotThrow(+ () ->+ RestrictedRegoTestUtils.parseFilterExpression(+ RestrictedRegoTestUtils.balancedAndExpression(0, 85)));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ RestrictedRegoTestUtils.parseFilterExpression(+ RestrictedRegoTestUtils.balancedAndExpression(0, 86)));+ }+}diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestSessionUser.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestSessionUser.javanew file mode 100644index 0000000000..e352df7731--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/policy/rego/TestSessionUser.java@@ -0,0 +1,35 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.policy.rego;++import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Tests for {@link SessionUser}. */+public class TestSessionUser {++ @Test+ void testValueSemantics() {+ SessionUser user = new SessionUser();+ Assertions.assertDoesNotThrow(user::validate);+ Assertions.assertEquals(0, user.depth());+ Assertions.assertEquals(user, new SessionUser());+ Assertions.assertEquals(user.hashCode(), new SessionUser().hashCode());+ }+}diff --git a/core/src/test/resources/restricted-rego-v1-cases.golden b/core/src/test/resources/restricted-rego-v1-cases.goldennew file mode 100644index 0000000000..84963a9da0--- /dev/null+++ b/core/src/test/resources/restricted-rego-v1-cases.golden@@ -0,0 +1,91 @@+# Licensed to the Apache Software Foundation (ASF) under one or more+# contributor license agreements. See the NOTICE file distributed with+# this work for additional information regarding copyright ownership.+# The ASF licenses this file to You under the Apache License, Version 2.0+# (the "License"); you may not use this file except in compliance with+# the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++=== column-session-user ===+source: filter := col("owner") == session_user()+result: RowFilter{branches=[], fallback=Comparison{operator=EQ, left=Column{name='owner'}, right=SessionUser{}}}++=== session-user-array ===+source: filter := session_user() in ["alice", "bob"]+result: RowFilter{branches=[], fallback=Comparison{operator=IN, left=SessionUser{}, right=LiteralArray{elementType=STRING, values=[Literal{literalType=STRING, value=alice, negativeZero=false}, Literal{literalType=STRING, value=bob, negativeZero=false}]}}}++=== logical-precedence ===+source: filter := col("region") in ["US", "CA"] or col("level") >= 3+result: RowFilter{branches=[], fallback=LogicalExpression{operator=OR, operands=[Comparison{operator=IN, left=Column{name='region'}, right=LiteralArray{elementType=STRING, values=[Literal{literalType=STRING, value=US, negativeZero=false}, Literal{literalType=STRING, value=CA, negativeZero=false}]}}, Comparison{operator=GTE, left=Column{name='level'}, right=Literal{literalType=NUMBER, value=3, negativeZero=false}}]}}++=== unicode-escape ===+source: filter := col("letter") == "\\u0041"+result: RowFilter{branches=[], fallback=Comparison{operator=EQ, left=Column{name='letter'}, right=Literal{literalType=STRING, value=A, negativeZero=false}}}++=== non-ascii-unicode-escape ===+source: filter := col("\\u٠٠٤١") == "x"+error: Invalid restricted-rego-v1 program at line 1, column 15: invalid Unicode escape in string++=== group-name-nul ===+source: filter := is_group_member("\\u0000")+error: group name cannot contain NUL++=== conditional-filter ===+source: filter := true if is_group_member("auditors") else := false+result: RowFilter{branches=[FilterBranch{result=Literal{literalType=BOOLEAN, value=true, negativeZero=false}, condition=GroupMembership{group='auditors'}}], fallback=Literal{literalType=BOOLEAN, value=false, negativeZero=false}}+lowered: LogicalExpression{operator=OR, operands=[LogicalExpression{operator=AND, operands=[GroupMembership{group='auditors'}, Literal{literalType=BOOLEAN, value=true, negativeZero=false}]}, LogicalExpression{operator=AND, operands=[Not{operand=GroupMembership{group='auditors'}}, Literal{literalType=BOOLEAN, value=false, negativeZero=false}]}]}++=== conditional-mask ===+source: mask := action("show-last-4") if is_group_member("support") else := action("replace-with-null")+result: ColumnMask{branches=[MaskBranch{action=SHOW_LAST_4, condition=GroupMembership{group='support'}}], fallback=REPLACE_WITH_NULL}++=== uppercase-in-title ===+source: filter := col("region") In ["US"]+error: Invalid restricted-rego-v1 program at line 1, column 25: unsupported identifier In++=== uppercase-in ===+source: filter := col("region") IN ["US"]+error: Invalid restricted-rego-v1 program at line 1, column 25: unsupported identifier IN++=== mixed-case-in ===+source: filter := col("region") iN ["US"]+error: Invalid restricted-rego-v1 program at line 1, column 25: unsupported identifier iN++=== column-to-column ===+source: filter := col("left") == col("right")+error: Unsupported operands for == in restricted-rego-v1; operator '==' with left=column and right=column++=== literal-to-literal ===+source: filter := 1 == 1+error: Unsupported operands for == in restricted-rego-v1; operator '==' with left=literal(NUMBER) and right=literal(NUMBER)++=== boolean-ordering ===+source: filter := col("active") > true+error: boolean literal supports only == and !=; operator '>' with left=column and right=literal(BOOLEAN)++=== session-user-ordering ===+source: filter := session_user() < "bob"+error: session_user() supports only == and !=; operator '<' with left=session-user and right=literal(STRING)++=== empty-array ===+source: filter := col("region") in []+error: Invalid restricted-rego-v1 program at line 1, column 29: expected a literal array element++=== heterogeneous-array ===+source: filter := col("region") in ["US", 1]+error: array literals must have one homogeneous non-null type++=== missing-final-else ===+source: filter := true if is_group_member("auditors")+error: Invalid restricted-rego-v1 program at line 1, column 46: expected final else branch++=== column-dependent-mask ===+source: mask := action("show-last-4") if col("region") == "US" else := action("replace-with-null")+error: column-mask condition cannot contain col(...)diff --git a/core/src/test/resources/restricted-rego-v1-cases.txt b/core/src/test/resources/restricted-rego-v1-cases.txtnew file mode 100644index 0000000000..8794dfc473--- /dev/null+++ b/core/src/test/resources/restricted-rego-v1-cases.txt@@ -0,0 +1,35 @@+# Licensed to the Apache Software Foundation (ASF) under one or more+# contributor license agreements. See the NOTICE file distributed with+# this work for additional information regarding copyright ownership.+# The ASF licenses this file to You under the Apache License, Version 2.0+# (the "License"); you may not use this file except in compliance with+# the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+# case name<TAB>source+column-session-user filter := col("owner") == session_user()+session-user-array filter := session_user() in ["alice", "bob"]+logical-precedence filter := col("region") in ["US", "CA"] or col("level") >= 3+unicode-escape filter := col("letter") == "\u0041"+non-ascii-unicode-escape filter := col("\u٠٠٤١") == "x"+group-name-nul filter := is_group_member("\u0000")+conditional-filter filter := true if is_group_member("auditors") else := false+conditional-mask mask := action("show-last-4") if is_group_member("support") else := action("replace-with-null")+uppercase-in-title filter := col("region") In ["US"]+uppercase-in filter := col("region") IN ["US"]+mixed-case-in filter := col("region") iN ["US"]+column-to-column filter := col("left") == col("right")+literal-to-literal filter := 1 == 1+boolean-ordering filter := col("active") > true+session-user-ordering filter := session_user() < "bob"+empty-array filter := col("region") in []+heterogeneous-array filter := col("region") in ["US", 1]+missing-final-else filter := true if is_group_member("auditors")+column-dependent-mask mask := action("show-last-4") if col("region") == "US" else := action("replace-with-null")diff --git a/design-docs/tag-based-read-restrictions-for-iceberg-rest.md b/design-docs/tag-based-read-restrictions-for-iceberg-rest.mdindex 5531791495..0b39d8aa52 100644--- a/design-docs/tag-based-read-restrictions-for-iceberg-rest.md+++ b/design-docs/tag-based-read-restrictions-for-iceberg-rest.md@@ -291,9 +291,12 @@ call.`filter` and `mask` are Gravitino restricted-syntax keywords, not standard Rego keywords. `filter`is valid only as the row-filter rule head, and `mask` is valid only as the column-mask rule head.-Column names, group names, and string values appear only as JSON string literals. A name equal to a-keyword needs no special keyword escape: `col("and")` references the column named `and`. Backticks,-single quotes, SQL delimited identifiers, and backslash escaping outside a JSON string are invalid.+Column names, group names, and string values appear only as JSON string literals. Raw U+0000 through+U+001F characters and decoded NUL are invalid. Valid JSON escapes for control characters other than+NUL, such as `\n`, are decoded and preserved. U+007F is also preserved in literal or escaped form. A+name equal to a keyword needs no special keyword escape: `col("and")` references the column named+`and`. Backticks, single quotes, SQL delimited identifiers, and backslash escaping outside a JSON+string are invalid.For example, this expression is valid and unambiguous:@@ -359,12 +362,23 @@ Save-time validation applies these limits before canonicalization:- source length: 16 KiB of UTF-8;- operation depth: 8;-- AST nodes: 256;-- decoded string literal: 4 KiB of UTF-8; and-- array elements: 256.--The resolved predicate also has maximum operation depth 8. Canonicalization cannot make an-oversized expression valid.+- source AST nodes: 256;+- decoded string literal: 4 KiB of UTF-8;+- numeric literal: 256 bytes;+- elements per literal array: 256;+- total array elements: 256 in the source; and+- parenthesis nesting: 256 levels.++Operation depth counts AST operation nodes. A consecutive associative `and` or `or` chain is one+n-ary logical node, and parentheses do not add depth. These limits apply to user-provided source.+They are not re-applied to the generated row-filter predicate.++Conditional row filters use linear nested lowering. Each condition appears once in its selected arm+and once, negated, in its remaining-branches arm. The source limits therefore bound generated work:+lowering is linear in the number and size of source branches, and generated array occurrences are at+most twice the source total. Under the 256-node source limit, 127 minimal branches lower to a+predicate with depth 256 and 890 node occurrences. A generated predicate may exceed the source+depth or node limits.## Context and Schema Binding@@ -397,8 +411,10 @@ is lowered to:```text(condition1 and result1)-or (not condition1 and condition2 and result2)-or (not condition1 and not condition2 and fallback)+or (not condition1 and (+ (condition2 and result2)+ or (not condition2 and fallback)+))```Request-context-only conditions are folded before the final predicate is built, but every branch@@ -407,6 +423,7 @@ evaluates them in order and selects the first action whose condition is true, oraction. The conditional assignment, `if`, and `else` nodes never appear in the Iceberg wireexpression or projection. This preserves the first-matching-branch semantics of Rego's `else`chain while producing the one closed Boolean predicate or one column action required by Iceberg.+The nested form grows linearly rather than repeating every earlier condition in every later branch.The first version supports these value predicates:diff --git a/docs/open-api/policies.yaml b/docs/open-api/policies.yamlindex 6440c2a290..e2310534b0 100644--- a/docs/open-api/policies.yaml+++ b/docs/open-api/policies.yaml@@ -516,7 +516,12 @@ components:type: stringminLength: 1pattern: '[\s\S]*\S[\s\S]*'- description: A nonblank expression whose UTF-8 encoding must not exceed 16 KiB.+ description: >-+ A complete restricted-rego-v1 row-filter program beginning with `filter :=`.+ Results and conditions must be Boolean. The program may use col("name"),+ session_user(), is_group_member("group"), literals, comparisons, in, and/or/not,+ including ordered `else := ... if ...` branches with a final `else`. The UTF-8 source+ must not exceed 16 KiB; see the Policies documentation for grammar, limits, and examples.ColumnMaskContent:type: object@@ -528,7 +533,12 @@ components:type: stringminLength: 1pattern: '[\s\S]*\S[\s\S]*'- description: A nonblank expression whose UTF-8 encoding must not exceed 16 KiB.+ description: >-+ A complete restricted-rego-v1 column-mask program beginning with+ `mask := action("...")`. Conditions are optional, must use only trusted request+ context, and require ordered `else := action(...) if ...` branches plus a final+ `else`. The UTF-8 source must not exceed 16 KiB; see the Policies documentation for+ allowlisted actions, grammar, limits, and examples.RowFilterPolicy:allOf:diff --git a/docs/policies.md b/docs/policies.mdindex 71f5b67654..832126444a 100644--- a/docs/policies.md+++ b/docs/policies.md@@ -47,6 +47,126 @@ The row-filter and column-mask policy types can be created and associated with tdoes not enforce them yet. Until enforcement is available, these policy types do not restrict dataaccess.+### Read-Restriction Expressions++Row-filter and column-mask expressions use `restricted-rego-v1`, a small, fail-closed Rego-like+syntax owned by Gravitino. Each expression is one complete rule, not an arbitrary Rego module. A+row filter starts with `filter :=` and produces a Boolean predicate. A column mask starts with+`mask := action("...")` and produces an allowlisted masking action.++The complete grammar is:++```text+program := filterRule | maskRule+filterRule := unconditionalFilter | conditionalFilter+unconditionalFilter := "filter" ":=" expr+conditionalFilter := "filter" ":=" expr "if" expr filterElse* filterFallback+filterElse := "else" ":=" expr "if" expr+filterFallback := "else" ":=" expr+maskRule := unconditionalMask | conditionalMask+unconditionalMask := "mask" ":=" maskAction+conditionalMask := "mask" ":=" maskAction "if" contextExpr maskElse* maskFallback+maskElse := "else" ":=" maskAction "if" contextExpr+maskFallback := "else" ":=" maskAction+maskAction := "action" "(" string ")"+contextExpr := expr+expr := orExpr+orExpr := andExpr ("or" andExpr)*+andExpr := notExpr ("and" notExpr)*+notExpr := "not" notExpr | compareExpr+compareExpr := primary (("==" | "!=" | "<" | "<=" | ">" | ">=" | "in") primary)?+primary := colRef | sessionUser | groupMember | literal | array | "(" expr ")"+colRef := "col" "(" string ")"+sessionUser := "session_user" "(" ")"+groupMember := "is_group_member" "(" string ")"+literal := string | number | boolean | null+array := "[" literal ("," literal)* "]"+boolean := "true" | "false"+null := "null"+number := "-"? ("0" | nonZeroDigit digit*) ("." digit+)?+digit := "0" | nonZeroDigit+nonZeroDigit := "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"+```++For example, a row-filter program can select the first matching predicate:++```restricted-rego-v1+filter := col("region") == "US" if is_group_member("auditors")+else := col("owner") == session_user()+```++This column-mask program selects a masking action in the same way:++```restricted-rego-v1+mask := action("show-last-4") if is_group_member("support")+else := action("replace-with-null")+```++Conditional branches are evaluated from left to right. The first true condition selects its result,+and every conditional rule must end with an unconditional `else`. Row-filter conditions and results+must be Boolean. Column-mask conditions may use only request context; they cannot reference columns.++The syntax supports these constructs:++- `col("name")`, `session_user()`, and `is_group_member("group")`;+- JSON string literals, exact decimal numbers, `true`, `false`, `null`, and homogeneous non-null+ literal arrays;+- comparisons `==`, `!=`, `<`, `<=`, `>`, `>=`, and `in`; and+- Boolean operators `and`, `or`, and `not`.++Keywords and built-in function names are case-sensitive. For example, only lowercase `in` is an+operator; `In`, `IN`, and `iN` are invalid.++Strings use JSON double-quoted syntax and are decoded exactly once after the enclosing HTTP JSON is+decoded. Raw U+0000 through U+001F characters, decoded NUL, isolated Unicode surrogates,+single-quoted strings, and invalid JSON escapes are rejected. Valid JSON escapes for control+characters other than NUL, such as `\n`, are decoded and preserved. U+007F is also preserved in+literal or escaped form. Gravitino does not normalize, trim, or case-fold decoded column names,+group names, or values. Numbers are exact decimals; exponent notation, a leading `+`, leading+zeroes, and a trailing decimal point are invalid.++Supported operand shapes are:++| Form | Operators | Requirements |+| --- | --- | --- |+| Boolean predicates | `and`, `or`, `not` | Every operand must be Boolean. |+| Column and non-null literal | `==`, `!=`, `<`, `<=`, `>`, `>=` | Either operand order; types must be compatible. Boolean literals support only `==` and `!=`. |+| String column and `session_user()` | `==`, `!=` | Either operand order. |+| `session_user()` and string literal | `==`, `!=` | Either operand order. |+| Column and `null` | `==`, `!=` | Either operand order. |+| Column and literal array | `in` | Column on the left; array must be non-empty and homogeneous. |+| `session_user()` and string array | `in` | `session_user()` on the left; array must be non-empty. |+| `is_group_member("group")` | none | Produces a Boolean request-context predicate. |++Column-to-column and literal-to-literal comparisons, ordering on `session_user()`, null array+elements, nested arrays, and comparisons on `is_group_member(...)` are invalid.++Column-mask actions are `mask-alphanum`, `mask-to-fixed-value`, `replace-with-null`, `show-first-4`,+`show-last-4`, `truncate-to-year`, `truncate-to-month`, `sha-256-global`, and+`sha-256-query-local`.++Validation applies these limits when a policy is created or its content is updated:++- 16 KiB of UTF-8 source;+- operation depth 8 for the source AST;+- 256 nodes for the source AST;+- 4 KiB of UTF-8 for each decoded string literal;+- 256 bytes for each numeric literal;+- 256 elements in each literal array;+- 256 array elements in total in the source; and+- 256 levels of parenthesis nesting.++These limits apply to user-provided source, not to the generated predicate. Gravitino lowers an+ordered row-filter branch chain to a linear nested Boolean expression in which each condition appears+at most twice. The source limits therefore bound generated work without reducing the array allowance+as branches are added. Under the 256-node source limit, 127 minimal branches lower to a predicate+with depth 256 and 890 node occurrences. A generated predicate may exceed the source depth or node+limits.++Bare identifiers, arbitrary functions, comments, packages, imports, variables, chained+comparisons, nested arrays, and a conditional rule without a final `else` are rejected. Read paths+do not re-parse stored policy expressions.+A custom policy's rules live in `customRules`. Gravitino stores them and returns them to clients;it does not interpret their names or values. Built-in types have a defined content shape. See[Iceberg compaction policy](./iceberg-compaction-policy.md) for the compaction rules and