Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#13719] refactor(policy): Parse SQL read restrictions with ANTLR (#14237)

roryqi486aa4ca0a57
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ec07cf4f7c..37d44fe80d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -228,6 +228,19 @@ You can also build manually with:
Import Gravitino into IntelliJ IDEA or Eclipse as a Gradle project.
+The SQL policy parser's ANTLR runtime is relocated into the packaged core JAR.
+Core's unrelocated module class output uses a `compileOnly` ANTLR dependency, so
+launching the server directly with IDE module outputs requires adding the ANTLR
+runtime version declared in `gradle/libs.versions.toml` to the launch classpath.
+Without it, SQL policy parsing can fail with `NoClassDefFoundError` for
+`org.antlr.v4.runtime` classes. Building the shaded JAR alone does not change the
+IDE's module classpath.
+
+To debug with the packaged runtime, build the distribution, enable
+`GRAVITINO_DEBUG_OPTS` in `conf/gravitino-env.sh`, start it with
+`bin/gravitino.sh start`, and attach an IDE remote JVM debugger as described in
+[the installation guide](docs/how-to-install.md).
+
## 💡 Tips for WSL Users
If using WSL on Windows, install Java and dev tools inside WSL. Access files via `/mnt/c/...` paths.
diff --git a/LICENSE.lance b/LICENSE.lance
index 551a34ad15..6b6373fa59 100644
--- a/LICENSE.lance
+++ b/LICENSE.lance
@@ -266,6 +266,7 @@
This product bundles various third-party components also under the
BSD license
+ ANTLR4
ASM
bigint
JSR305
diff --git a/api/src/main/java/org/apache/gravitino/policy/PolicyContents.java b/api/src/main/java/org/apache/gravitino/policy/PolicyContents.java
index 0c354d53d5..416d69c3d5 100644
--- a/api/src/main/java/org/apache/gravitino/policy/PolicyContents.java
+++ b/api/src/main/java/org/apache/gravitino/policy/PolicyContents.java
@@ -431,9 +431,9 @@ public class PolicyContents {
/**
* Creates a row-filter policy for tagged tables.
*
- * <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.
+ * <p>The expression must be a complete {@code restricted-sql-v1} definition, for example {@code
+ * (region STRING) RETURNS BOOLEAN -> region = 'US'}. The server validates syntax and types when
+ * the policy is created or updated.
*
* @param expression complete row-filter program
* @return structurally validated read-restriction policy content
@@ -447,9 +447,10 @@ public class PolicyContents {
/**
* Creates a column-mask policy for tagged tables or columns.
*
- * <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.
+ * <p>The expression must be a complete {@code restricted-sql-v1} definition with one parameter
+ * and the same return type, for example {@code (value STRING) RETURNS STRING ->
+ * show_last_4(value)}. The parameter binds to the selected column independently of its local
+ * name. The server validates syntax and types when the policy is created or updated.
*
* @param expression complete column-mask program
* @return structurally validated read-restriction policy content
diff --git a/api/src/test/java/org/apache/gravitino/policy/TestReadRestrictionContent.java b/api/src/test/java/org/apache/gravitino/policy/TestReadRestrictionContent.java
index 02f0ea5e4d..886d17986f 100644
--- a/api/src/test/java/org/apache/gravitino/policy/TestReadRestrictionContent.java
+++ b/api/src/test/java/org/apache/gravitino/policy/TestReadRestrictionContent.java
@@ -29,10 +29,10 @@ public class TestReadRestrictionContent {
@Test
void testCreatesReadRestrictionContent() {
String rowFilterExpression =
- "filter := col(\"region\") == \"US\" if is_group_member(\"analysts\") else := false";
+ "(region STRING) RETURNS BOOLEAN -> CASE WHEN is_group_member('analysts') THEN region = 'US' ELSE FALSE END";
String columnMaskExpression =
- "mask := action(\"show-last-4\") if is_group_member(\"analysts\") "
- + "else := action(\"replace-with-null\")";
+ "(value STRING) RETURNS STRING -> CASE WHEN is_group_member('analysts') "
+ + "THEN show_last_4(value) ELSE NULL END";
RowFilterContent rowFilter = PolicyContents.rowFilter(rowFilterExpression);
ColumnMaskContent columnMask = PolicyContents.columnMask(columnMaskExpression);
@@ -54,15 +54,16 @@ public class TestReadRestrictionContent {
@Test
void testEqualityUsesPolicyTypeAndExpression() {
- String expression = "filter := col(\"region\") == \"US\"";
+ String expression = "(region STRING) RETURNS BOOLEAN -> region = 'US'";
Assertions.assertEquals(
PolicyContents.rowFilter(expression), PolicyContents.rowFilter(expression));
Assertions.assertNotEquals(
- PolicyContents.rowFilter(expression), PolicyContents.rowFilter("filter := true"));
+ PolicyContents.rowFilter(expression),
+ PolicyContents.rowFilter("() RETURNS BOOLEAN -> TRUE"));
Assertions.assertNotEquals(
PolicyContents.rowFilter(expression),
- PolicyContents.columnMask("mask := action(\"replace-with-null\")"));
+ PolicyContents.columnMask("(value STRING) RETURNS STRING -> NULL"));
}
@Test
@@ -77,11 +78,11 @@ public class TestReadRestrictionContent {
void testValidatesUtf8ExpressionLength() {
Assertions.assertEquals(16 * 1024, ReadRestrictionContent.MAX_SOURCE_LENGTH_BYTES);
- String rowFilterPrefix = "filter := true";
+ String rowFilterPrefix = "() RETURNS BOOLEAN -> TRUE";
String maximumRowFilter =
rowFilterPrefix
+ " ".repeat(ReadRestrictionContent.MAX_SOURCE_LENGTH_BYTES - rowFilterPrefix.length());
- String columnMaskPrefix = "mask := action(\"replace-with-null\")";
+ String columnMaskPrefix = "(value STRING) RETURNS STRING -> NULL";
String maximumColumnMask =
columnMaskPrefix
+ " "
diff --git a/common/src/test/java/org/apache/gravitino/dto/policy/TestReadRestrictionPolicyDTO.java b/common/src/test/java/org/apache/gravitino/dto/policy/TestReadRestrictionPolicyDTO.java
index 9c1dd80bde..bde0d0f070 100644
--- a/common/src/test/java/org/apache/gravitino/dto/policy/TestReadRestrictionPolicyDTO.java
+++ b/common/src/test/java/org/apache/gravitino/dto/policy/TestReadRestrictionPolicyDTO.java
@@ -37,8 +37,9 @@ public class TestReadRestrictionPolicyDTO {
@Test
void testRowFilterPolicyRoundTrip() throws JsonProcessingException {
String expression =
- "filter := col(\"region\") == \"US\" if is_group_member(\"auditors\") "
- + "else := col(\"owner\") == session_user()";
+ "(\"Customer Region\" STRING, owner STRING) RETURNS BOOLEAN -> "
+ + "CASE WHEN is_group_member('auditors') THEN \"Customer Region\" = 'US' "
+ + "ELSE owner = CURRENT_USER() END";
RowFilterContent content = PolicyContents.rowFilter(expression);
PolicyDTO policy =
PolicyDTO.builder()
@@ -53,7 +54,7 @@ public class TestReadRestrictionPolicyDTO {
Assertions.assertEquals(policy, restored);
Assertions.assertInstanceOf(PolicyContentDTO.RowFilterContentDTO.class, restored.content());
- Assertions.assertTrue(json.contains("\"expression\":\"filter :="));
+ Assertions.assertTrue(json.contains("\"expression\":\"(\\\"Customer Region\\\" STRING"));
Assertions.assertFalse(json.contains("\"rules\""));
Assertions.assertEquals(content, DTOConverters.fromDTO(restored.content()));
Assertions.assertDoesNotThrow(restored.content()::validate);
@@ -67,8 +68,8 @@ public class TestReadRestrictionPolicyDTO {
+ "\"policyType\":\"system_row_filter\","
+ "\"enabled\":true,"
+ "\"content\":{\"expression\":"
- + "\"filter := col(\\\"region\\\") == \\\"US\\\" if "
- + "is_group_member(\\\"auditors\\\") else := false\"}}";
+ + "\"(region STRING) RETURNS BOOLEAN -> CASE WHEN "
+ + "is_group_member('auditors') THEN region = 'US' ELSE FALSE END\"}}";
PolicyCreateRequest request =
JsonUtils.objectMapper().readValue(json, PolicyCreateRequest.class);
@@ -78,7 +79,8 @@ public class TestReadRestrictionPolicyDTO {
RowFilterContent content = (RowFilterContent) DTOConverters.fromDTO(request.getPolicyContent());
Assertions.assertEquals(
- "filter := col(\"region\") == \"US\" if is_group_member(\"auditors\") else := false",
+ "(region STRING) RETURNS BOOLEAN -> CASE WHEN is_group_member('auditors') "
+ + "THEN region = 'US' ELSE FALSE END",
content.expression());
}
@@ -90,9 +92,9 @@ public class TestReadRestrictionPolicyDTO {
+ "\"policyType\":\"system_column_mask\","
+ "\"enabled\":true,"
+ "\"content\":{\"expression\":"
- + "\"mask := action(\\\"show-last-4\\\") if "
- + "is_group_member(\\\"pii_unmasked\\\") "
- + "else := action(\\\"mask-alphanum\\\")\"}}";
+ + "\"(value STRING) RETURNS STRING -> CASE WHEN "
+ + "is_group_member('pii_unmasked') THEN show_last_4(value) "
+ + "ELSE mask_alphanum(value) END\"}}";
PolicyCreateRequest request =
JsonUtils.objectMapper().readValue(json, PolicyCreateRequest.class);
@@ -103,8 +105,8 @@ public class TestReadRestrictionPolicyDTO {
ColumnMaskContent content =
(ColumnMaskContent) DTOConverters.fromDTO(request.getPolicyContent());
Assertions.assertEquals(
- "mask := action(\"show-last-4\") if is_group_member(\"pii_unmasked\") "
- + "else := action(\"mask-alphanum\")",
+ "(value STRING) RETURNS STRING -> CASE WHEN is_group_member('pii_unmasked') "
+ + "THEN show_last_4(value) ELSE mask_alphanum(value) END",
content.expression());
}
@@ -113,25 +115,25 @@ public class TestReadRestrictionPolicyDTO {
assertUpdateRoundTrip(
"system_row_filter",
PolicyContents.rowFilter(
- "filter := col(\"region\") == \"US\" if session_user() == \"alice\" "
- + "else := col(\"owner\") == session_user()"));
+ "(region STRING, owner STRING) RETURNS BOOLEAN -> CASE WHEN CURRENT_USER() = 'alice' "
+ + "THEN region = 'US' ELSE owner = CURRENT_USER() END"));
assertUpdateRoundTrip(
"system_column_mask",
PolicyContents.columnMask(
- "mask := action(\"show-last-4\") if session_user() == \"alice\" "
- + "else := action(\"replace-with-null\")"));
+ "(value STRING) RETURNS STRING -> CASE WHEN CURRENT_USER() = 'alice' "
+ + "THEN show_last_4(value) ELSE NULL END"));
}
@Test
void testStoredContentRoundTripUsesEachBuiltInContentClass() throws JsonProcessingException {
RowFilterContent rowFilter =
PolicyContents.rowFilter(
- "filter := col(\"region\") == \"US\" if is_group_member(\"analysts\") "
- + "else := col(\"owner\") == session_user()");
+ "(region STRING, owner STRING) RETURNS BOOLEAN -> CASE WHEN is_group_member('analysts') "
+ + "THEN region = 'US' ELSE owner = CURRENT_USER() END");
ColumnMaskContent columnMask =
PolicyContents.columnMask(
- "mask := action(\"show-last-4\") if is_group_member(\"analysts\") "
- + "else := action(\"replace-with-null\")");
+ "(value STRING) RETURNS STRING -> CASE WHEN is_group_member('analysts') "
+ + "THEN show_last_4(value) ELSE NULL END");
PolicyContent restoredRowFilter =
JsonUtils.anyFieldMapper()
diff --git a/core/build.gradle.kts b/core/build.gradle.kts
index e53c185bae..459efb988d 100644
--- a/core/build.gradle.kts
+++ b/core/build.gradle.kts
@@ -1,3 +1,4 @@
+import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import net.ltgt.gradle.errorprone.errorprone
/*
@@ -22,12 +23,21 @@ plugins {
`maven-publish`
id("java")
id("idea")
+ antlr
alias(libs.plugins.jcstress)
alias(libs.plugins.jmh)
alias(libs.plugins.aspectj.post.compile.weaving)
+ alias(libs.plugins.shadow)
+}
+
+val shadedAntlr by configurations.creating {
+ isCanBeConsumed = false
}
dependencies {
+ antlr(libs.antlr.tool)
+ shadedAntlr(libs.antlr.runtime)
+ compileOnly(libs.antlr.runtime)
implementation(project(":api"))
implementation(project(":common"))
implementation(project(":catalogs:catalog-common"))
@@ -78,6 +88,7 @@ dependencies {
testImplementation(project(":server-common"))
testImplementation(project(":clients:client-java"))
testImplementation(libs.awaitility)
+ testImplementation(libs.antlr.runtime)
testImplementation(libs.junit.jupiter.api)
testImplementation(libs.junit.jupiter.params)
testImplementation(libs.junit.platform.testkit)
@@ -202,11 +213,12 @@ tasks.named<JacocoReport>("jacocoTestReport") {
// :core:test is kept for IDEs and local habit, and is deprecated: run a lane instead. CI skips it
// (`build` passes `-x :core:test`) and runs each lane in its own `core-test` job.
-// TestRestrictedRegoGoldenFile reads docs/policies.md. It is a unit test, so only coreUnitTest and
+// TestRestrictedSqlGoldenFile reads docs/policies.md. It is a unit test, so only coreUnitTest and
// the legacy :core:test run it; the database lanes don't need the input.
listOf("coreUnitTest", "test").forEach {
tasks.named<Test>(it) {
inputs.file(rootProject.file("docs/policies.md"))
+ inputs.property("updateRestrictedSqlGolden", providers.environmentVariable("GRAVITINO_UPDATE_RESTRICTED_SQL_GOLDEN").orElse("false"))
systemProperty("gravitino.repositoryRoot", rootProject.projectDir.path)
}
}
@@ -227,11 +239,52 @@ tasks.test {
}
tasks.withType<JavaCompile>().configureEach {
+ options.errorprone.excludedPaths.set(".*/generated-src/antlr/.*")
if (name.contains("jcstress", ignoreCase = true)) {
- options.errorprone.excludedPaths.set(".*/generated/.*")
+ options.errorprone.excludedPaths.set(".*/(generated|generated-src/antlr)/.*")
}
}
+// The generator is build tooling; only antlr4-runtime belongs on the server classpath.
+configurations.matching { it.name in setOf("api", "implementation") }.configureEach {
+ setExtendsFrom(extendsFrom.filterNot { it.name == "antlr" })
+}
+
+tasks.generateGrammarSource {
+ arguments = arguments + listOf("-visitor", "-no-listener", "-package", "org.apache.gravitino.policy.sql.antlr")
+}
+
+tasks.named<Jar>("sourcesJar") {
+ dependsOn(tasks.generateGrammarSource)
+}
+
+val shadedCoreJar = tasks.named<ShadowJar>("shadowJar") {
+ configurations = listOf(shadedAntlr)
+ archiveClassifier.set("")
+ relocate("org.antlr.v4.runtime", "org.apache.gravitino.shaded.org.antlr.v4.runtime")
+}
+
+tasks.jar {
+ enabled = false
+ dependsOn(shadedCoreJar)
+}
+
+// Every runtime consumer, including Spark test fixtures, must use the relocated parser classes.
+listOf("apiElements", "runtimeElements").forEach { name ->
+ configurations.named(name) {
+ outgoing.artifacts.clear()
+ outgoing.artifact(shadedCoreJar)
+ }
+}
+
+components.named<AdhocComponentWithVariants>("java") {
+ withVariantsFromConfiguration(configurations["shadowRuntimeElements"]) { skip() }
+}
+
+tasks.javadoc {
+ exclude("**/policy/sql/antlr/**")
+}
+
tasks.named<JavaCompile>("jmhCompileGeneratedClasses").configure {
options.errorprone.isEnabled = false
options.compilerArgs.removeAll { it.contains("Xplugin:ErrorProne") }
diff --git a/core/src/main/antlr/org/apache/gravitino/policy/sql/antlr/RestrictedSql.g4 b/core/src/main/antlr/org/apache/gravitino/policy/sql/antlr/RestrictedSql.g4
new file mode 100644
index 0000000000..5da736401f
--- /dev/null
+++ b/core/src/main/antlr/org/apache/gravitino/policy/sql/antlr/RestrictedSql.g4
@@ -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.
+ */
+grammar RestrictedSql;
+
+options { caseInsensitive = true; }
+
+definition: LPAREN (parameter (COMMA parameter)*)? RPAREN RETURNS dataType ARROW expression EOF;
+parameter: identifier dataType;
+dataType
+ : BOOLEAN | INTEGER | LONG | FLOAT | DOUBLE | STRING_TYPE | BINARY | DATE
+ | DECIMAL LPAREN NUMBER COMMA NUMBER RPAREN
+ | TIME (LPAREN NUMBER RPAREN)?
+ | TIMESTAMP (LPAREN NUMBER RPAREN)? ((WITH | WITHOUT) TIME ZONE)?
+ ;
+expression: orExpression;
+orExpression: andExpression (OR andExpression)*;
+andExpression: notExpression (AND notExpression)*;
+notExpression: NOT* predicate;
+predicate
+ : scalar (comparisonOperator scalar
+ | IS NOT? NULL
+ | NOT? IN LPAREN literal (COMMA literal)* RPAREN
+ | NOT? BETWEEN scalar AND scalar
+ | NOT? LIKE STRING)?
+ ;
+comparisonOperator: EQ | NEQ | LT | LTE | GT | GTE;
+scalar
+ : identifier
+ | literal
+ | functionCall
+ | caseExpression
+ | LPAREN expression RPAREN
+ ;
+functionCall: identifier LPAREN (expression (COMMA expression)*)? RPAREN;
+caseExpression: CASE expression? whenClause+ (ELSE expression)? END;
+whenClause: WHEN expression THEN expression;
+literal
+ : STRING | NUMBER | TRUE | FALSE | NULL
+ | DATE STRING
+ | TIME STRING
+ | TIMESTAMP (WITH TIME ZONE)? STRING
+ ;
+identifier: IDENTIFIER | QUOTED_IDENTIFIER;
+
+RETURNS: 'RETURNS';
+BOOLEAN: 'BOOLEAN';
+INTEGER: 'INTEGER';
+LONG: 'LONG';
+FLOAT: 'FLOAT';
+DOUBLE: 'DOUBLE';
+STRING_TYPE: 'STRING';
+BINARY: 'BINARY';
+DATE: 'DATE';
+DECIMAL: 'DECIMAL';
+TIME: 'TIME';
+TIMESTAMP: 'TIMESTAMP';
+WITH: 'WITH';
+WITHOUT: 'WITHOUT';
+ZONE: 'ZONE';
+OR: 'OR';
+AND: 'AND';
+NOT: 'NOT';
+IS: 'IS';
+NULL: 'NULL';
+IN: 'IN';
+BETWEEN: 'BETWEEN';
+LIKE: 'LIKE';
+CASE: 'CASE';
+WHEN: 'WHEN';
+THEN: 'THEN';
+ELSE: 'ELSE';
+END: 'END';
+TRUE: 'TRUE';
+FALSE: 'FALSE';
+ARROW: '->';
+LPAREN: '(';
+RPAREN: ')';
+COMMA: ',';
+EQ: '=';
+NEQ: '<>' | '!=';
+LTE: '<=';
+GTE: '>=';
+LT: '<';
+GT: '>';
+NUMBER: '-'? ('0' | [1-9] [0-9]*) ('.' [0-9]+)?;
+STRING: '\'' ('\'\'' | ~'\'')* '\'';
+QUOTED_IDENTIFIER: '"' ('""' | ~'"')* '"';
+IDENTIFIER: [a-z_] [a-z_0-9]*;
+WHITESPACE: [ \t\r\n]+ -> skip;
diff --git a/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java b/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java
index 55e623c9d7..2ec5a804d0 100644
--- a/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java
+++ b/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java
@@ -42,7 +42,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.policy.sql.RestrictedSqlExpressionParserFacade;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.utils.MetadataObjectUtil;
import org.apache.gravitino.utils.NameIdentifierUtil;
@@ -381,11 +381,11 @@ public class PolicyManager implements PolicyDispatcher {
private static void validateReadRestrictionContent(
Policy.BuiltInType policyType, PolicyContent content) {
if (policyType == Policy.BuiltInType.ROW_FILTER && content instanceof RowFilterContent) {
- RestrictedRegoExpressionParserFacade.validateRowFilter(
+ RestrictedSqlExpressionParserFacade.validateRowFilter(
((RowFilterContent) content).expression());
} else if (policyType == Policy.BuiltInType.COLUMN_MASK
&& content instanceof ColumnMaskContent) {
- RestrictedRegoExpressionParserFacade.validateColumnMask(
+ RestrictedSqlExpressionParserFacade.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.java
deleted file mode 100644
index 622e5ca7f6..0000000000
--- a/core/src/main/java/org/apache/gravitino/policy/rego/CanonicalExpression.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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.
- */
-public 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/Comparison.java b/core/src/main/java/org/apache/gravitino/policy/rego/Comparison.java
deleted file mode 100644
index 1b5e1e6c94..0000000000
--- a/core/src/main/java/org/apache/gravitino/policy/rego/Comparison.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * 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. */
-public 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;
- }
-
- /**
- * Returns the comparison operator.
- *
- * @return comparison operator
- */
- public ComparisonOperator operator() {
- return operator;
- }
-
- /**
- * Returns the left operand.
- *
- * @return left operand
- */
- public CanonicalExpression left() {
- return left;
- }
-
- /**
- * Returns the right operand.
- *
- * @return right operand
- */
- public 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/ExpressionValidator.java b/core/src/main/java/org/apache/gravitino/policy/rego/ExpressionValidator.java
deleted file mode 100644
index 9d5c8bb9f2..0000000000
--- a/core/src/main/java/org/apache/gravitino/policy/rego/ExpressionValidator.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * 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.java
deleted file mode 100644
index f3e96e4753..0000000000
--- a/core/src/main/java/org/apache/gravitino/policy/rego/GroupMembership.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * 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. */
-public final class GroupMembership implements CanonicalExpression {
- private final String group;
-
- GroupMembership(String group) {
- this.group = group;
- }
-
- /**
- * Returns the exact group name.
- *
- * @return group name
- */
- public 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.java
deleted file mode 100644
index 9df5420b26..0000000000
--- a/core/src/main/java/org/apache/gravitino/policy/rego/Literal.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * 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. */
-public 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;
- }
-
- /**
- * Returns the source literal type.
- *
- * @return literal type
- */
- public LiteralType literalType() {
- return literalType;
- }
-
- /**
- * Returns the decoded literal value.
- *
- * @return decoded value, or {@code null} for a null literal
- */
- public Object value() {
- return value;
- }
-
- /**
- * Returns whether a numeric zero used a negative sign in the source.
- *
- * @return {@code true} for source negative zero
- */
- public 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.java
deleted file mode 100644
index 6c6830e837..0000000000
--- a/core/src/main/java/org/apache/gravitino/policy/rego/LiteralArray.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * 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. */
-public 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));
- }
-
- /**
- * Returns the homogeneous element type.
- *
- * @return element type
- */
- public LiteralType elementType() {
- return elementType;
- }
-
- /**
- * Returns the immutable decoded literal values.
- *
- * @return literal values
- */
- public 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/LogicalExpression.java b/core/src/main/java/org/apache/gravitino/policy/rego/LogicalExpression.java
deleted file mode 100644
index 9ccac1954a..0000000000
--- a/core/src/main/java/org/apache/gravitino/policy/rego/LogicalExpression.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * 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. */
-public 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);
- }
-
- /**
- * Returns the logical operator.
- *
- * @return logical operator
- */
- public LogicalOperator operator() {
- return operator;
- }
-
- /**
- * Returns the immutable operands.
- *
- * @return logical operands
- */
- public 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/Not.java b/core/src/main/java/org/apache/gravitino/policy/rego/Not.java
deleted file mode 100644
index 1792723781..0000000000
--- a/core/src/main/java/org/apache/gravitino/policy/rego/Not.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * 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. */
-public 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);
- }
-
- /**
- * Returns the negated operand.
- *
- * @return negated operand
- */
- public 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.java
deleted file mode 100644
index 3e411482b5..0000000000
--- a/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoExpressionParserFacade.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * 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
- */
- public 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}
- */
- public 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}
- */
- public 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.java
deleted file mode 100644
index c0918cf0d8..0000000000
--- a/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoLexer.java
+++ /dev/null
@@ -1,322 +0,0 @@
-/*
- * 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.java
deleted file mode 100644
index 40d7726322..0000000000
--- a/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoLimits.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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.java
deleted file mode 100644
index 8e7f680035..0000000000
--- a/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoProgram.java
+++ /dev/null
@@ -1,410 +0,0 @@
-/*
- * 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. */
-public 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.java
deleted file mode 100644
index 6fb02f4790..0000000000
--- a/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoSourceParser.java
+++ /dev/null
@@ -1,358 +0,0 @@
-/*
- * 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.java
deleted file mode 100644
index 2714b5a8ee..0000000000
--- a/core/src/main/java/org/apache/gravitino/policy/rego/RestrictedRegoSourceValidator.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * 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/sql/Between.java b/core/src/main/java/org/apache/gravitino/policy/sql/Between.java
new file mode 100644
index 0000000000..9d0f3f96ca
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/Between.java
@@ -0,0 +1,68 @@
+/*
+ * 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.sql;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/** An inclusive SQL range test. */
+public final class Between extends SqlExpression {
+ Between(SqlExpression operand, SqlExpression lower, SqlExpression upper) {
+ super(Arrays.asList(operand, lower, upper));
+ }
+
+ /**
+ * Returns the source operand.
+ *
+ * @return the source operand
+ */
+ public SqlExpression operand() {
+ return children().get(0);
+ }
+
+ /**
+ * Returns the inclusive lower bound.
+ *
+ * @return the inclusive lower bound
+ */
+ public SqlExpression lower() {
+ return children().get(1);
+ }
+
+ /**
+ * Returns the inclusive upper bound.
+ *
+ * @return the inclusive upper bound
+ */
+ public SqlExpression upper() {
+ return children().get(2);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof Between && sameContents((Between) other);
+ }
+
+ @Override
+ List<?> attributes() {
+ return Collections.emptyList();
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestColumn.java b/core/src/main/java/org/apache/gravitino/policy/sql/CaseBranch.java
similarity index 54%
rename from core/src/test/java/org/apache/gravitino/policy/rego/TestColumn.java
rename to core/src/main/java/org/apache/gravitino/policy/sql/CaseBranch.java
index 5fccffff92..acb0ae1e96 100644
--- a/core/src/test/java/org/apache/gravitino/policy/rego/TestColumn.java
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/CaseBranch.java
@@ -16,21 +16,33 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.policy.rego;
+package org.apache.gravitino.policy.sql;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.Test;
+/** One ordered WHEN/THEN arm in a searched or simple CASE expression. */
+public final class CaseBranch {
+ private final SqlExpression condition;
+ private final SqlExpression result;
-/** Tests for {@link Column}. */
-public class TestColumn {
+ CaseBranch(SqlExpression condition, SqlExpression result) {
+ this.condition = condition;
+ this.result = result;
+ }
+
+ /**
+ * Returns the WHEN condition or simple CASE match value.
+ *
+ * @return the WHEN condition or simple CASE match value
+ */
+ public SqlExpression condition() {
+ return condition;
+ }
- @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());
+ /**
+ * Returns the THEN result.
+ *
+ * @return the THEN result
+ */
+ public SqlExpression result() {
+ return result;
}
}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/CaseExpression.java b/core/src/main/java/org/apache/gravitino/policy/sql/CaseExpression.java
new file mode 100644
index 0000000000..64a57c4427
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/CaseExpression.java
@@ -0,0 +1,115 @@
+/*
+ * 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.sql;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import javax.annotation.Nullable;
+
+/** A searched or simple CASE, preserving first-match order and an optional ELSE. */
+public final class CaseExpression extends SqlExpression {
+ @Nullable private final SqlExpression selector;
+ private final List<CaseBranch> branches;
+ @Nullable private final SqlExpression fallback;
+
+ CaseExpression(
+ @Nullable SqlExpression selector,
+ List<CaseBranch> branches,
+ @Nullable SqlExpression fallback) {
+ super(children(selector, branches, fallback));
+ this.selector = selector;
+ this.branches = Collections.unmodifiableList(new ArrayList<>(branches));
+ this.fallback = fallback;
+ }
+
+ /**
+ * Returns the simple CASE selector, or null for searched CASE.
+ *
+ * @return the simple CASE selector, or null for searched CASE
+ */
+ @Nullable
+ public SqlExpression selector() {
+ return selector;
+ }
+
+ /**
+ * Returns the immutable ordered WHEN/THEN branches.
+ *
+ * @return the immutable ordered WHEN/THEN branches
+ */
+ public List<CaseBranch> branches() {
+ return branches;
+ }
+
+ /**
+ * Returns the ELSE expression, or null when omitted.
+ *
+ * @return the ELSE expression, or null when omitted
+ */
+ @Nullable
+ public SqlExpression fallback() {
+ return fallback;
+ }
+
+ /**
+ * Returns the immutable explicitly authored result branches.
+ *
+ * @return the immutable explicitly authored result branches
+ */
+ public List<SqlExpression> results() {
+ List<SqlExpression> result = new ArrayList<>();
+ branches.forEach(branch -> result.add(branch.result()));
+ if (fallback != null) {
+ result.add(fallback);
+ }
+ return Collections.unmodifiableList(result);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof CaseExpression && sameContents((CaseExpression) other);
+ }
+
+ @Override
+ List<?> attributes() {
+ return Arrays.asList(selector != null, fallback != null);
+ }
+
+ private static List<SqlExpression> children(
+ @Nullable SqlExpression selector,
+ List<CaseBranch> branches,
+ @Nullable SqlExpression fallback) {
+ List<SqlExpression> result = new ArrayList<>();
+ if (selector != null) {
+ result.add(selector);
+ }
+ branches.forEach(
+ branch -> {
+ result.add(branch.condition());
+ result.add(branch.result());
+ });
+ if (fallback != null) {
+ result.add(fallback);
+ }
+ return result;
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/Comparison.java b/core/src/main/java/org/apache/gravitino/policy/sql/Comparison.java
new file mode 100644
index 0000000000..5519ca196d
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/Comparison.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.sql;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/** A binary comparison with SQL three-valued null semantics. */
+public final class Comparison extends SqlExpression {
+ private final ComparisonOperator operator;
+
+ Comparison(ComparisonOperator operator, SqlExpression left, SqlExpression right) {
+ super(Arrays.asList(left, right));
+ this.operator = operator;
+ }
+
+ /**
+ * Returns the typed operator.
+ *
+ * @return the typed operator
+ */
+ public ComparisonOperator operator() {
+ return operator;
+ }
+
+ /**
+ * Returns the left comparison operand.
+ *
+ * @return the left comparison operand
+ */
+ public SqlExpression left() {
+ return children().get(0);
+ }
+
+ /**
+ * Returns the right comparison operand.
+ *
+ * @return the right comparison operand
+ */
+ public SqlExpression right() {
+ return children().get(1);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof Comparison && sameContents((Comparison) other);
+ }
+
+ @Override
+ List<?> attributes() {
+ return Collections.singletonList(operator);
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/ComparisonOperator.java b/core/src/main/java/org/apache/gravitino/policy/sql/ComparisonOperator.java
similarity index 50%
rename from core/src/main/java/org/apache/gravitino/policy/rego/ComparisonOperator.java
rename to core/src/main/java/org/apache/gravitino/policy/sql/ComparisonOperator.java
index baf554d689..c64b70cba5 100644
--- a/core/src/main/java/org/apache/gravitino/policy/rego/ComparisonOperator.java
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/ComparisonOperator.java
@@ -16,56 +16,52 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.policy.rego;
+package org.apache.gravitino.policy.sql;
-import com.google.common.base.Preconditions;
-
-/** Comparison operators supported by {@code restricted-rego-v1}. */
+/** Binary comparison operators in restricted SQL. */
public enum ComparisonOperator {
- /** Equality comparison. */
- EQ("=="),
- /** Inequality comparison. */
- NEQ("!="),
- /** Less-than comparison. */
+ /** SQL EQ comparison. */
+ EQ("="),
+ /** SQL NEQ comparison. */
+ NEQ("<>"),
+ /** SQL LT comparison. */
LT("<"),
- /** Less-than-or-equal comparison. */
+ /** SQL LTE comparison. */
LTE("<="),
- /** Greater-than comparison. */
+ /** SQL GT comparison. */
GT(">"),
- /** Greater-than-or-equal comparison. */
- GTE(">="),
- /** Literal-array membership comparison. */
- IN("in");
-
+ /** SQL GTE comparison. */
+ GTE(">=");
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);
- }
+ /**
+ * Returns the SQL source token.
+ *
+ * @return the SQL source token
+ */
+ public String sourceToken() {
+ return sourceToken;
}
- String sourceToken() {
- return sourceToken;
+ /**
+ * Returns whether this is an ordering comparison.
+ *
+ * @return whether this is an ordering comparison
+ */
+ public boolean ordered() {
+ return this != EQ && this != NEQ;
+ }
+
+ static ComparisonOperator fromToken(String token) {
+ for (ComparisonOperator operator : values()) {
+ if (operator.sourceToken.equals(token) || operator == NEQ && token.equals("!=")) {
+ return operator;
+ }
+ }
+ throw new IllegalArgumentException("Unsupported SQL comparison: " + token);
}
}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/FunctionCall.java b/core/src/main/java/org/apache/gravitino/policy/sql/FunctionCall.java
new file mode 100644
index 0000000000..706b574162
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/FunctionCall.java
@@ -0,0 +1,61 @@
+/*
+ * 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.sql;
+
+import java.util.Collections;
+import java.util.List;
+
+/** A call to an allowlisted function; it is not executed during parsing. */
+public final class FunctionCall extends SqlExpression {
+ private final SqlFunction function;
+
+ FunctionCall(SqlFunction function, List<SqlExpression> arguments) {
+ super(arguments);
+ this.function = function;
+ }
+
+ /**
+ * Returns the allowlisted function.
+ *
+ * @return the allowlisted function
+ */
+ public SqlFunction function() {
+ return function;
+ }
+
+ /**
+ * Returns the immutable ordered function arguments.
+ *
+ * @return the immutable ordered function arguments
+ */
+ public List<SqlExpression> arguments() {
+ return children();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof FunctionCall && sameContents((FunctionCall) other);
+ }
+
+ @Override
+ List<?> attributes() {
+ return Collections.singletonList(function);
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/In.java b/core/src/main/java/org/apache/gravitino/policy/sql/In.java
new file mode 100644
index 0000000000..7bc68f1fe7
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/In.java
@@ -0,0 +1,66 @@
+/*
+ * 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.sql;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/** SQL membership in a literal list, including null members. */
+public final class In extends SqlExpression {
+ In(SqlExpression operand, List<Literal> values) {
+ super(children(operand, values));
+ }
+
+ /**
+ * Returns the source operand.
+ *
+ * @return the source operand
+ */
+ public SqlExpression operand() {
+ return children().get(0);
+ }
+
+ /**
+ * Returns the immutable membership list.
+ *
+ * @return the immutable membership list
+ */
+ public List<SqlExpression> values() {
+ return children().subList(1, children().size());
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof In && sameContents((In) other);
+ }
+
+ @Override
+ List<?> attributes() {
+ return Collections.emptyList();
+ }
+
+ private static List<SqlExpression> children(SqlExpression operand, List<Literal> values) {
+ List<SqlExpression> result = new ArrayList<>();
+ result.add(operand);
+ result.addAll(values);
+ return result;
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/Column.java b/core/src/main/java/org/apache/gravitino/policy/sql/InputReference.java
similarity index 54%
rename from core/src/main/java/org/apache/gravitino/policy/rego/Column.java
rename to core/src/main/java/org/apache/gravitino/policy/sql/InputReference.java
index 7eeaf5bc70..8bc59c8011 100644
--- a/core/src/main/java/org/apache/gravitino/policy/rego/Column.java
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/InputReference.java
@@ -16,55 +16,55 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.policy.rego;
+package org.apache.gravitino.policy.sql;
-import com.google.common.base.Preconditions;
-import java.util.Objects;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
-/** A symbolic top-level column reference. */
-public final class Column implements CanonicalExpression {
+/** A declared local parameter, unresolved against a physical column. */
+public final class InputReference extends SqlExpression {
private final String name;
+ private final SqlType type;
- Column(String name) {
+ InputReference(String name, SqlType type) {
+ super(Collections.emptyList());
this.name = name;
+ this.type = type;
}
/**
- * Returns the symbolic top-level column name.
+ * Returns the normalized local parameter name.
*
- * @return column name
+ * @return the normalized local parameter name
*/
public String name() {
return name;
}
+ /**
+ * Returns the intrinsic logical type, or null when inferred from context.
+ *
+ * @return the intrinsic logical type, or null when inferred from context
+ */
@Override
- public void validate() throws IllegalArgumentException {
- Preconditions.checkArgument(name != null && !name.isEmpty(), "column name cannot be empty");
- ExpressionValidator.validateUnicodeScalars(name, "column name");
+ public SqlType type() {
+ return type;
}
@Override
- public int depth() {
+ int depth() {
return 0;
}
+ /** {@inheritDoc} */
@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);
+ return other instanceof InputReference && sameContents((InputReference) other);
}
@Override
- public String toString() {
- return "Column{" + "name='" + name + '\'' + '}';
+ List<?> attributes() {
+ return Arrays.asList(name, type);
}
}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/IsNull.java b/core/src/main/java/org/apache/gravitino/policy/sql/IsNull.java
new file mode 100644
index 0000000000..c658124f91
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/IsNull.java
@@ -0,0 +1,61 @@
+/*
+ * 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.sql;
+
+import java.util.Collections;
+import java.util.List;
+
+/** IS NULL or IS NOT NULL, without rewriting ordinary comparisons with null. */
+public final class IsNull extends SqlExpression {
+ private final boolean negated;
+
+ IsNull(SqlExpression operand, boolean negated) {
+ super(Collections.singletonList(operand));
+ this.negated = negated;
+ }
+
+ /**
+ * Returns the source operand.
+ *
+ * @return the source operand
+ */
+ public SqlExpression operand() {
+ return children().get(0);
+ }
+
+ /**
+ * Returns whether this is IS NOT NULL.
+ *
+ * @return whether this is IS NOT NULL
+ */
+ public boolean negated() {
+ return negated;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof IsNull && sameContents((IsNull) other);
+ }
+
+ @Override
+ List<?> attributes() {
+ return Collections.singletonList(negated);
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/Like.java b/core/src/main/java/org/apache/gravitino/policy/sql/Like.java
new file mode 100644
index 0000000000..4c38c5cd0b
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/Like.java
@@ -0,0 +1,59 @@
+/*
+ * 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.sql;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/** A case-sensitive fixed-prefix SQL LIKE predicate. */
+public final class Like extends SqlExpression {
+ Like(SqlExpression operand, Literal pattern) {
+ super(Arrays.asList(operand, pattern));
+ }
+
+ /**
+ * Returns the source operand.
+ *
+ * @return the source operand
+ */
+ public SqlExpression operand() {
+ return children().get(0);
+ }
+
+ /**
+ * Returns the literal prefix pattern.
+ *
+ * @return the literal prefix pattern
+ */
+ public Literal pattern() {
+ return (Literal) children().get(1);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof Like && sameContents((Like) other);
+ }
+
+ @Override
+ List<?> attributes() {
+ return Collections.emptyList();
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/Literal.java b/core/src/main/java/org/apache/gravitino/policy/sql/Literal.java
new file mode 100644
index 0000000000..795227230a
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/Literal.java
@@ -0,0 +1,90 @@
+/*
+ * 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.sql;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import javax.annotation.Nullable;
+
+/** A literal retaining its exact decoded text, including negative zero. */
+public final class Literal extends SqlExpression {
+ private final LiteralType literalType;
+ private final String value;
+ @Nullable private final SqlType type;
+
+ /**
+ * Creates a literal retaining its exact decoded text.
+ *
+ * @param literalType source literal kind
+ * @param value decoded literal text
+ * @param type intrinsic or trusted declared type, or null for an inferred literal
+ */
+ public Literal(LiteralType literalType, String value, @Nullable SqlType type) {
+ super(Collections.emptyList());
+ this.literalType = literalType;
+ this.value = value;
+ this.type = type;
+ }
+
+ /**
+ * Returns the source literal kind.
+ *
+ * @return the source literal kind
+ */
+ public LiteralType literalType() {
+ return literalType;
+ }
+
+ /**
+ * Returns the exact decoded literal text.
+ *
+ * @return the exact decoded literal text
+ */
+ public String value() {
+ return value;
+ }
+
+ /**
+ * Returns the intrinsic logical type, or null when inferred from context.
+ *
+ * @return the intrinsic logical type, or null when inferred from context
+ */
+ @Nullable
+ @Override
+ public SqlType type() {
+ return type;
+ }
+
+ @Override
+ int depth() {
+ return 0;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof Literal && sameContents((Literal) other);
+ }
+
+ @Override
+ List<?> attributes() {
+ return Arrays.asList(literalType, value, type);
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/LiteralType.java b/core/src/main/java/org/apache/gravitino/policy/sql/LiteralType.java
similarity index 77%
rename from core/src/main/java/org/apache/gravitino/policy/rego/LiteralType.java
rename to core/src/main/java/org/apache/gravitino/policy/sql/LiteralType.java
index e83ca32fde..279972f1db 100644
--- a/core/src/main/java/org/apache/gravitino/policy/rego/LiteralType.java
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/LiteralType.java
@@ -16,16 +16,18 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.policy.rego;
+package org.apache.gravitino.policy.sql;
-/** Source literal types supported by {@code restricted-rego-v1}. */
+/** Source literal kinds; numeric and NULL values acquire their expected type during validation. */
public enum LiteralType {
- /** String literal. */
+ /** String. */
STRING,
- /** Exact base-10 numeric literal. */
+ /** Number. */
NUMBER,
- /** Boolean literal. */
+ /** Boolean. */
BOOLEAN,
- /** Null literal. */
- NULL
+ /** Null. */
+ NULL,
+ /** Temporal. */
+ TEMPORAL
}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/LogicalExpression.java b/core/src/main/java/org/apache/gravitino/policy/sql/LogicalExpression.java
new file mode 100644
index 0000000000..33075c03d2
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/LogicalExpression.java
@@ -0,0 +1,61 @@
+/*
+ * 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.sql;
+
+import java.util.Collections;
+import java.util.List;
+
+/** An n-ary SQL Boolean conjunction or disjunction, retaining source operand order. */
+public final class LogicalExpression extends SqlExpression {
+ private final LogicalOperator operator;
+
+ LogicalExpression(LogicalOperator operator, List<SqlExpression> operands) {
+ super(operands);
+ this.operator = operator;
+ }
+
+ /**
+ * Returns the typed operator.
+ *
+ * @return the typed operator
+ */
+ public LogicalOperator operator() {
+ return operator;
+ }
+
+ /**
+ * Returns the immutable logical operands.
+ *
+ * @return the immutable logical operands
+ */
+ public List<SqlExpression> operands() {
+ return children();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof LogicalExpression && sameContents((LogicalExpression) other);
+ }
+
+ @Override
+ List<?> attributes() {
+ return Collections.singletonList(operator);
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/LogicalOperator.java b/core/src/main/java/org/apache/gravitino/policy/sql/LogicalOperator.java
similarity index 69%
rename from core/src/main/java/org/apache/gravitino/policy/rego/LogicalOperator.java
rename to core/src/main/java/org/apache/gravitino/policy/sql/LogicalOperator.java
index 88a45fe59f..b8c1fb64dc 100644
--- a/core/src/main/java/org/apache/gravitino/policy/rego/LogicalOperator.java
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/LogicalOperator.java
@@ -16,22 +16,12 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.policy.rego;
+package org.apache.gravitino.policy.sql;
-/** N-ary logical operators supported by {@code restricted-rego-v1}. */
+/** N-ary Boolean composition operators. */
public enum LogicalOperator {
- /** Boolean conjunction. */
- AND("and"),
- /** Boolean disjunction. */
- OR("or");
-
- private final String sourceToken;
-
- LogicalOperator(String sourceToken) {
- this.sourceToken = sourceToken;
- }
-
- String sourceToken() {
- return sourceToken;
- }
+ /** And. */
+ AND,
+ /** Or. */
+ OR
}
diff --git a/core/src/main/java/org/apache/gravitino/policy/rego/SessionUser.java b/core/src/main/java/org/apache/gravitino/policy/sql/Not.java
similarity index 61%
rename from core/src/main/java/org/apache/gravitino/policy/rego/SessionUser.java
rename to core/src/main/java/org/apache/gravitino/policy/sql/Not.java
index c8f4a33995..8f50029321 100644
--- a/core/src/main/java/org/apache/gravitino/policy/rego/SessionUser.java
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/Not.java
@@ -16,32 +16,34 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.policy.rego;
+package org.apache.gravitino.policy.sql;
-/** A symbolic reference to the trusted effective session user. */
-public final class SessionUser implements CanonicalExpression {
- SessionUser() {}
+import java.util.Collections;
+import java.util.List;
- @Override
- public void validate() throws IllegalArgumentException {}
-
- @Override
- public int depth() {
- return 0;
+/** SQL negation; an unknown operand stays unknown. */
+public final class Not extends SqlExpression {
+ Not(SqlExpression operand) {
+ super(Collections.singletonList(operand));
}
- @Override
- public boolean equals(Object other) {
- return other instanceof SessionUser;
+ /**
+ * Returns the source operand.
+ *
+ * @return the source operand
+ */
+ public SqlExpression operand() {
+ return children().get(0);
}
+ /** {@inheritDoc} */
@Override
- public int hashCode() {
- return SessionUser.class.hashCode();
+ public boolean equals(Object other) {
+ return other instanceof Not && sameContents((Not) other);
}
@Override
- public String toString() {
- return "SessionUser{}";
+ List<?> attributes() {
+ return Collections.emptyList();
}
}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/RestrictedSqlExpressionParserFacade.java b/core/src/main/java/org/apache/gravitino/policy/sql/RestrictedSqlExpressionParserFacade.java
new file mode 100644
index 0000000000..5e490849b8
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/RestrictedSqlExpressionParserFacade.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.sql;
+
+import java.nio.charset.StandardCharsets;
+import org.apache.gravitino.policy.ReadRestrictionContent;
+
+/** Parses and validates typed definitions in the {@code restricted-sql-v1} source dialect. */
+public final class RestrictedSqlExpressionParserFacade {
+ private RestrictedSqlExpressionParserFacade() {}
+
+ /**
+ * Validates a complete SQL row-filter definition with a BOOLEAN result.
+ *
+ * @param source parameter declarations, RETURNS type, arrow and SQL body
+ * @throws IllegalArgumentException if syntax, types or resource limits are invalid
+ */
+ public static void validateRowFilter(String source) {
+ parse(source, false);
+ }
+
+ /**
+ * Validates a complete SQL mask definition with one parameter and the same result type.
+ *
+ * @param source parameter declaration, RETURNS type, arrow and SQL body
+ * @throws IllegalArgumentException if syntax, types or resource limits are invalid
+ */
+ public static void validateColumnMask(String source) {
+ parse(source, true);
+ }
+
+ /**
+ * Parses and validates a complete SQL row-filter definition.
+ *
+ * @param source complete typed SQL definition
+ * @return immutable unresolved row filter
+ * @throws IllegalArgumentException if syntax, semantics or resource limits are invalid
+ */
+ public static SqlDefinition parseRowFilter(String source) {
+ return parse(source, false);
+ }
+
+ /**
+ * Parses and validates a complete SQL column-mask definition.
+ *
+ * @param source complete typed SQL definition
+ * @return immutable unresolved column mask
+ * @throws IllegalArgumentException if syntax, semantics or resource limits are invalid
+ */
+ public static SqlDefinition parseColumnMask(String source) {
+ return parse(source, true);
+ }
+
+ static SqlDefinition parse(String source, boolean mask) {
+ if (source == null || source.trim().isEmpty()) {
+ throw new IllegalArgumentException("restricted-sql-v1 definition cannot be blank");
+ }
+ if (source.getBytes(StandardCharsets.UTF_8).length
+ > ReadRestrictionContent.MAX_SOURCE_LENGTH_BYTES) {
+ throw new IllegalArgumentException(
+ "restricted-sql-v1 source must not exceed 16384 UTF-8 bytes");
+ }
+ return RestrictedSqlSourceParser.parse(source, mask);
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestSessionUser.java b/core/src/main/java/org/apache/gravitino/policy/sql/RestrictedSqlLimits.java
similarity index 61%
rename from core/src/test/java/org/apache/gravitino/policy/rego/TestSessionUser.java
rename to core/src/main/java/org/apache/gravitino/policy/sql/RestrictedSqlLimits.java
index e352df7731..d51d3c21d5 100644
--- a/core/src/test/java/org/apache/gravitino/policy/rego/TestSessionUser.java
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/RestrictedSqlLimits.java
@@ -16,20 +16,17 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.policy.rego;
+package org.apache.gravitino.policy.sql;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.Test;
+/** Source resource limits shared by ANTLR token validation and AST construction. */
+final class RestrictedSqlLimits {
+ static final int MAX_DEPTH = 16;
+ static final int MAX_NODES = 1024;
+ static final int MAX_PARAMETERS = 256;
+ static final int MAX_STRING_BYTES = 4096;
+ static final int MAX_NUMBER_BYTES = 256;
+ static final int MAX_IN_ELEMENTS = 1000;
+ static final int MAX_PARENTHESES = 64;
-/** 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());
- }
+ private RestrictedSqlLimits() {}
}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/RestrictedSqlSourceParser.java b/core/src/main/java/org/apache/gravitino/policy/sql/RestrictedSqlSourceParser.java
new file mode 100644
index 0000000000..616c8319a1
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/RestrictedSqlSourceParser.java
@@ -0,0 +1,173 @@
+/*
+ * 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.sql;
+
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.antlr.v4.runtime.BaseErrorListener;
+import org.antlr.v4.runtime.CharStreams;
+import org.antlr.v4.runtime.CommonTokenStream;
+import org.antlr.v4.runtime.ParserRuleContext;
+import org.antlr.v4.runtime.RecognitionException;
+import org.antlr.v4.runtime.Recognizer;
+import org.antlr.v4.runtime.Token;
+import org.antlr.v4.runtime.tree.ErrorNode;
+import org.antlr.v4.runtime.tree.ParseTreeListener;
+import org.antlr.v4.runtime.tree.TerminalNode;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlLexer;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser;
+
+/** Runs the generated ANTLR parser with fail-fast diagnostics and bounded recursive work. */
+final class RestrictedSqlSourceParser {
+ private RestrictedSqlSourceParser() {}
+
+ static SqlDefinition parse(String source, boolean mask) {
+ validateUnicode(source);
+ RestrictedSqlLexer lexer = new RestrictedSqlLexer(CharStreams.fromString(source));
+ lexer.removeErrorListeners();
+ lexer.addErrorListener(new SyntaxErrors());
+ CommonTokenStream tokens = new CommonTokenStream(lexer);
+ tokens.fill();
+ validateTokens(tokens.getTokens(), source);
+ RestrictedSqlParser parser = new RestrictedSqlParser(tokens);
+ parser.removeErrorListeners();
+ parser.addErrorListener(new SyntaxErrors());
+ parser.addParseListener(new RecursionLimit());
+ return new SqlAstBuilder().build(parser.definition(), mask);
+ }
+
+ static IllegalArgumentException error(Token token, String message) {
+ return new IllegalArgumentException(
+ "Invalid restricted-sql-v1 definition at line "
+ + token.getLine()
+ + ", column "
+ + (token.getCharPositionInLine() + 1)
+ + ": "
+ + message);
+ }
+
+ private static void validateUnicode(String source) {
+ for (int i = 0; i < source.length(); i++) {
+ char c = source.charAt(i);
+ if (Character.isHighSurrogate(c)) {
+ if (++i >= source.length() || !Character.isLowSurrogate(source.charAt(i))) {
+ throw new IllegalArgumentException(
+ "Invalid restricted-sql-v1 source: isolated surrogate");
+ }
+ } else if (Character.isLowSurrogate(c) || c == 0) {
+ throw new IllegalArgumentException(
+ "Invalid restricted-sql-v1 source: invalid Unicode character");
+ }
+ }
+ }
+
+ private static void validateTokens(List<Token> tokens, String source) {
+ int parentheses = 0;
+ for (Token token : tokens) {
+ if (token.getType() == RestrictedSqlLexer.LPAREN
+ && ++parentheses > RestrictedSqlLimits.MAX_PARENTHESES) {
+ throw error(
+ token, "parenthesis nesting must not exceed " + RestrictedSqlLimits.MAX_PARENTHESES);
+ }
+ if (token.getType() == RestrictedSqlLexer.RPAREN) {
+ parentheses--;
+ }
+ if (token.getType() == RestrictedSqlLexer.NUMBER) {
+ if (token.getText().length() > RestrictedSqlLimits.MAX_NUMBER_BYTES) {
+ throw error(
+ token, "numeric literal exceeds " + RestrictedSqlLimits.MAX_NUMBER_BYTES + " bytes");
+ }
+ int next = token.getStopIndex() + 1;
+ // ANTLR offsets count code points. Numeric tokens contain only ASCII, but their prefix may
+ // not.
+ int sourceIndex = source.offsetByCodePoints(0, next);
+ if (sourceIndex < source.length()
+ && (Character.isLetterOrDigit(source.charAt(sourceIndex))
+ || source.charAt(sourceIndex) == '_')) {
+ throw error(token, "numeric literal must end at a token boundary");
+ }
+ }
+ if (token.getType() == RestrictedSqlLexer.STRING
+ || token.getType() == RestrictedSqlLexer.QUOTED_IDENTIFIER) {
+ String quote = token.getType() == RestrictedSqlLexer.STRING ? "'" : "\"";
+ String decoded =
+ token
+ .getText()
+ .substring(1, token.getText().length() - 1)
+ .replace(quote + quote, quote);
+ if (decoded.getBytes(StandardCharsets.UTF_8).length
+ > RestrictedSqlLimits.MAX_STRING_BYTES) {
+ throw error(
+ token,
+ "quoted token exceeds " + RestrictedSqlLimits.MAX_STRING_BYTES + " UTF-8 bytes");
+ }
+ }
+ }
+ }
+
+ private static final class SyntaxErrors extends BaseErrorListener {
+ /** {@inheritDoc} */
+ @Override
+ public void syntaxError(
+ Recognizer<?, ?> recognizer,
+ Object offendingSymbol,
+ int line,
+ int column,
+ String message,
+ RecognitionException exception) {
+ throw new IllegalArgumentException(
+ "Invalid restricted-sql-v1 definition at line "
+ + line
+ + ", column "
+ + (column + 1)
+ + ": "
+ + message);
+ }
+ }
+
+ private static final class RecursionLimit implements ParseTreeListener {
+ private int operations;
+ /** {@inheritDoc} */
+ @Override
+ public void enterEveryRule(ParserRuleContext context) {
+ if (recursive(context) && ++operations > RestrictedSqlLimits.MAX_DEPTH) {
+ throw error(
+ context.getStart(), "operation depth must not exceed " + RestrictedSqlLimits.MAX_DEPTH);
+ }
+ }
+ /** {@inheritDoc} */
+ @Override
+ public void exitEveryRule(ParserRuleContext context) {
+ if (recursive(context)) {
+ operations--;
+ }
+ }
+ /** {@inheritDoc} */
+ @Override
+ public void visitTerminal(TerminalNode node) {}
+ /** {@inheritDoc} */
+ @Override
+ public void visitErrorNode(ErrorNode node) {}
+
+ private static boolean recursive(ParserRuleContext context) {
+ return context.getRuleIndex() == RestrictedSqlParser.RULE_caseExpression
+ || context.getRuleIndex() == RestrictedSqlParser.RULE_functionCall;
+ }
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/SqlAstBuilder.java b/core/src/main/java/org/apache/gravitino/policy/sql/SqlAstBuilder.java
new file mode 100644
index 0000000000..e7ea1b1031
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/SqlAstBuilder.java
@@ -0,0 +1,362 @@
+/*
+ * 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.sql;
+
+import java.util.ArrayList;
+import java.util.IdentityHashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import org.antlr.v4.runtime.ParserRuleContext;
+import org.antlr.v4.runtime.Token;
+import org.antlr.v4.runtime.tree.ParseTree;
+import org.apache.gravitino.policy.sql.SqlTypeValidator.InvalidExpressionException;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlBaseVisitor;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser.AndExpressionContext;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser.CaseExpressionContext;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser.DataTypeContext;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser.DefinitionContext;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser.ExpressionContext;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser.FunctionCallContext;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser.IdentifierContext;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser.LiteralContext;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser.NotExpressionContext;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser.OrExpressionContext;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser.ParameterContext;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser.PredicateContext;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser.ScalarContext;
+import org.apache.gravitino.policy.sql.antlr.RestrictedSqlParser.WhenClauseContext;
+
+/** Converts an ANTLR parse tree into operation-specific immutable SQL nodes. */
+final class SqlAstBuilder extends RestrictedSqlBaseVisitor<SqlExpression> {
+ private final Map<String, SqlType> parameters = new LinkedHashMap<>();
+ private final Set<String> quotedParameters = new LinkedHashSet<>();
+ private final IdentityHashMap<SqlExpression, Token> sourceTokens = new IdentityHashMap<>();
+ private int nodes;
+ private int listElements;
+ private int activeOperations;
+
+ SqlDefinition build(DefinitionContext context, boolean mask) {
+ for (ParameterContext parameter : context.parameter()) {
+ String name = identifier(parameter.identifier());
+ SqlType type = type(parameter.dataType());
+ if (parameter.identifier().QUOTED_IDENTIFIER() != null) {
+ quotedParameters.add(name);
+ }
+ require(parameters.putIfAbsent(name, type) == null, parameter, "duplicate parameter " + name);
+ require(
+ parameters.size() <= RestrictedSqlLimits.MAX_PARAMETERS,
+ parameter,
+ "too many parameters");
+ }
+ SqlType result = type(context.dataType());
+ if (mask) {
+ require(parameters.size() == 1, context, "column mask requires exactly one parameter");
+ require(
+ result.equals(parameters.values().iterator().next()),
+ context,
+ "mask parameter and result types must match");
+ } else {
+ require(result.equals(SqlType.BOOLEAN), context, "row filter must return BOOLEAN");
+ }
+ SqlExpression body = visit(context.expression());
+ try {
+ new SqlTypeValidator().validate(body, result);
+ } catch (InvalidExpressionException e) {
+ throw RestrictedSqlSourceParser.error(sourceTokens.get(e.expression()), e.getMessage());
+ }
+ return new SqlDefinition(parameters, result, body, quotedParameters, mask);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public SqlExpression visit(ParseTree tree) {
+ // Grammar precedence and parentheses add parse-tree layers, but no AST operations.
+ // Unwrap them iteratively so legal nested parentheses do not consume the visitor stack.
+ ParseTree current = tree;
+ while (true) {
+ if (current instanceof ExpressionContext) {
+ current = ((ExpressionContext) current).orExpression();
+ } else if (current instanceof OrExpressionContext
+ && ((OrExpressionContext) current).andExpression().size() == 1) {
+ current = ((OrExpressionContext) current).andExpression(0);
+ } else if (current instanceof AndExpressionContext
+ && ((AndExpressionContext) current).notExpression().size() == 1) {
+ current = ((AndExpressionContext) current).notExpression(0);
+ } else if (current instanceof NotExpressionContext
+ && ((NotExpressionContext) current).NOT().isEmpty()) {
+ current = ((NotExpressionContext) current).predicate();
+ } else if (current instanceof PredicateContext && current.getChildCount() == 1) {
+ current = ((PredicateContext) current).scalar(0);
+ } else if (current instanceof ScalarContext
+ && ((ScalarContext) current).expression() != null) {
+ current = ((ScalarContext) current).expression();
+ } else {
+ break;
+ }
+ }
+ boolean operation =
+ current instanceof OrExpressionContext
+ || current instanceof AndExpressionContext
+ || current instanceof NotExpressionContext
+ || current instanceof PredicateContext
+ || current instanceof FunctionCallContext
+ || current instanceof CaseExpressionContext;
+ if (!operation) {
+ return super.visit(current);
+ }
+ require(
+ ++activeOperations <= RestrictedSqlLimits.MAX_DEPTH,
+ (ParserRuleContext) current,
+ "operation depth must not exceed " + RestrictedSqlLimits.MAX_DEPTH);
+ try {
+ return super.visit(current);
+ } finally {
+ activeOperations--;
+ }
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public SqlExpression visitExpression(ExpressionContext context) {
+ return visit(context.orExpression());
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public SqlExpression visitOrExpression(OrExpressionContext context) {
+ List<SqlExpression> children = new ArrayList<>();
+ context.andExpression().forEach(child -> children.add(visit(child)));
+ return children.size() == 1
+ ? children.get(0)
+ : node(new LogicalExpression(LogicalOperator.OR, children), context);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public SqlExpression visitAndExpression(AndExpressionContext context) {
+ List<SqlExpression> children = new ArrayList<>();
+ context.notExpression().forEach(child -> children.add(visit(child)));
+ return children.size() == 1
+ ? children.get(0)
+ : node(new LogicalExpression(LogicalOperator.AND, children), context);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public SqlExpression visitNotExpression(NotExpressionContext context) {
+ require(
+ context.NOT().size() <= RestrictedSqlLimits.MAX_DEPTH,
+ context,
+ "operation depth must not exceed " + RestrictedSqlLimits.MAX_DEPTH);
+ SqlExpression result = visit(context.predicate());
+ for (int i = 0; i < context.NOT().size(); i++) {
+ result = node(new Not(result), context);
+ }
+ return result;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public SqlExpression visitPredicate(PredicateContext context) {
+ SqlExpression left = visit(context.scalar(0));
+ if (context.comparisonOperator() != null) {
+ return node(
+ new Comparison(
+ ComparisonOperator.fromToken(context.comparisonOperator().getText()),
+ left,
+ visit(context.scalar(1))),
+ context);
+ }
+ if (context.IS() != null) {
+ return node(new IsNull(left, context.NOT() != null), context);
+ }
+ SqlExpression result;
+ if (context.IN() != null) {
+ List<Literal> values = new ArrayList<>();
+ for (LiteralContext literal : context.literal()) {
+ require(
+ ++listElements <= RestrictedSqlLimits.MAX_IN_ELEMENTS,
+ context,
+ "IN lists must not exceed " + RestrictedSqlLimits.MAX_IN_ELEMENTS + " total elements");
+ values.add((Literal) visit(literal));
+ }
+ result = node(new In(left, values), context);
+ } else if (context.BETWEEN() != null) {
+ result = node(new Between(left, visit(context.scalar(1)), visit(context.scalar(2))), context);
+ } else if (context.LIKE() != null) {
+ String pattern = quoted(context.STRING().getText());
+ require(
+ pattern.length() > 1
+ && pattern.endsWith("%")
+ && pattern.indexOf('%') == pattern.length() - 1
+ && pattern.indexOf('_') < 0,
+ context,
+ "LIKE requires a non-empty fixed prefix followed by one %");
+ Literal literal = node(new Literal(LiteralType.STRING, pattern, SqlType.STRING), context);
+ result = node(new Like(left, literal), context);
+ } else {
+ return left;
+ }
+ return context.NOT() == null ? result : node(new Not(result), context);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public SqlExpression visitScalar(ScalarContext context) {
+ if (context.identifier() != null) {
+ String name = identifier(context.identifier());
+ require(parameters.containsKey(name), context, "undeclared parameter " + name);
+ return node(new InputReference(name, parameters.get(name)), context);
+ }
+ if (context.literal() != null) {
+ return visit(context.literal());
+ }
+ if (context.functionCall() != null) {
+ return visit(context.functionCall());
+ }
+ if (context.caseExpression() != null) {
+ return visit(context.caseExpression());
+ }
+ return visit(context.expression());
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public SqlExpression visitFunctionCall(FunctionCallContext context) {
+ require(
+ context.identifier().QUOTED_IDENTIFIER() == null,
+ context,
+ "quoted function names are unsupported");
+ SqlFunction function;
+ try {
+ function = SqlFunction.fromName(context.identifier().getText());
+ } catch (IllegalArgumentException e) {
+ throw RestrictedSqlSourceParser.error(context.getStart(), e.getMessage());
+ }
+ List<SqlExpression> arguments = new ArrayList<>();
+ context.expression().forEach(argument -> arguments.add(visit(argument)));
+ return node(new FunctionCall(function, arguments), context);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public SqlExpression visitCaseExpression(CaseExpressionContext context) {
+ SqlExpression selector =
+ context.getChild(1) instanceof ExpressionContext ? visit(context.expression(0)) : null;
+ List<CaseBranch> branches = new ArrayList<>();
+ for (WhenClauseContext branch : context.whenClause()) {
+ branches.add(new CaseBranch(visit(branch.expression(0)), visit(branch.expression(1))));
+ }
+ SqlExpression fallback =
+ context.ELSE() == null ? null : visit(context.expression(context.expression().size() - 1));
+ return node(new CaseExpression(selector, branches, fallback), context);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public SqlExpression visitLiteral(LiteralContext context) {
+ if (context.NUMBER() != null) {
+ return node(new Literal(LiteralType.NUMBER, context.getText(), null), context);
+ }
+ if (context.NULL() != null) {
+ return node(new Literal(LiteralType.NULL, "", null), context);
+ }
+ if (context.TRUE() != null || context.FALSE() != null) {
+ return node(
+ new Literal(
+ LiteralType.BOOLEAN, context.getText().toUpperCase(Locale.ROOT), SqlType.BOOLEAN),
+ context);
+ }
+ String value = quoted(context.STRING().getText());
+ if (context.getStart().getType() == RestrictedSqlParser.STRING) {
+ return node(new Literal(LiteralType.STRING, value, SqlType.STRING), context);
+ }
+ String name = context.getStart().getText().toUpperCase(Locale.ROOT);
+ return node(
+ new Literal(
+ LiteralType.TEMPORAL,
+ value,
+ new SqlType(name, name.equals("DATE") ? 0 : 6, 0, context.WITH() != null)),
+ context);
+ }
+
+ private SqlType type(DataTypeContext context) {
+ String name = context.getStart().getText().toUpperCase(Locale.ROOT);
+ int precision = 0;
+ int scale = 0;
+ if (name.equals("DECIMAL")) {
+ precision = unsignedInteger(context.NUMBER(0).getText(), context);
+ scale = unsignedInteger(context.NUMBER(1).getText(), context);
+ require(
+ precision >= 1 && precision <= 38 && scale <= precision,
+ context,
+ "invalid decimal precision or scale");
+ } else if (name.equals("TIME") || name.equals("TIMESTAMP")) {
+ precision = 6;
+ require(
+ context.NUMBER().isEmpty() || unsignedInteger(context.NUMBER(0).getText(), context) == 6,
+ context,
+ "temporal precision must be 6");
+ }
+ return new SqlType(name, precision, scale, context.WITH() != null);
+ }
+
+ private static int unsignedInteger(String source, ParserRuleContext context) {
+ require(source.matches("[0-9]{1,2}"), context, "expected unsigned integer");
+ return Integer.parseInt(source);
+ }
+
+ private static String identifier(IdentifierContext context) {
+ String name =
+ context.QUOTED_IDENTIFIER() == null
+ ? context.getText().toUpperCase(Locale.ROOT)
+ : quoted(context.getText());
+ require(!name.isEmpty(), context, "identifier cannot be empty");
+ return name;
+ }
+
+ private static String quoted(String text) {
+ String quote = text.substring(0, 1);
+ return text.substring(1, text.length() - 1).replace(quote + quote, quote);
+ }
+
+ private <T extends SqlExpression> T node(T expression, ParserRuleContext context) {
+ sourceTokens.put(expression, context.getStart());
+ require(
+ ++nodes <= RestrictedSqlLimits.MAX_NODES,
+ context,
+ "expression must not exceed " + RestrictedSqlLimits.MAX_NODES + " nodes");
+ require(
+ expression.depth() <= RestrictedSqlLimits.MAX_DEPTH,
+ context,
+ "operation depth must not exceed " + RestrictedSqlLimits.MAX_DEPTH);
+ return expression;
+ }
+
+ private static void require(boolean valid, ParserRuleContext context, String message) {
+ if (!valid) {
+ throw RestrictedSqlSourceParser.error(context.getStart(), message);
+ }
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/SqlDefinition.java b/core/src/main/java/org/apache/gravitino/policy/sql/SqlDefinition.java
new file mode 100644
index 0000000000..bdc3a1621a
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/SqlDefinition.java
@@ -0,0 +1,109 @@
+/*
+ * 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.sql;
+
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.Map;
+import java.util.Set;
+
+/** A validated definition; parameter names are local and have no physical field IDs yet. */
+public final class SqlDefinition {
+ private final Map<String, SqlType> parameters;
+ private final SqlType resultType;
+ private final SqlExpression body;
+ private final Set<String> quotedParameters;
+ private final boolean columnMask;
+
+ SqlDefinition(
+ Map<String, SqlType> parameters,
+ SqlType resultType,
+ SqlExpression body,
+ Set<String> quotedParameters,
+ boolean columnMask) {
+ this.parameters = Collections.unmodifiableMap(new LinkedHashMap<>(parameters));
+ this.resultType = resultType;
+ this.body = body;
+ this.quotedParameters = Collections.unmodifiableSet(new LinkedHashSet<>(quotedParameters));
+ this.columnMask = columnMask;
+ }
+
+ /**
+ * Returns the immutable declared parameter types keyed by normalized local name.
+ *
+ * @return the immutable declared parameter types keyed by normalized local name
+ */
+ public Map<String, SqlType> parameters() {
+ return parameters;
+ }
+
+ /**
+ * Returns the declared result type.
+ *
+ * @return the declared result type
+ */
+ public SqlType resultType() {
+ return resultType;
+ }
+
+ /**
+ * Returns the validated unresolved expression body.
+ *
+ * @return the validated unresolved expression body
+ */
+ public SqlExpression body() {
+ return body;
+ }
+
+ /**
+ * Checks whether a parameter was declared with exact SQL quoting.
+ *
+ * @param name normalized local parameter name
+ * @return whether physical column matching must be case sensitive
+ */
+ public boolean isQuotedParameter(String name) {
+ return quotedParameters.contains(name);
+ }
+
+ /**
+ * Returns whether this definition targets a column mask.
+ *
+ * @return whether this definition was validated as a column mask
+ */
+ public boolean isColumnMask() {
+ return columnMask;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public String toString() {
+ return "SqlDefinition{parameters="
+ + parameters
+ + ", resultType="
+ + resultType
+ + ", body="
+ + body
+ + ", quotedParameters="
+ + quotedParameters
+ + ", columnMask="
+ + columnMask
+ + "}";
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/SqlExpression.java b/core/src/main/java/org/apache/gravitino/policy/sql/SqlExpression.java
new file mode 100644
index 0000000000..cf187482d4
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/SqlExpression.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.sql;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import javax.annotation.Nullable;
+
+/** Base for immutable, typed SQL AST nodes. Each operation has its own node class. */
+public abstract class SqlExpression {
+ private final List<SqlExpression> children;
+
+ SqlExpression(List<SqlExpression> children) {
+ this.children = Collections.unmodifiableList(new ArrayList<>(children));
+ this.children.forEach(Objects::requireNonNull);
+ }
+
+ /**
+ * Returns the immutable ordered source operands.
+ *
+ * @return the immutable ordered source operands
+ */
+ public List<SqlExpression> children() {
+ return children;
+ }
+
+ /**
+ * Returns the intrinsic logical type, or null when inferred from context.
+ *
+ * @return the intrinsic logical type, or null when inferred from context
+ */
+ @Nullable
+ public SqlType type() {
+ return null;
+ }
+
+ int depth() {
+ return 1 + children.stream().mapToInt(SqlExpression::depth).max().orElse(0);
+ }
+
+ abstract List<?> attributes();
+
+ boolean sameContents(SqlExpression other) {
+ return attributes().equals(other.attributes()) && children.equals(other.children());
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public final int hashCode() {
+ return Objects.hash(getClass(), attributes(), children);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public final String toString() {
+ return getClass().getSimpleName()
+ + "{attributes="
+ + attributes()
+ + ", children="
+ + children
+ + "}";
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/SqlFunction.java b/core/src/main/java/org/apache/gravitino/policy/sql/SqlFunction.java
new file mode 100644
index 0000000000..289bd75f47
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/SqlFunction.java
@@ -0,0 +1,63 @@
+/*
+ * 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.sql;
+
+import java.util.Locale;
+
+/** Allowlisted context, predicate, date-part and mask functions. */
+public enum SqlFunction {
+ /** Returns the trusted effective user's name. */
+ CURRENT_USER,
+ /** Tests the effective user's flat membership in a named group. */
+ IS_GROUP_MEMBER,
+ /** Tests whether a FLOAT or DOUBLE value is NaN. */
+ IS_NAN,
+ /** Extracts the calendar year from a DATE or TIMESTAMP. */
+ YEAR,
+ /** Extracts the month of the year from a DATE or TIMESTAMP. */
+ MONTH,
+ /** Extracts the day of the month from a DATE or TIMESTAMP. */
+ DAY,
+ /** Replaces string characters with the profile's digit and character masks. */
+ MASK_ALPHANUM,
+ /** Preserves the first four string code points and masks the remainder. */
+ SHOW_FIRST_4,
+ /** Preserves the last four string code points and masks the remainder. */
+ SHOW_LAST_4,
+ /** Replaces the input with the fixed mask value for its logical type. */
+ MASK_TO_FIXED_VALUE,
+ /** Replaces the input with a NULL of the same logical type. */
+ REPLACE_WITH_NULL,
+ /** Truncates a DATE or TIMESTAMP to the start of its year. */
+ TRUNCATE_TO_YEAR,
+ /** Truncates a DATE or TIMESTAMP to the start of its month. */
+ TRUNCATE_TO_MONTH,
+ /** Applies the type-preserving SHA-256 mask. */
+ SHA256_GLOBAL,
+ /** Applies the type-preserving SHA-256 mask with a salt shared within one query. */
+ SHA256_QUERY_LOCAL;
+
+ static SqlFunction fromName(String name) {
+ try {
+ return valueOf(name.toUpperCase(Locale.ROOT));
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException("Unknown restricted-sql-v1 function: " + name, e);
+ }
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/SqlType.java b/core/src/main/java/org/apache/gravitino/policy/sql/SqlType.java
new file mode 100644
index 0000000000..d405c840ce
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/SqlType.java
@@ -0,0 +1,143 @@
+/*
+ * 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.sql;
+
+import java.util.Objects;
+
+/** Exact logical types in the restricted SQL profile, independent of a target schema. */
+public final class SqlType {
+ /** SQL Boolean type. */
+ public static final SqlType BOOLEAN = new SqlType("BOOLEAN");
+ /** SQL string type. */
+ public static final SqlType STRING = new SqlType("STRING");
+ /** SQL signed integer type. */
+ public static final SqlType INTEGER = new SqlType("INTEGER");
+ // Exact, as yet unbound numeric constants (not a supported declaration type).
+ static final SqlType NUMBER = new SqlType("NUMBER");
+
+ final String name;
+ final int precision;
+ final int scale;
+ final boolean withTimeZone;
+
+ /**
+ * Creates a scalar type without precision or timezone attributes.
+ *
+ * @param name canonical SQL type name
+ */
+ public SqlType(String name) {
+ this(name, 0, 0, false);
+ }
+
+ /**
+ * Creates an exact logical type descriptor.
+ *
+ * @param name canonical SQL type name
+ * @param precision decimal precision or temporal fractional precision
+ * @param scale decimal scale
+ * @param withTimeZone whether a timestamp has a timezone
+ */
+ public SqlType(String name, int precision, int scale, boolean withTimeZone) {
+ this.name = name;
+ this.precision = precision;
+ this.scale = scale;
+ this.withTimeZone = withTimeZone;
+ }
+
+ /**
+ * Returns the canonical SQL type name.
+ *
+ * @return canonical SQL type name
+ */
+ public String name() {
+ return name;
+ }
+
+ /**
+ * Returns decimal or temporal precision.
+ *
+ * @return declared precision, or zero when unset
+ */
+ public int precision() {
+ return precision;
+ }
+
+ /**
+ * Returns decimal scale.
+ *
+ * @return decimal scale
+ */
+ public int scale() {
+ return scale;
+ }
+
+ /**
+ * Returns whether the timestamp carries a timezone.
+ *
+ * @return whether this timestamp has a timezone
+ */
+ public boolean withTimeZone() {
+ return withTimeZone;
+ }
+
+ /**
+ * Returns whether this is a numeric type.
+ *
+ * @return whether this is a numeric type
+ */
+ public boolean numeric() {
+ return name.matches("INTEGER|LONG|FLOAT|DOUBLE|DECIMAL|NUMBER");
+ }
+
+ /**
+ * Returns whether this is a date or timestamp type.
+ *
+ * @return whether this is a date or timestamp type
+ */
+ public boolean temporal() {
+ return name.equals("DATE") || name.equals("TIMESTAMP");
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof SqlType)) {
+ return false;
+ }
+ SqlType that = (SqlType) other;
+ return name.equals(that.name)
+ && precision == that.precision
+ && scale == that.scale
+ && withTimeZone == that.withTimeZone;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, precision, scale, withTimeZone);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public String toString() {
+ return name.equals("DECIMAL")
+ ? name + "(" + precision + "," + scale + ")"
+ : name + (withTimeZone ? " WITH TIME ZONE" : "");
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/policy/sql/SqlTypeValidator.java b/core/src/main/java/org/apache/gravitino/policy/sql/SqlTypeValidator.java
new file mode 100644
index 0000000000..e233775c62
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/policy/sql/SqlTypeValidator.java
@@ -0,0 +1,302 @@
+/*
+ * 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.sql;
+
+import java.math.BigDecimal;
+import java.time.DateTimeException;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.OffsetDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import javax.annotation.Nullable;
+
+/** Checks every source branch without evaluating request context or lowering SQL null semantics. */
+final class SqlTypeValidator {
+ void validate(SqlExpression node, @Nullable SqlType expected) {
+ try {
+ validateNode(node, expected);
+ } catch (InvalidExpressionException e) {
+ throw e;
+ } catch (IllegalArgumentException e) {
+ throw new InvalidExpressionException(node, e);
+ }
+ }
+
+ private void validateNode(SqlExpression node, @Nullable SqlType expected) {
+ SqlType actual = naturalType(node);
+ require(
+ expected == null
+ || actual == null
+ || actual.equals(SqlType.NUMBER) && expected.numeric()
+ || expected.equals(actual),
+ "expected " + expected + ", found " + actual);
+ SqlType hint = expected == null ? actual : expected;
+ if (node instanceof Literal) {
+ Literal literal = (Literal) node;
+ if (literal.literalType() == LiteralType.NUMBER) {
+ validateNumber(literal.value(), hint);
+ }
+ if (literal.literalType() == LiteralType.TEMPORAL) {
+ validateTemporal(literal);
+ }
+ } else if (node instanceof InputReference) {
+ return;
+ } else if (node instanceof LogicalExpression || node instanceof Not) {
+ node.children().forEach(arg -> validate(arg, SqlType.BOOLEAN));
+ } else if (node instanceof IsNull) {
+ validate(((IsNull) node).operand(), null);
+ } else if (node instanceof Like) {
+ node.children().forEach(arg -> validate(arg, SqlType.STRING));
+ } else if (node instanceof CaseExpression) {
+ validateCase((CaseExpression) node, hint);
+ } else if (node instanceof FunctionCall) {
+ validateCall((FunctionCall) node, hint);
+ } else if (node instanceof Comparison) {
+ validateCompatible(node.children(), ((Comparison) node).operator().ordered());
+ } else if (node instanceof In || node instanceof Between) {
+ validateCompatible(node.children(), node instanceof Between);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported SQL AST node: " + node.getClass().getSimpleName());
+ }
+ }
+
+ @Nullable
+ private SqlType naturalType(SqlExpression node) {
+ if (node.type() != null) {
+ return node.type();
+ }
+ if (node instanceof Literal) {
+ return ((Literal) node).literalType() == LiteralType.NUMBER ? SqlType.NUMBER : null;
+ }
+ if (node instanceof FunctionCall) {
+ FunctionCall call = (FunctionCall) node;
+ switch (call.function()) {
+ case CURRENT_USER:
+ return SqlType.STRING;
+ case IS_GROUP_MEMBER:
+ case IS_NAN:
+ return SqlType.BOOLEAN;
+ case YEAR:
+ case MONTH:
+ case DAY:
+ return SqlType.INTEGER;
+ default:
+ return call.arguments().size() == 1 ? naturalType(call.arguments().get(0)) : null;
+ }
+ }
+ if (node instanceof CaseExpression) {
+ return commonType(((CaseExpression) node).results());
+ }
+ return SqlType.BOOLEAN;
+ }
+
+ private void validateCase(CaseExpression expression, @Nullable SqlType hint) {
+ List<SqlExpression> matches = new ArrayList<>();
+ if (expression.selector() != null) {
+ matches.add(expression.selector());
+ }
+ for (CaseBranch branch : expression.branches()) {
+ if (expression.selector() == null) {
+ validate(branch.condition(), SqlType.BOOLEAN);
+ } else {
+ matches.add(branch.condition());
+ }
+ validate(branch.result(), hint);
+ }
+ if (expression.selector() != null) {
+ validateCompatible(matches, false);
+ }
+ if (expression.fallback() != null) {
+ validate(expression.fallback(), hint);
+ }
+ }
+
+ @Nullable
+ private SqlType commonType(List<SqlExpression> nodes) {
+ SqlType result = null;
+ for (SqlExpression node : nodes) {
+ SqlType candidate = naturalType(node);
+ if (candidate != null && (result == null || result.equals(SqlType.NUMBER))) {
+ result = candidate;
+ }
+ }
+ return result;
+ }
+
+ private void validateCompatible(List<SqlExpression> args, boolean ordered) {
+ SqlType type = commonType(args);
+ require(type == null || !type.name.equals("BINARY"), "BINARY value predicates are unsupported");
+ require(
+ !ordered || type == null || !type.equals(SqlType.BOOLEAN),
+ "BOOLEAN ordering is unsupported");
+ args.forEach(arg -> validate(arg, type));
+ }
+
+ private void validateCall(FunctionCall node, @Nullable SqlType hint) {
+ List<SqlExpression> args = node.arguments();
+ if (node.function() == SqlFunction.CURRENT_USER) {
+ require(args.isEmpty(), "CURRENT_USER requires no arguments");
+ return;
+ }
+ require(args.size() == 1, node.function() + " requires exactly one argument");
+ SqlExpression arg = args.get(0);
+ SqlType type = naturalType(arg);
+ switch (node.function()) {
+ case IS_GROUP_MEMBER:
+ require(
+ arg instanceof Literal
+ && ((Literal) arg).literalType() == LiteralType.STRING
+ && !((Literal) arg).value().isEmpty(),
+ "context key must be a non-empty string literal");
+ return;
+ case IS_NAN:
+ require(
+ type != null && type.name.matches("FLOAT|DOUBLE"), "IS_NAN requires FLOAT or DOUBLE");
+ validate(arg, type);
+ return;
+ case YEAR:
+ case MONTH:
+ case DAY:
+ require(type != null && type.temporal(), node.function() + " requires DATE or TIMESTAMP");
+ validate(arg, type);
+ return;
+ case MASK_ALPHANUM:
+ case SHOW_FIRST_4:
+ case SHOW_LAST_4:
+ require(hint == null || hint.equals(SqlType.STRING), "string mask requires STRING result");
+ validate(arg, SqlType.STRING);
+ return;
+ case TRUNCATE_TO_YEAR:
+ case TRUNCATE_TO_MONTH:
+ type = hint == null ? type : hint;
+ require(type != null && type.temporal(), "truncation requires DATE or TIMESTAMP");
+ break;
+ case SHA256_GLOBAL:
+ case SHA256_QUERY_LOCAL:
+ type = hint == null ? type : hint;
+ require(
+ type != null && type.name.matches("STRING|INTEGER|LONG|BINARY"),
+ "unsupported hash input type");
+ break;
+ case MASK_TO_FIXED_VALUE:
+ type = hint == null ? type : hint;
+ require(
+ type != null
+ && type.name.matches(
+ "STRING|INTEGER|LONG|FLOAT|DOUBLE|DECIMAL|BOOLEAN|DATE|TIMESTAMP"),
+ "unsupported fixed-value input type");
+ break;
+ case REPLACE_WITH_NULL:
+ type = hint == null ? type : hint;
+ require(type != null, "replace_with_null requires a typed scalar");
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Unknown restricted-sql-v1 function: " + node.function());
+ }
+ validate(arg, type);
+ }
+
+ private static void validateNumber(String source, @Nullable SqlType type) {
+ BigDecimal value = new BigDecimal(source);
+ if (type == null || type.equals(SqlType.NUMBER)) {
+ return;
+ }
+ require(type.numeric(), "numeric literal requires a numeric type");
+ try {
+ switch (type.name) {
+ case "INTEGER":
+ value.intValueExact();
+ break;
+ case "LONG":
+ value.longValueExact();
+ break;
+ case "DECIMAL":
+ BigDecimal scaled = value.setScale(type.scale);
+ require(scaled.precision() <= type.precision, "decimal precision overflow");
+ break;
+ case "FLOAT":
+ require(Float.isFinite(Float.parseFloat(source)), "floating point overflow");
+ break;
+ case "DOUBLE":
+ require(Double.isFinite(Double.parseDouble(source)), "floating point overflow");
+ break;
+ default:
+ break;
+ }
+ } catch (ArithmeticException e) {
+ throw new IllegalArgumentException("Numeric literal does not fit " + type, e);
+ }
+ }
+
+ private static void validateTemporal(Literal node) {
+ String value = node.value();
+ SqlType type = node.type();
+ require(type != null, "temporal literal requires a type");
+ try {
+ if (type.name.equals("DATE")) {
+ require(value.matches("[0-9]{4}-[0-9]{2}-[0-9]{2}"), "invalid DATE literal");
+ LocalDate.parse(value);
+ } else {
+ String clock = "[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]{1,6})?";
+ if (type.name.equals("TIME")) {
+ require(value.matches(clock), "invalid TIME literal or precision");
+ LocalTime.parse(value);
+ } else {
+ require(
+ value.matches(
+ "[0-9]{4}-[0-9]{2}-[0-9]{2} "
+ + clock
+ + (type.withTimeZone ? "(Z|[+-][0-9]{2}:[0-9]{2})" : "")),
+ "invalid TIMESTAMP literal, precision or offset");
+ if (type.withTimeZone) {
+ OffsetDateTime.parse(value.replace(' ', 'T'));
+ } else {
+ LocalDateTime.parse(value.replace(' ', 'T'));
+ }
+ }
+ }
+ } catch (DateTimeException e) {
+ throw new IllegalArgumentException("Invalid temporal literal for " + type, e);
+ }
+ }
+
+ private static void require(boolean valid, String message) {
+ if (!valid) {
+ throw new IllegalArgumentException("Invalid restricted-sql-v1 expression: " + message);
+ }
+ }
+
+ /** Retains the innermost failing node without expanding literal payloads in diagnostics. */
+ static final class InvalidExpressionException extends IllegalArgumentException {
+ private final SqlExpression expression;
+
+ private InvalidExpressionException(SqlExpression expression, IllegalArgumentException cause) {
+ super(cause.getMessage(), cause);
+ this.expression = expression;
+ }
+
+ SqlExpression expression() {
+ return expression;
+ }
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/meta/TestPolicyEntity.java b/core/src/test/java/org/apache/gravitino/meta/TestPolicyEntity.java
index 2be5f4517b..8e5c4de482 100644
--- a/core/src/test/java/org/apache/gravitino/meta/TestPolicyEntity.java
+++ b/core/src/test/java/org/apache/gravitino/meta/TestPolicyEntity.java
@@ -158,8 +158,8 @@ public class TestPolicyEntity {
@Test
public void testReadRestrictionPolicyContentTypes() {
- PolicyContent rowFilter = PolicyContents.rowFilter("filter := true");
- PolicyContent columnMask = PolicyContents.columnMask("mask := action(\"replace-with-null\")");
+ PolicyContent rowFilter = PolicyContents.rowFilter("() RETURNS BOOLEAN -> TRUE");
+ PolicyContent columnMask = PolicyContents.columnMask("(value STRING) RETURNS STRING -> NULL");
Assertions.assertDoesNotThrow(
() -> readRestrictionPolicy(Policy.BuiltInType.ROW_FILTER, rowFilter));
diff --git a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
index cf74141a2b..45cbaf2b9c 100644
--- a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
+++ b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
@@ -511,7 +511,8 @@ public class TestPolicyManager {
@Test
public void testCreateUpdateAndGetRowFilterPolicy() {
String policyName = "row_filter_" + UUID.randomUUID().toString().replace("-", "");
- PolicyContent originalContent = PolicyContents.rowFilter("filter := col(\"region\") == \"US\"");
+ PolicyContent originalContent =
+ PolicyContents.rowFilter("(region STRING) RETURNS BOOLEAN -> region = 'US'");
PolicyEntity created =
policyManager.createPolicy(
@@ -523,7 +524,8 @@ public class TestPolicyManager {
Assertions.assertEquals(
originalContent, policyManager.getPolicy(METALAKE, policyName).content());
- PolicyContent updatedContent = PolicyContents.rowFilter("filter := col(\"region\") == \"EU\"");
+ PolicyContent updatedContent =
+ PolicyContents.rowFilter("(region STRING) RETURNS BOOLEAN -> region = 'EU'");
PolicyEntity updated =
policyManager.alterPolicy(
METALAKE, policyName, PolicyChange.updateContent("system_row_filter", updatedContent));
@@ -541,7 +543,7 @@ public class TestPolicyManager {
Policy.BuiltInType.ROW_FILTER,
null,
true,
- PolicyContents.rowFilter("filter := col(\"region\")")));
+ PolicyContents.rowFilter("(region STRING) RETURNS BOOLEAN -> region")));
Assertions.assertThrows(
IllegalArgumentException.class,
() ->
@@ -550,27 +552,29 @@ public class TestPolicyManager {
policyName,
PolicyChange.updateContent(
"system_row_filter",
- PolicyContents.rowFilter("mask := action(\"replace-with-null\")"))));
+ PolicyContents.rowFilter(
+ "(value STRING) RETURNS STRING -> replace_with_null(value)"))));
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 =
+ String policyName = "stored_row_filter_" + UUID.randomUUID().toString().replace("-", "");
+ PolicyContent storedContent =
+ PolicyContents.rowFilter("() RETURNS BOOLEAN -> unsupported_function()");
+ PolicyEntity storedPolicy =
PolicyEntity.builder()
.withId(new RandomIdGenerator().nextId())
.withName(policyName)
.withNamespace(NamespaceUtil.ofPolicy(METALAKE))
.withPolicyType(Policy.BuiltInType.ROW_FILTER)
.withEnabled(true)
- .withContent(legacyContent)
+ .withContent(storedContent)
.withAuditInfo(
AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())
.build();
- entityStore.put(legacyPolicy, false /* overwritten */);
+ entityStore.put(storedPolicy, false /* overwritten */);
String newName = "renamed_" + policyName;
PolicyEntity renamed =
@@ -580,12 +584,12 @@ public class TestPolicyManager {
Assertions.assertDoesNotThrow(
() ->
policyManager.alterPolicy(
- METALAKE, newName, PolicyChange.updateComment("legacy policy")));
+ METALAKE, newName, PolicyChange.updateComment("stored policy")));
Assertions.assertEquals(newName, commented.name());
- Assertions.assertEquals("legacy policy", commented.comment());
- Assertions.assertEquals(legacyContent, renamed.content());
- Assertions.assertEquals(legacyContent, commented.content());
+ Assertions.assertEquals("stored policy", commented.comment());
+ Assertions.assertEquals(storedContent, renamed.content());
+ Assertions.assertEquals(storedContent, commented.content());
}
@Test
@@ -629,7 +633,8 @@ public class TestPolicyManager {
@Test
public void testCreateUpdateAndGetColumnMaskPolicy() {
String policyName = "column_mask_" + UUID.randomUUID().toString().replace("-", "");
- PolicyContent originalContent = PolicyContents.columnMask("mask := action(\"show-last-4\")");
+ PolicyContent originalContent =
+ PolicyContents.columnMask("(value STRING) RETURNS STRING -> show_last_4(value)");
PolicyEntity created =
policyManager.createPolicy(
@@ -640,7 +645,7 @@ public class TestPolicyManager {
originalContent, policyManager.getPolicy(METALAKE, policyName).content());
PolicyContent updatedContent =
- PolicyContents.columnMask("mask := action(\"replace-with-null\")");
+ PolicyContents.columnMask("(value STRING) RETURNS STRING -> replace_with_null(value)");
PolicyEntity updated =
policyManager.alterPolicy(
METALAKE, policyName, PolicyChange.updateContent("system_column_mask", updatedContent));
@@ -658,7 +663,7 @@ public class TestPolicyManager {
Policy.BuiltInType.COLUMN_MASK,
null,
true,
- PolicyContents.columnMask("mask := action(\"unknown\")")));
+ PolicyContents.columnMask("(value STRING) RETURNS STRING -> unknown(value)")));
Assertions.assertThrows(
IllegalArgumentException.class,
() ->
@@ -666,7 +671,8 @@ public class TestPolicyManager {
METALAKE,
policyName,
PolicyChange.updateContent(
- "system_column_mask", PolicyContents.columnMask("filter := true"))));
+ "system_column_mask",
+ PolicyContents.columnMask("() RETURNS BOOLEAN -> TRUE"))));
Assertions.assertEquals(
updatedContent, policyManager.getPolicy(METALAKE, policyName).content());
}
diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/RestrictedRegoTestUtils.java b/core/src/test/java/org/apache/gravitino/policy/rego/RestrictedRegoTestUtils.java
deleted file mode 100644
index a9caa483b5..0000000000
--- a/core/src/test/java/org/apache/gravitino/policy/rego/RestrictedRegoTestUtils.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * 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/TestComparison.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestComparison.java
deleted file mode 100644
index 775bf647a3..0000000000
--- a/core/src/test/java/org/apache/gravitino/policy/rego/TestComparison.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * 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.java
deleted file mode 100644
index d8c263b7f1..0000000000
--- a/core/src/test/java/org/apache/gravitino/policy/rego/TestComparisonOperator.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * 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.java
deleted file mode 100644
index 76751be333..0000000000
--- a/core/src/test/java/org/apache/gravitino/policy/rego/TestGroupMembership.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.java
deleted file mode 100644
index de4f4a81e8..0000000000
--- a/core/src/test/java/org/apache/gravitino/policy/rego/TestLiteral.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * 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.java
deleted file mode 100644
index f0d831b786..0000000000
--- a/core/src/test/java/org/apache/gravitino/policy/rego/TestLiteralArray.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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.java
deleted file mode 100644
index 76fc9523d1..0000000000
--- a/core/src/test/java/org/apache/gravitino/policy/rego/TestLogicalExpression.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * 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.java
deleted file mode 100644
index 839e9e8412..0000000000
--- a/core/src/test/java/org/apache/gravitino/policy/rego/TestNot.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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.java
deleted file mode 100644
index 4e81d84177..0000000000
--- a/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoExpressionParserFacade.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * 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/TestRestrictedRegoLexer.java b/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoLexer.java
deleted file mode 100644
index b4a8346b97..0000000000
--- a/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoLexer.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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.java
deleted file mode 100644
index f5a1cee4a5..0000000000
--- a/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoProgram.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * 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.java
deleted file mode 100644
index d6afa5b961..0000000000
--- a/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoSourceParser.java
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * 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.java
deleted file mode 100644
index e4e08bab84..0000000000
--- a/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoSourceValidator.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * 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/sql/TestRestrictedSqlExpressionParser.java b/core/src/test/java/org/apache/gravitino/policy/sql/TestRestrictedSqlExpressionParser.java
new file mode 100644
index 0000000000..f7196811d0
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/policy/sql/TestRestrictedSqlExpressionParser.java
@@ -0,0 +1,427 @@
+/*
+ * 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.sql;
+
+import java.util.Collections;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/** Conformance tests for typed SQL read-restriction definitions. */
+class TestRestrictedSqlExpressionParser {
+ @ParameterizedTest
+ @MethodSource("validFilters")
+ void testValidFilters(String source) {
+ Assertions.assertDoesNotThrow(
+ () -> RestrictedSqlExpressionParserFacade.validateRowFilter(source));
+ }
+
+ private static Stream<String> validFilters() {
+ return Stream.of(
+ "() RETURNS BOOLEAN -> TRUE",
+ "() RETURNS BOOLEAN -> NULL",
+ "() returns boolean -> current_user() = 'O''Brien'",
+ "() RETURNS BOOLEAN -> is_group_member('auditors')",
+ "() RETURNS BOOLEAN -> NOT NULL OR FALSE AND TRUE",
+ "() RETURNS BOOLEAN -> 1.0 = 1",
+ "() RETURNS BOOLEAN -> NULL = NULL",
+ "(active BOOLEAN) RETURNS BOOLEAN -> active",
+ "(x STRING) RETURNS BOOLEAN -> x <> 'US'",
+ "(x STRING) RETURNS BOOLEAN -> NOT (x = 'US')",
+ "(x STRING) RETURNS BOOLEAN -> x IS NULL OR x != 'US'",
+ "(x STRING) RETURNS BOOLEAN -> x LIKE 'Acme%'",
+ "(x STRING) RETURNS BOOLEAN -> x NOT LIKE 'Acme%'",
+ "(x STRING) RETURNS BOOLEAN -> x IN ('US', 'CA', NULL)",
+ "(x STRING) RETURNS BOOLEAN -> x NOT IN (NULL)",
+ "(x STRING) RETURNS BOOLEAN -> CASE WHEN x IS NULL THEN FALSE ELSE x = 'US' END",
+ "(x STRING) RETURNS BOOLEAN -> CASE x WHEN 'US' THEN TRUE WHEN 'CA' THEN TRUE ELSE FALSE END",
+ "(x STRING) RETURNS BOOLEAN -> CASE x WHEN NULL THEN TRUE END",
+ "(x STRING) RETURNS BOOLEAN -> CASE WHEN NULL THEN TRUE ELSE CASE x WHEN 'US' THEN TRUE ELSE FALSE END END",
+ "(x STRING, y STRING) RETURNS BOOLEAN -> x = y",
+ "(x INTEGER) RETURNS BOOLEAN -> x BETWEEN -2147483648 AND 2147483647",
+ "(x LONG) RETURNS BOOLEAN -> x NOT BETWEEN -9223372036854775808 AND 9223372036854775807",
+ "(x DECIMAL(4,2)) RETURNS BOOLEAN -> x IN (99.99, -99.99, 1.000, NULL)",
+ "(x FLOAT) RETURNS BOOLEAN -> is_nan(x) OR x = -0.0",
+ "(x DOUBLE) RETURNS BOOLEAN -> NOT is_nan(x)",
+ "(x DATE) RETURNS BOOLEAN -> x >= DATE '2024-02-29' AND year(x) = 2024",
+ "(x DATE) RETURNS BOOLEAN -> month(x) = 3 OR day(x) = 15",
+ "(x TIME(6)) RETURNS BOOLEAN -> x = TIME '12:30:00.123456'",
+ "(x TIMESTAMP) RETURNS BOOLEAN -> x = TIMESTAMP '2026-01-01 12:30:00'",
+ "(x TIMESTAMP WITHOUT TIME ZONE) RETURNS BOOLEAN -> x = TIMESTAMP '2026-01-01 12:30:00'",
+ "(x TIMESTAMP(6) WITH TIME ZONE) RETURNS BOOLEAN -> x = TIMESTAMP WITH TIME ZONE '2026-01-01 12:30:00+00:00'",
+ "(val STRING, \"val\" STRING) RETURNS BOOLEAN -> VAL = \"val\"",
+ "(\"CASE\" STRING, \"Customer Region\" STRING) RETURNS BOOLEAN -> \"CASE\" = \"Customer Region\"",
+ "(\"a\"\"b\" STRING) RETURNS BOOLEAN -> \"a\"\"b\" = '\\n中😀'");
+ }
+
+ @ParameterizedTest
+ @MethodSource("validMasks")
+ void testValidMasks(String source) {
+ Assertions.assertDoesNotThrow(
+ () -> RestrictedSqlExpressionParserFacade.validateColumnMask(source));
+ }
+
+ private static Stream<String> validMasks() {
+ Stream<String> strings =
+ Stream.of(
+ "value",
+ "NULL",
+ "'XXXXXXXX'",
+ "mask_alphanum(value)",
+ "show_first_4(value)",
+ "show_last_4(value)",
+ "mask_to_fixed_value(value)",
+ "replace_with_null(value)",
+ "sha256_global(value)",
+ "sha256_query_local(value)",
+ "show_last_4(mask_alphanum(value))",
+ "CASE WHEN is_group_member('auditors') THEN show_last_4(value) ELSE NULL END",
+ "CASE WHEN value IS NULL THEN NULL ELSE 'XXXXXXXX' END",
+ "CASE CURRENT_USER() WHEN 'alice' THEN value END")
+ .map(body -> "(value STRING) RETURNS STRING -> " + body);
+ return Stream.concat(
+ strings,
+ Stream.of(
+ "(xxx STRING) RETURNS STRING -> show_last_4(xxx)",
+ "(value INTEGER) RETURNS INTEGER -> sha256_global(value)",
+ "(value LONG) RETURNS LONG -> sha256_query_local(value)",
+ "(value BINARY) RETURNS BINARY -> sha256_global(value)",
+ "(value BINARY) RETURNS BINARY -> replace_with_null(value)",
+ "(value DATE) RETURNS DATE -> truncate_to_year(value)",
+ "(value TIMESTAMP WITH TIME ZONE) RETURNS TIMESTAMP(6) WITH TIME ZONE -> truncate_to_month(value)",
+ "(value TIME) RETURNS TIME(6) -> value",
+ "(value BOOLEAN) RETURNS BOOLEAN -> mask_to_fixed_value(value)",
+ "(value DOUBLE) RETURNS DOUBLE -> mask_to_fixed_value(value)",
+ "(value DECIMAL(3,1)) RETURNS DECIMAL(3,1) -> CASE WHEN TRUE THEN -99.9 ELSE 0 END"));
+ }
+
+ @ParameterizedTest
+ @MethodSource("invalidFilters")
+ void testInvalidFilters(String source) {
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> RestrictedSqlExpressionParserFacade.validateRowFilter(source),
+ source);
+ }
+
+ private static Stream<String> invalidFilters() {
+ Stream<String> bodies =
+ Stream.of(
+ "'not boolean'",
+ "1",
+ "unknown",
+ "col('x') = 'a'",
+ "session_user() = 'a'",
+ "TRUE;",
+ "TRUE -- comment",
+ "TRUE /* comment */",
+ "TRUE # comment",
+ "SELECT TRUE",
+ "TRUE TRUE",
+ "1 < 2 < 3",
+ "1 == 1",
+ "1 '=' 1",
+ "TRUE OR 1",
+ "NOT 1",
+ "NULL IS TRUE",
+ "TRUE < FALSE",
+ "'1' = 1",
+ "TRUE = 1",
+ "1 = +1",
+ "1 = 01",
+ "1 = 1e2",
+ "1 = 1.",
+ "1 = 1and TRUE",
+ "TRUEFALSE",
+ "NOTTRUE",
+ "CURRENT_USER('a') = 'a'",
+ "unknown_function()",
+ "is_group_member(CURRENT_USER())",
+ "is_group_member('')",
+ "user_attribute('') IS NULL",
+ "user_attribute('region') IS NULL",
+ "CURRENT_USER() = user_attribute('name')",
+ "is_nan('a')",
+ "year('2026-01-01') = 2026",
+ "CASE WHEN 1 THEN TRUE END",
+ "CASE WHEN TRUE THEN FALSE ELSE 1 END",
+ "CASE WHEN TRUE THEN TRUE ELSE unknown_function() END",
+ "CASE TRUE WHEN 'a' THEN TRUE END",
+ "CASE WHEN TRUE THEN TRUE",
+ "CASE END",
+ "CASE WHEN TRUE THEN TRUE ELSE FALSE END END",
+ "TRUE IN ()",
+ "TRUE IN (TRUE, 1)",
+ "TRUE IN [TRUE]",
+ "TRUE IN (CURRENT_USER())",
+ "TRUE BETWEEN FALSE AND TRUE",
+ "'x' LIKE '%Acme'",
+ "'x' LIKE '%'",
+ "'x' LIKE 'A_me%'",
+ "'x' LIKE 'A%%'",
+ "'x' LIKE 'Acme%' ESCAPE '!'",
+ "TRUE NOT NULL",
+ "DATE '2025-02-29' IS NULL",
+ "TIME '24:00:00' IS NULL",
+ "TIME '12:00:00.1234567' IS NULL",
+ "TIMESTAMP WITH TIME ZONE '2026-01-01 12:00:00' IS NULL",
+ "TIMESTAMP '2026-01-01 12:00:00Z' IS NULL",
+ "user_attribute('k') = 's' AND user_attribute('k') = TRUE");
+ return Stream.concat(
+ bodies.map(body -> "() RETURNS BOOLEAN -> " + body),
+ Stream.of(
+ "",
+ " ",
+ "TRUE",
+ "filter := true",
+ "(x STRING) -> TRUE",
+ "RETURNS BOOLEAN -> TRUE",
+ "() RETURNS STRING -> TRUE",
+ "(x INTEGER, X INTEGER) RETURNS BOOLEAN -> TRUE",
+ "(\"X\" STRING, x STRING) RETURNS BOOLEAN -> TRUE",
+ "(TRUE STRING) RETURNS BOOLEAN -> TRUE",
+ "(x INT) RETURNS BOOLEAN -> TRUE",
+ "(x ARRAY) RETURNS BOOLEAN -> TRUE",
+ "(x DECIMAL(0,0)) RETURNS BOOLEAN -> TRUE",
+ "(x DECIMAL(39,0)) RETURNS BOOLEAN -> TRUE",
+ "(x DECIMAL(2,3)) RETURNS BOOLEAN -> TRUE",
+ "(x DECIMAL(-1,0)) RETURNS BOOLEAN -> TRUE",
+ "(x TIME(3)) RETURNS BOOLEAN -> TRUE",
+ "(x TIMESTAMP(9)) RETURNS BOOLEAN -> TRUE",
+ "(x INTEGER) RETURNS BOOLEAN -> x = 2147483648",
+ "(x LONG) RETURNS BOOLEAN -> x = -9223372036854775809",
+ "(x INTEGER) RETURNS BOOLEAN -> x = 1.1",
+ "(x DECIMAL(3,2)) RETURNS BOOLEAN -> x = 10.00",
+ "(x DECIMAL(3,2)) RETURNS BOOLEAN -> x = 1.001",
+ "(x STRING) RETURNS BOOLEAN -> x = 1",
+ "(x INTEGER, y LONG) RETURNS BOOLEAN -> x = y",
+ "(x BINARY) RETURNS BOOLEAN -> x = x",
+ "(x STRING) RETURNS BOOLEAN -> x IN ('a', x)",
+ "(x STRING) RETURNS BOOLEAN -> x = \"a\"",
+ "(x STRING) RETURNS BOOLEAN -> x.field = 'a'",
+ "(x STRING) RETURNS BOOLEAN -> x = 'unterminated",
+ "(\"\" STRING) RETURNS BOOLEAN -> TRUE"));
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "() RETURNS STRING -> 'x'",
+ "(a STRING, b STRING) RETURNS STRING -> a",
+ "(value STRING) RETURNS INTEGER -> 1",
+ "(value STRING) RETURNS STRING -> phone_number",
+ "(value STRING) RETURNS STRING -> CASE WHEN TRUE THEN value ELSE 1 END",
+ "(value STRING) RETURNS STRING -> show_last_4(value, 4)",
+ "(value INTEGER) RETURNS INTEGER -> show_last_4(value)",
+ "(value DOUBLE) RETURNS DOUBLE -> sha256_global(value)",
+ "(value TIME) RETURNS TIME -> mask_to_fixed_value(value)",
+ "(value STRING) RETURNS STRING -> truncate_to_month(value)",
+ "(value STRING) RETURNS STRING -> unknown(value)",
+ "(value DECIMAL(3,1)) RETURNS DECIMAL(3,2) -> NULL",
+ "(value TIMESTAMP) RETURNS TIMESTAMP WITH TIME ZONE -> NULL",
+ "mask := action('show-last-4')"
+ })
+ void testInvalidMasks(String source) {
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> RestrictedSqlExpressionParserFacade.validateColumnMask(source));
+ }
+
+ @Test
+ void testPreservesCaseNullAndPredicateStructure() {
+ SqlDefinition definition =
+ RestrictedSqlExpressionParserFacade.parse(
+ "(x STRING) RETURNS BOOLEAN -> CASE WHEN x = 'US' THEN TRUE WHEN x IS NULL THEN FALSE END",
+ false);
+ CaseExpression expression =
+ Assertions.assertInstanceOf(CaseExpression.class, definition.body());
+ Assertions.assertEquals(2, expression.branches().size());
+ Assertions.assertInstanceOf(Comparison.class, expression.branches().get(0).condition());
+ Assertions.assertInstanceOf(IsNull.class, expression.branches().get(1).condition());
+ Assertions.assertNull(expression.fallback());
+ SqlDefinition negation =
+ RestrictedSqlExpressionParserFacade.parse(
+ "(x STRING) RETURNS BOOLEAN -> NOT x = 'US' OR x IS NULL AND FALSE", false);
+ LogicalExpression logical =
+ Assertions.assertInstanceOf(LogicalExpression.class, negation.body());
+ Assertions.assertEquals(LogicalOperator.OR, logical.operator());
+ Assertions.assertInstanceOf(Not.class, logical.operands().get(0));
+ LogicalExpression conjunction =
+ Assertions.assertInstanceOf(LogicalExpression.class, logical.operands().get(1));
+ Assertions.assertEquals(LogicalOperator.AND, conjunction.operator());
+ Assertions.assertThrows(
+ UnsupportedOperationException.class, () -> definition.parameters().clear());
+ Assertions.assertThrows(
+ UnsupportedOperationException.class, () -> definition.body().children().clear());
+ }
+
+ @Test
+ void testIdentifierAndLiteralPreservation() {
+ SqlDefinition definition =
+ RestrictedSqlExpressionParserFacade.parse(
+ "(\"a\"\"b\" STRING) RETURNS BOOLEAN -> \"a\"\"b\" = 'O''Brien\\n😀'", false);
+ Assertions.assertTrue(definition.parameters().containsKey("a\"b"));
+ Comparison comparison = Assertions.assertInstanceOf(Comparison.class, definition.body());
+ Literal value = Assertions.assertInstanceOf(Literal.class, comparison.right());
+ Assertions.assertEquals("O'Brien\\n😀", value.value());
+ SqlDefinition mask =
+ RestrictedSqlExpressionParserFacade.parse(
+ "(local_name STRING) RETURNS STRING -> show_last_4(local_name)", true);
+ FunctionCall call = Assertions.assertInstanceOf(FunctionCall.class, mask.body());
+ Assertions.assertEquals(SqlFunction.SHOW_LAST_4, call.function());
+ Assertions.assertEquals("LOCAL_NAME", ((InputReference) call.arguments().get(0)).name());
+ SqlDefinition zero =
+ RestrictedSqlExpressionParserFacade.parse("(x DOUBLE) RETURNS DOUBLE -> -0.0", true);
+ Assertions.assertEquals("-0.0", ((Literal) zero.body()).value());
+ }
+
+ @Test
+ void testPublicParseInterfacesPreserveBindingMetadata() {
+ SqlDefinition filter =
+ RestrictedSqlExpressionParserFacade.parseRowFilter(
+ "(\"Region\" STRING, owner STRING) RETURNS BOOLEAN -> \"Region\" = owner");
+ Assertions.assertFalse(filter.isColumnMask());
+ Assertions.assertTrue(filter.isQuotedParameter("Region"));
+ Assertions.assertFalse(filter.isQuotedParameter("OWNER"));
+ SqlDefinition mask =
+ RestrictedSqlExpressionParserFacade.parseColumnMask(
+ "(local STRING) RETURNS STRING -> local");
+ Assertions.assertTrue(mask.isColumnMask());
+ Assertions.assertEquals(SqlType.STRING, mask.resultType());
+ Assertions.assertEquals("STRING", mask.resultType().name());
+ Assertions.assertEquals(0, mask.resultType().precision());
+ Assertions.assertEquals(0, mask.resultType().scale());
+ Assertions.assertFalse(mask.resultType().withTimeZone());
+ }
+
+ @Test
+ void testSourceAndLiteralLimits() {
+ String prefix = "() RETURNS BOOLEAN -> TRUE";
+ Assertions.assertDoesNotThrow(
+ () ->
+ RestrictedSqlExpressionParserFacade.validateRowFilter(
+ prefix + " ".repeat(16384 - prefix.length())));
+ reject(prefix + " ".repeat(16385 - prefix.length()));
+ filter("'" + "中".repeat(1365) + "a' IS NULL");
+ rejectBody("'" + "中".repeat(1365) + "aa' IS NULL");
+ filter("1 = " + "9".repeat(256));
+ rejectBody("1 = " + "9".repeat(257));
+ rejectBody("'\uD800' IS NULL");
+ rejectBody("'\uDC00' IS NULL");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> RestrictedSqlExpressionParserFacade.validateRowFilter(null));
+ reject("(x FLOAT) RETURNS BOOLEAN -> x = " + "9".repeat(40));
+ }
+
+ @Test
+ void testDepthNodeAndListLimits() {
+ filter("NOT ".repeat(16) + "TRUE");
+ rejectBody("NOT ".repeat(17) + "TRUE");
+ rejectBody("NOT ".repeat(2000) + "TRUE");
+ rejectBody("TRUE OR (".repeat(17) + "FALSE" + ")".repeat(17));
+ filter("(".repeat(64) + "TRUE" + ")".repeat(64));
+ rejectBody("(".repeat(65) + "TRUE" + ")".repeat(65));
+ filter(String.join(" OR ", Collections.nCopies(1023, "TRUE")));
+ rejectBody(String.join(" OR ", Collections.nCopies(1024, "TRUE")));
+ filter("1 IN (" + numbers(1000) + ")");
+ rejectBody("1 IN (" + numbers(1001) + ")");
+ filter("1 IN (" + numbers(500) + ") AND 2 IN (" + numbers(500) + ")");
+ rejectBody("1 IN (" + numbers(500) + ") AND 2 IN (" + numbers(501) + ")");
+ filter("CASE WHEN TRUE THEN ".repeat(16) + "TRUE" + " END".repeat(16));
+ rejectBody("CASE WHEN TRUE THEN ".repeat(17) + "TRUE" + " END".repeat(17));
+ Assertions.assertDoesNotThrow(
+ () ->
+ RestrictedSqlExpressionParserFacade.validateColumnMask(
+ "(x STRING) RETURNS STRING -> "
+ + "show_last_4(".repeat(16)
+ + "x"
+ + ")".repeat(16)));
+ rejectBody("show_last_4(".repeat(17) + "'x'" + ")".repeat(17) + " IS NULL");
+ }
+
+ @Test
+ void testSyntaxErrorsHaveLocation() {
+ IllegalArgumentException error =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ RestrictedSqlExpressionParserFacade.validateRowFilter(
+ "() RETURNS BOOLEAN ->\n TRUE;"));
+ Assertions.assertTrue(error.getMessage().contains("line 2, column"));
+ }
+
+ @Test
+ void testSemanticErrorsLocateInnermostOperand() {
+ IllegalArgumentException error =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ RestrictedSqlExpressionParserFacade.validateRowFilter(
+ "(x INTEGER) RETURNS BOOLEAN ->\nx < TRUE"));
+ Assertions.assertTrue(error.getMessage().contains("line 2, column 5"));
+ Assertions.assertTrue(error.getMessage().contains("expected INTEGER, found BOOLEAN"));
+ }
+
+ @Test
+ void testSemanticDiagnosticsDoNotExpandLiteralPayloads() {
+ for (String body :
+ new String[] {
+ "x IN (" + "'private-value',".repeat(200) + "'private-value')",
+ "user_attribute('private-value') IS NULL",
+ "DATE '2025-02-29' IS NULL"
+ }) {
+ IllegalArgumentException error =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ RestrictedSqlExpressionParserFacade.validateRowFilter(
+ "(x INTEGER) RETURNS BOOLEAN ->\n" + body));
+ Assertions.assertTrue(error.getMessage().contains("line 2, column"));
+ Assertions.assertTrue(error.getMessage().length() < 512);
+ Assertions.assertFalse(error.getMessage().contains("private-value"));
+ Assertions.assertFalse(error.getMessage().contains("2025-02-29"));
+ }
+ }
+
+ private static String numbers(int count) {
+ return IntStream.range(0, count).mapToObj(Integer::toString).collect(Collectors.joining(","));
+ }
+
+ private static void filter(String body) {
+ Assertions.assertDoesNotThrow(
+ () ->
+ RestrictedSqlExpressionParserFacade.validateRowFilter("() RETURNS BOOLEAN -> " + body));
+ }
+
+ private static void rejectBody(String body) {
+ reject("() RETURNS BOOLEAN -> " + body);
+ }
+
+ private static void reject(String source) {
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> RestrictedSqlExpressionParserFacade.validateRowFilter(source));
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoGoldenFile.java b/core/src/test/java/org/apache/gravitino/policy/sql/TestRestrictedSqlGoldenFile.java
similarity index 81%
rename from core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoGoldenFile.java
rename to core/src/test/java/org/apache/gravitino/policy/sql/TestRestrictedSqlGoldenFile.java
index 1cec255da9..8b2128654b 100644
--- a/core/src/test/java/org/apache/gravitino/policy/rego/TestRestrictedRegoGoldenFile.java
+++ b/core/src/test/java/org/apache/gravitino/policy/sql/TestRestrictedSqlGoldenFile.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.policy.rego;
+package org.apache.gravitino.policy.sql;
import java.io.IOException;
import java.io.InputStream;
@@ -26,16 +26,15 @@ 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";
+/** Golden-file and documentation-drift tests for {@code restricted-sql-v1}. */
+public class TestRestrictedSqlGoldenFile {
+ private static final String GOLDEN_CASES_RESOURCE = "/restricted-sql-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";
+ "core/src/test/resources/restricted-sql-v1-cases.golden";
+ private static final String UPDATE_GOLDEN_ENV = "GRAVITINO_UPDATE_RESTRICTED_SQL_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"
@@ -54,7 +53,7 @@ public class TestRestrictedRegoGoldenFile {
+ "# limitations under the License.\n";
@Test
- void testRestrictedRegoGoldenFile() throws IOException {
+ void testRestrictedSqlGoldenFile() throws IOException {
String actual = renderGoldenResults();
Path goldenFile = repositoryRoot().resolve(GOLDEN_FILE);
if (Boolean.parseBoolean(System.getenv(UPDATE_GOLDEN_ENV))) {
@@ -76,7 +75,10 @@ public class TestRestrictedRegoGoldenFile {
Assertions.assertFalse(programs.isEmpty());
for (String program : programs) {
- Assertions.assertDoesNotThrow(() -> RestrictedRegoExpressionParserFacade.parse(program));
+ Assertions.assertDoesNotThrow(
+ () ->
+ RestrictedSqlExpressionParserFacade.parse(
+ program, !program.contains("RETURNS BOOLEAN")));
}
}
@@ -92,8 +94,8 @@ public class TestRestrictedRegoGoldenFile {
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");
+ TestRestrictedSqlGoldenFile.class.getResourceAsStream(GOLDEN_CASES_RESOURCE)) {
+ Assertions.assertNotNull(input, "restricted SQL golden cases");
lines = new String(input.readAllBytes(), StandardCharsets.UTF_8).lines().toList();
}
@@ -101,21 +103,16 @@ public class TestRestrictedRegoGoldenFile {
if (line.isBlank() || line.startsWith("#")) {
continue;
}
- String[] fields = line.split("\\t", 2);
- Assertions.assertEquals(2, fields.length, "Invalid restricted Rego golden case: " + line);
+ String[] fields = line.split("\\t", 3);
+ Assertions.assertEquals(3, fields.length, "Invalid restricted SQL golden case: " + line);
String name = fields[0];
- String source = fields[1];
+ String source = fields[2];
result.append('\n').append("=== ").append(name).append(" ===\n");
result.append("source: ").append(escapeGoldenValue(source)).append('\n');
try {
- RestrictedRegoProgram program = RestrictedRegoExpressionParserFacade.parse(source);
+ SqlDefinition program =
+ RestrictedSqlExpressionParserFacade.parse(source, fields[1].equals("mask"));
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');
}
@@ -160,8 +157,8 @@ public class TestRestrictedRegoGoldenFile {
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");
+ if (line.equals("```sql")) {
+ Assertions.assertNull(current, "Nested restricted SQL documentation fence");
current = new StringBuilder();
} else if (current != null && line.equals("```")) {
programs.add(current.toString().stripTrailing());
@@ -170,7 +167,7 @@ public class TestRestrictedRegoGoldenFile {
current.append(line).append('\n');
}
}
- Assertions.assertNull(current, "Unclosed restricted Rego documentation fence");
+ Assertions.assertNull(current, "Unclosed restricted SQL documentation fence");
return programs;
}
}
diff --git a/core/src/test/java/org/apache/gravitino/policy/sql/TestSqlExpression.java b/core/src/test/java/org/apache/gravitino/policy/sql/TestSqlExpression.java
new file mode 100644
index 0000000000..fbff3baabd
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/policy/sql/TestSqlExpression.java
@@ -0,0 +1,134 @@
+/*
+ * 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.sql;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+/** Structural tests for the operation-specific AST and operator enums. */
+class TestSqlExpression {
+ @ParameterizedTest
+ @MethodSource("sources")
+ void testStructuralEqualityAndImmutableOperands(String source) {
+ boolean mask = !source.contains("RETURNS BOOLEAN");
+ SqlExpression first = RestrictedSqlExpressionParserFacade.parse(source, mask).body();
+ SqlExpression second = RestrictedSqlExpressionParserFacade.parse(source, mask).body();
+ Assertions.assertEquals(first, second);
+ Assertions.assertEquals(first.hashCode(), second.hashCode());
+ Assertions.assertEquals(first.toString(), second.toString());
+ Assertions.assertNotEquals(first, null);
+ Assertions.assertNotEquals(first, new Object());
+ Assertions.assertThrows(UnsupportedOperationException.class, () -> first.children().clear());
+ }
+
+ private static Stream<String> sources() {
+ return Stream.of(
+ "() RETURNS BOOLEAN -> TRUE",
+ "(x BOOLEAN) RETURNS BOOLEAN -> x",
+ "(x INTEGER) RETURNS BOOLEAN -> x = 1",
+ "(x BOOLEAN) RETURNS BOOLEAN -> x AND TRUE",
+ "(x BOOLEAN) RETURNS BOOLEAN -> NOT x",
+ "(x STRING) RETURNS BOOLEAN -> x IS NULL",
+ "(x INTEGER) RETURNS BOOLEAN -> x IN (1, NULL)",
+ "(x INTEGER) RETURNS BOOLEAN -> x BETWEEN 1 AND 10",
+ "(x STRING) RETURNS BOOLEAN -> x LIKE 'A%'",
+ "(x STRING) RETURNS BOOLEAN -> CASE x WHEN 'US' THEN TRUE ELSE FALSE END",
+ "(x STRING) RETURNS BOOLEAN -> CASE WHEN x IS NULL THEN FALSE END",
+ "(x STRING) RETURNS STRING -> show_last_4(x)");
+ }
+
+ @Test
+ void testComparisonOperatorsAndAliases() {
+ for (ComparisonOperator operator : ComparisonOperator.values()) {
+ Assertions.assertSame(operator, ComparisonOperator.fromToken(operator.sourceToken()));
+ Assertions.assertEquals(
+ operator != ComparisonOperator.EQ && operator != ComparisonOperator.NEQ,
+ operator.ordered());
+ }
+ Assertions.assertSame(ComparisonOperator.NEQ, ComparisonOperator.fromToken("!="));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> ComparisonOperator.fromToken("=="));
+ Assertions.assertEquals(SqlFunction.SHOW_LAST_4, SqlFunction.fromName("Show_Last_4"));
+ Assertions.assertThrows(IllegalArgumentException.class, () -> SqlFunction.fromName("unknown"));
+ }
+
+ @Test
+ void testOperationIdentityAndAccessorMethods() {
+ Literal one = new Literal(LiteralType.NUMBER, "1", null);
+ Literal two = new Literal(LiteralType.NUMBER, "2", null);
+ Literal three = new Literal(LiteralType.NUMBER, "3", null);
+ Comparison comparison = new Comparison(ComparisonOperator.LT, one, two);
+ Assertions.assertSame(one, comparison.left());
+ Assertions.assertSame(two, comparison.right());
+ Assertions.assertNotEquals(comparison, new Comparison(ComparisonOperator.LTE, one, two));
+ Assertions.assertSame(one, new Not(one).operand());
+ Assertions.assertSame(one, new IsNull(one, true).operand());
+ Assertions.assertTrue(new IsNull(one, true).negated());
+ Assertions.assertNotEquals(new IsNull(one, true), new IsNull(one, false));
+ Between between = new Between(one, two, three);
+ Assertions.assertSame(one, between.operand());
+ Assertions.assertSame(two, between.lower());
+ Assertions.assertSame(three, between.upper());
+ In in = new In(one, Arrays.asList(two, three));
+ Assertions.assertSame(one, in.operand());
+ Assertions.assertEquals(Arrays.asList(two, three), in.values());
+ Assertions.assertNotEquals(between, in);
+ Literal pattern = new Literal(LiteralType.STRING, "A%", SqlType.STRING);
+ Like like = new Like(one, pattern);
+ Assertions.assertSame(one, like.operand());
+ Assertions.assertSame(pattern, like.pattern());
+ Assertions.assertNotEquals(one, new Literal(LiteralType.NUMBER, "2", null));
+ Assertions.assertNotEquals(one, new InputReference("X", SqlType.INTEGER));
+ }
+
+ @Test
+ void testCopiesMutableConstructionInputs() {
+ Literal yes = new Literal(LiteralType.BOOLEAN, "TRUE", SqlType.BOOLEAN);
+ List<SqlExpression> operands = new ArrayList<>(Arrays.asList(yes, yes));
+ LogicalExpression logical = new LogicalExpression(LogicalOperator.AND, operands);
+ operands.clear();
+ Assertions.assertEquals(2, logical.operands().size());
+ FunctionCall call = new FunctionCall(SqlFunction.CURRENT_USER, operands);
+ operands.add(yes);
+ Assertions.assertTrue(call.arguments().isEmpty());
+ CaseBranch branch = new CaseBranch(yes, yes);
+ List<CaseBranch> branches = new ArrayList<>(Collections.singletonList(branch));
+ CaseExpression expression = new CaseExpression(null, branches, null);
+ branches.clear();
+ Assertions.assertEquals(1, expression.branches().size());
+ Assertions.assertSame(yes, expression.branches().get(0).condition());
+ Assertions.assertSame(yes, expression.results().get(0));
+ Assertions.assertThrows(
+ UnsupportedOperationException.class, () -> expression.branches().clear());
+ Assertions.assertThrows(
+ UnsupportedOperationException.class, () -> expression.results().clear());
+ Assertions.assertNull(expression.selector());
+ Assertions.assertNull(expression.fallback());
+ Assertions.assertEquals(1, expression.depth());
+ Assertions.assertEquals(0, yes.depth());
+ Assertions.assertEquals(1, call.depth());
+ }
+}
diff --git a/core/src/test/resources/restricted-rego-v1-cases.golden b/core/src/test/resources/restricted-rego-v1-cases.golden
deleted file mode 100644
index 84963a9da0..0000000000
--- a/core/src/test/resources/restricted-rego-v1-cases.golden
+++ /dev/null
@@ -1,91 +0,0 @@
-# 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.txt
deleted file mode 100644
index 8794dfc473..0000000000
--- a/core/src/test/resources/restricted-rego-v1-cases.txt
+++ /dev/null
@@ -1,35 +0,0 @@
-# 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/core/src/test/resources/restricted-sql-v1-cases.golden b/core/src/test/resources/restricted-sql-v1-cases.golden
new file mode 100644
index 0000000000..121bf74718
--- /dev/null
+++ b/core/src/test/resources/restricted-sql-v1-cases.golden
@@ -0,0 +1,254 @@
+# 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.
+
+=== eq ===
+source: (x STRING) RETURNS BOOLEAN -> x = 'US'
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=Comparison{attributes=[EQ], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, US, STRING], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== neq ===
+source: (x STRING) RETURNS BOOLEAN -> x <> 'US'
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=Comparison{attributes=[NEQ], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, US, STRING], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== neq_alias ===
+source: (x STRING) RETURNS BOOLEAN -> x != 'US'
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=Comparison{attributes=[NEQ], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, US, STRING], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== lt ===
+source: (x STRING) RETURNS BOOLEAN -> x < 'US'
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=Comparison{attributes=[LT], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, US, STRING], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== lte ===
+source: (x STRING) RETURNS BOOLEAN -> x <= 'US'
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=Comparison{attributes=[LTE], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, US, STRING], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== gt ===
+source: (x STRING) RETURNS BOOLEAN -> x > 'US'
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=Comparison{attributes=[GT], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, US, STRING], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== gte ===
+source: (x STRING) RETURNS BOOLEAN -> x >= 'US'
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=Comparison{attributes=[GTE], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, US, STRING], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== in ===
+source: (x STRING) RETURNS BOOLEAN -> x IN ('US', 'CA', NULL)
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=In{attributes=[], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, US, STRING], children=[]}, Literal{attributes=[STRING, CA, STRING], children=[]}, Literal{attributes=[NULL, , null], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== not_in ===
+source: (x STRING) RETURNS BOOLEAN -> x NOT IN ('US', NULL)
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=Not{attributes=[], children=[In{attributes=[], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, US, STRING], children=[]}, Literal{attributes=[NULL, , null], children=[]}]}]}, quotedParameters=[], columnMask=false}
+
+=== between ===
+source: (x STRING) RETURNS BOOLEAN -> x BETWEEN 'A' AND 'Z'
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=Between{attributes=[], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, A, STRING], children=[]}, Literal{attributes=[STRING, Z, STRING], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== not_between ===
+source: (x STRING) RETURNS BOOLEAN -> x NOT BETWEEN 'A' AND 'Z'
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=Not{attributes=[], children=[Between{attributes=[], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, A, STRING], children=[]}, Literal{attributes=[STRING, Z, STRING], children=[]}]}]}, quotedParameters=[], columnMask=false}
+
+=== is_null ===
+source: (x STRING) RETURNS BOOLEAN -> x IS NULL
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=IsNull{attributes=[false], children=[InputReference{attributes=[X, STRING], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== is_not_null ===
+source: (x STRING) RETURNS BOOLEAN -> x IS NOT NULL
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=IsNull{attributes=[true], children=[InputReference{attributes=[X, STRING], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== like ===
+source: (x STRING) RETURNS BOOLEAN -> x LIKE 'Acme%'
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=Like{attributes=[], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, Acme%, STRING], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== not_like ===
+source: (x STRING) RETURNS BOOLEAN -> x NOT LIKE 'Acme%'
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=Not{attributes=[], children=[Like{attributes=[], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, Acme%, STRING], children=[]}]}]}, quotedParameters=[], columnMask=false}
+
+=== precedence ===
+source: (x STRING) RETURNS BOOLEAN -> NOT x = 'US' OR x IS NULL AND FALSE
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=LogicalExpression{attributes=[OR], children=[Not{attributes=[], children=[Comparison{attributes=[EQ], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, US, STRING], children=[]}]}]}, LogicalExpression{attributes=[AND], children=[IsNull{attributes=[false], children=[InputReference{attributes=[X, STRING], children=[]}]}, Literal{attributes=[BOOLEAN, FALSE, BOOLEAN], children=[]}]}]}, quotedParameters=[], columnMask=false}
+
+=== searched_case ===
+source: (x STRING) RETURNS BOOLEAN -> CASE WHEN is_group_member('auditors') THEN x = 'US' ELSE x = CURRENT_USER() END
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=CaseExpression{attributes=[false, true], children=[FunctionCall{attributes=[IS_GROUP_MEMBER], children=[Literal{attributes=[STRING, auditors, STRING], children=[]}]}, Comparison{attributes=[EQ], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, US, STRING], children=[]}]}, Comparison{attributes=[EQ], children=[InputReference{attributes=[X, STRING], children=[]}, FunctionCall{attributes=[CURRENT_USER], children=[]}]}]}, quotedParameters=[], columnMask=false}
+
+=== simple_case ===
+source: (x STRING) RETURNS BOOLEAN -> CASE x WHEN 'US' THEN TRUE WHEN NULL THEN FALSE END
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=CaseExpression{attributes=[true, false], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, US, STRING], children=[]}, Literal{attributes=[BOOLEAN, TRUE, BOOLEAN], children=[]}, Literal{attributes=[NULL, , null], children=[]}, Literal{attributes=[BOOLEAN, FALSE, BOOLEAN], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== quoted_string ===
+source: (x STRING) RETURNS BOOLEAN -> x = 'O''Brien\\n😀'
+result: SqlDefinition{parameters={X=STRING}, resultType=BOOLEAN, body=Comparison{attributes=[EQ], children=[InputReference{attributes=[X, STRING], children=[]}, Literal{attributes=[STRING, O'Brien\\n😀, STRING], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== unsupported_user_attribute ===
+source: (x STRING) RETURNS BOOLEAN -> x = user_attribute('region')
+error: Invalid restricted-sql-v1 definition at line 1, column 35: Unknown restricted-sql-v1 function: user_attribute
+
+=== quoted_identifier ===
+source: ("Customer Region" STRING) RETURNS BOOLEAN -> "Customer Region" = 'US'
+result: SqlDefinition{parameters={Customer Region=STRING}, resultType=BOOLEAN, body=Comparison{attributes=[EQ], children=[InputReference{attributes=[Customer Region, STRING], children=[]}, Literal{attributes=[STRING, US, STRING], children=[]}]}, quotedParameters=[Customer Region], columnMask=false}
+
+=== nan ===
+source: (x DOUBLE) RETURNS BOOLEAN -> is_nan(x)
+result: SqlDefinition{parameters={X=DOUBLE}, resultType=BOOLEAN, body=FunctionCall{attributes=[IS_NAN], children=[InputReference{attributes=[X, DOUBLE], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== date_part ===
+source: (x DATE) RETURNS BOOLEAN -> year(x) = 2026 AND month(x) = 3 OR day(x) = 15
+result: SqlDefinition{parameters={X=DATE}, resultType=BOOLEAN, body=LogicalExpression{attributes=[OR], children=[LogicalExpression{attributes=[AND], children=[Comparison{attributes=[EQ], children=[FunctionCall{attributes=[YEAR], children=[InputReference{attributes=[X, DATE], children=[]}]}, Literal{attributes=[NUMBER, 2026, null], children=[]}]}, Comparison{attributes=[EQ], children=[FunctionCall{attributes=[MONTH], children=[InputReference{attributes=[X, DATE], children=[]}]}, Literal{attributes=[NUMBER, 3, null], children=[]}]}]}, Comparison{attributes=[EQ], children=[FunctionCall{attributes=[DAY], children=[InputReference{attributes=[X, DATE], children=[]}]}, Literal{attributes=[NUMBER, 15, null], children=[]}]}]}, quotedParameters=[], columnMask=false}
+
+=== date ===
+source: (x DATE) RETURNS BOOLEAN -> x = DATE '2024-02-29'
+result: SqlDefinition{parameters={X=DATE}, resultType=BOOLEAN, body=Comparison{attributes=[EQ], children=[InputReference{attributes=[X, DATE], children=[]}, Literal{attributes=[TEMPORAL, 2024-02-29, DATE], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== time ===
+source: (x TIME) RETURNS BOOLEAN -> x = TIME '12:30:00.123456'
+result: SqlDefinition{parameters={X=TIME}, resultType=BOOLEAN, body=Comparison{attributes=[EQ], children=[InputReference{attributes=[X, TIME], children=[]}, Literal{attributes=[TEMPORAL, 12:30:00.123456, TIME], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== timestamp ===
+source: (x TIMESTAMP) RETURNS BOOLEAN -> x = TIMESTAMP '2026-01-01 12:30:00'
+result: SqlDefinition{parameters={X=TIMESTAMP}, resultType=BOOLEAN, body=Comparison{attributes=[EQ], children=[InputReference{attributes=[X, TIMESTAMP], children=[]}, Literal{attributes=[TEMPORAL, 2026-01-01 12:30:00, TIMESTAMP], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== timestamp_zone ===
+source: (x TIMESTAMP WITH TIME ZONE) RETURNS BOOLEAN -> x = TIMESTAMP WITH TIME ZONE '2026-01-01 12:30:00+00:00'
+result: SqlDefinition{parameters={X=TIMESTAMP WITH TIME ZONE}, resultType=BOOLEAN, body=Comparison{attributes=[EQ], children=[InputReference{attributes=[X, TIMESTAMP WITH TIME ZONE], children=[]}, Literal{attributes=[TEMPORAL, 2026-01-01 12:30:00+00:00, TIMESTAMP WITH TIME ZONE], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== integer_min ===
+source: (x INTEGER) RETURNS BOOLEAN -> x = -2147483648
+result: SqlDefinition{parameters={X=INTEGER}, resultType=BOOLEAN, body=Comparison{attributes=[EQ], children=[InputReference{attributes=[X, INTEGER], children=[]}, Literal{attributes=[NUMBER, -2147483648, null], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== long_max ===
+source: (x LONG) RETURNS BOOLEAN -> x = 9223372036854775807
+result: SqlDefinition{parameters={X=LONG}, resultType=BOOLEAN, body=Comparison{attributes=[EQ], children=[InputReference{attributes=[X, LONG], children=[]}, Literal{attributes=[NUMBER, 9223372036854775807, null], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== decimal ===
+source: (x DECIMAL(4,2)) RETURNS BOOLEAN -> x = 99.99
+result: SqlDefinition{parameters={X=DECIMAL(4,2)}, resultType=BOOLEAN, body=Comparison{attributes=[EQ], children=[InputReference{attributes=[X, DECIMAL(4,2)], children=[]}, Literal{attributes=[NUMBER, 99.99, null], children=[]}]}, quotedParameters=[], columnMask=false}
+
+=== mask_alphanum ===
+source: (value STRING) RETURNS STRING -> mask_alphanum(value)
+result: SqlDefinition{parameters={VALUE=STRING}, resultType=STRING, body=FunctionCall{attributes=[MASK_ALPHANUM], children=[InputReference{attributes=[VALUE, STRING], children=[]}]}, quotedParameters=[], columnMask=true}
+
+=== show_first_4 ===
+source: (value STRING) RETURNS STRING -> show_first_4(value)
+result: SqlDefinition{parameters={VALUE=STRING}, resultType=STRING, body=FunctionCall{attributes=[SHOW_FIRST_4], children=[InputReference{attributes=[VALUE, STRING], children=[]}]}, quotedParameters=[], columnMask=true}
+
+=== show_last_4 ===
+source: (value STRING) RETURNS STRING -> show_last_4(value)
+result: SqlDefinition{parameters={VALUE=STRING}, resultType=STRING, body=FunctionCall{attributes=[SHOW_LAST_4], children=[InputReference{attributes=[VALUE, STRING], children=[]}]}, quotedParameters=[], columnMask=true}
+
+=== mask_to_fixed_value ===
+source: (value STRING) RETURNS STRING -> mask_to_fixed_value(value)
+result: SqlDefinition{parameters={VALUE=STRING}, resultType=STRING, body=FunctionCall{attributes=[MASK_TO_FIXED_VALUE], children=[InputReference{attributes=[VALUE, STRING], children=[]}]}, quotedParameters=[], columnMask=true}
+
+=== replace_with_null ===
+source: (value STRING) RETURNS STRING -> replace_with_null(value)
+result: SqlDefinition{parameters={VALUE=STRING}, resultType=STRING, body=FunctionCall{attributes=[REPLACE_WITH_NULL], children=[InputReference{attributes=[VALUE, STRING], children=[]}]}, quotedParameters=[], columnMask=true}
+
+=== sha256_global ===
+source: (value STRING) RETURNS STRING -> sha256_global(value)
+result: SqlDefinition{parameters={VALUE=STRING}, resultType=STRING, body=FunctionCall{attributes=[SHA256_GLOBAL], children=[InputReference{attributes=[VALUE, STRING], children=[]}]}, quotedParameters=[], columnMask=true}
+
+=== sha256_query_local ===
+source: (value STRING) RETURNS STRING -> sha256_query_local(value)
+result: SqlDefinition{parameters={VALUE=STRING}, resultType=STRING, body=FunctionCall{attributes=[SHA256_QUERY_LOCAL], children=[InputReference{attributes=[VALUE, STRING], children=[]}]}, quotedParameters=[], columnMask=true}
+
+=== mask_nested ===
+source: (value STRING) RETURNS STRING -> show_last_4(mask_alphanum(value))
+result: SqlDefinition{parameters={VALUE=STRING}, resultType=STRING, body=FunctionCall{attributes=[SHOW_LAST_4], children=[FunctionCall{attributes=[MASK_ALPHANUM], children=[InputReference{attributes=[VALUE, STRING], children=[]}]}]}, quotedParameters=[], columnMask=true}
+
+=== mask_case ===
+source: (value STRING) RETURNS STRING -> CASE WHEN CURRENT_USER() = 'alice' THEN value ELSE NULL END
+result: SqlDefinition{parameters={VALUE=STRING}, resultType=STRING, body=CaseExpression{attributes=[false, true], children=[Comparison{attributes=[EQ], children=[FunctionCall{attributes=[CURRENT_USER], children=[]}, Literal{attributes=[STRING, alice, STRING], children=[]}]}, InputReference{attributes=[VALUE, STRING], children=[]}, Literal{attributes=[NULL, , null], children=[]}]}, quotedParameters=[], columnMask=true}
+
+=== truncate_to_year ===
+source: (value TIMESTAMP WITH TIME ZONE) RETURNS TIMESTAMP WITH TIME ZONE -> truncate_to_year(value)
+result: SqlDefinition{parameters={VALUE=TIMESTAMP WITH TIME ZONE}, resultType=TIMESTAMP WITH TIME ZONE, body=FunctionCall{attributes=[TRUNCATE_TO_YEAR], children=[InputReference{attributes=[VALUE, TIMESTAMP WITH TIME ZONE], children=[]}]}, quotedParameters=[], columnMask=true}
+
+=== truncate_to_month ===
+source: (value TIMESTAMP WITH TIME ZONE) RETURNS TIMESTAMP WITH TIME ZONE -> truncate_to_month(value)
+result: SqlDefinition{parameters={VALUE=TIMESTAMP WITH TIME ZONE}, resultType=TIMESTAMP WITH TIME ZONE, body=FunctionCall{attributes=[TRUNCATE_TO_MONTH], children=[InputReference{attributes=[VALUE, TIMESTAMP WITH TIME ZONE], children=[]}]}, quotedParameters=[], columnMask=true}
+
+=== invalid_rego ===
+source: filter := true
+error: Invalid restricted-sql-v1 definition at line 1, column 8: token recognition error at: ':'
+
+=== missing_declarations ===
+source: TRUE
+error: Invalid restricted-sql-v1 definition at line 1, column 1: mismatched input 'TRUE' expecting '('
+
+=== duplicate_parameters ===
+source: (x STRING, X STRING) RETURNS BOOLEAN -> TRUE
+error: Invalid restricted-sql-v1 definition at line 1, column 12: duplicate parameter X
+
+=== undeclared ===
+source: () RETURNS BOOLEAN -> x = 1
+error: Invalid restricted-sql-v1 definition at line 1, column 23: undeclared parameter X
+
+=== non_boolean ===
+source: () RETURNS BOOLEAN -> 1
+error: Invalid restricted-sql-v1 definition at line 1, column 23: Invalid restricted-sql-v1 expression: expected BOOLEAN, found NUMBER
+
+=== invalid_branch ===
+source: () RETURNS BOOLEAN -> CASE WHEN TRUE THEN TRUE ELSE 1 END
+error: Invalid restricted-sql-v1 definition at line 1, column 53: Invalid restricted-sql-v1 expression: expected BOOLEAN, found NUMBER
+
+=== invalid_mask ===
+source: (value STRING) RETURNS STRING -> show_last_4(value, 4)
+error: Invalid restricted-sql-v1 definition at line 1, column 34: Invalid restricted-sql-v1 expression: SHOW_LAST_4 requires exactly one argument
+
+=== unknown_function ===
+source: () RETURNS BOOLEAN -> unknown()
+error: Invalid restricted-sql-v1 definition at line 1, column 23: Unknown restricted-sql-v1 function: unknown
+
+=== integer_overflow ===
+source: (x INTEGER) RETURNS BOOLEAN -> x = 2147483648
+error: Invalid restricted-sql-v1 definition at line 1, column 36: Numeric literal does not fit INTEGER
+
+=== fractional_integer ===
+source: (x INTEGER) RETURNS BOOLEAN -> x = 1.1
+error: Invalid restricted-sql-v1 definition at line 1, column 36: Numeric literal does not fit INTEGER
+
+=== invalid_date ===
+source: () RETURNS BOOLEAN -> DATE '2025-02-29' IS NULL
+error: Invalid restricted-sql-v1 definition at line 1, column 23: Invalid temporal literal for DATE
+
+=== invalid_precision ===
+source: (x TIME(3)) RETURNS BOOLEAN -> TRUE
+error: Invalid restricted-sql-v1 definition at line 1, column 4: temporal precision must be 6
+
+=== invalid_pattern ===
+source: () RETURNS BOOLEAN -> 'x' LIKE '%x'
+error: Invalid restricted-sql-v1 definition at line 1, column 23: LIKE requires a non-empty fixed prefix followed by one %
+
+=== chained_comparison ===
+source: () RETURNS BOOLEAN -> 1 < 2 < 3
+error: Invalid restricted-sql-v1 definition at line 1, column 29: mismatched input '<' expecting {<EOF>, 'OR', 'AND'}
+
+=== numeric_boundary ===
+source: () RETURNS BOOLEAN -> 1and TRUE
+error: Invalid restricted-sql-v1 definition at line 1, column 23: numeric literal must end at a token boundary
+
+=== sql_comment ===
+source: () RETURNS BOOLEAN -> TRUE -- comment
+error: Invalid restricted-sql-v1 definition at line 1, column 28: token recognition error at: '--'
+
+=== invalid_quote ===
+source: () RETURNS BOOLEAN -> 'unterminated
+error: Invalid restricted-sql-v1 definition at line 1, column 23: token recognition error at: ''unterminated'
+
+=== unsupported_user_attribute_mask ===
+source: (value STRING) RETURNS STRING -> user_attribute('region')
+error: Invalid restricted-sql-v1 definition at line 1, column 34: Unknown restricted-sql-v1 function: user_attribute
+
+=== unsupported_user_attribute_unselected ===
+source: () RETURNS BOOLEAN -> CASE WHEN TRUE THEN TRUE ELSE user_attribute('active') END
+error: Invalid restricted-sql-v1 definition at line 1, column 53: Unknown restricted-sql-v1 function: user_attribute
diff --git a/core/src/test/resources/restricted-sql-v1-cases.txt b/core/src/test/resources/restricted-sql-v1-cases.txt
new file mode 100644
index 0000000000..a31f416f04
--- /dev/null
+++ b/core/src/test/resources/restricted-sql-v1-cases.txt
@@ -0,0 +1,77 @@
+# 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.
+
+eq row (x STRING) RETURNS BOOLEAN -> x = 'US'
+neq row (x STRING) RETURNS BOOLEAN -> x <> 'US'
+neq_alias row (x STRING) RETURNS BOOLEAN -> x != 'US'
+lt row (x STRING) RETURNS BOOLEAN -> x < 'US'
+lte row (x STRING) RETURNS BOOLEAN -> x <= 'US'
+gt row (x STRING) RETURNS BOOLEAN -> x > 'US'
+gte row (x STRING) RETURNS BOOLEAN -> x >= 'US'
+in row (x STRING) RETURNS BOOLEAN -> x IN ('US', 'CA', NULL)
+not_in row (x STRING) RETURNS BOOLEAN -> x NOT IN ('US', NULL)
+between row (x STRING) RETURNS BOOLEAN -> x BETWEEN 'A' AND 'Z'
+not_between row (x STRING) RETURNS BOOLEAN -> x NOT BETWEEN 'A' AND 'Z'
+is_null row (x STRING) RETURNS BOOLEAN -> x IS NULL
+is_not_null row (x STRING) RETURNS BOOLEAN -> x IS NOT NULL
+like row (x STRING) RETURNS BOOLEAN -> x LIKE 'Acme%'
+not_like row (x STRING) RETURNS BOOLEAN -> x NOT LIKE 'Acme%'
+precedence row (x STRING) RETURNS BOOLEAN -> NOT x = 'US' OR x IS NULL AND FALSE
+searched_case row (x STRING) RETURNS BOOLEAN -> CASE WHEN is_group_member('auditors') THEN x = 'US' ELSE x = CURRENT_USER() END
+simple_case row (x STRING) RETURNS BOOLEAN -> CASE x WHEN 'US' THEN TRUE WHEN NULL THEN FALSE END
+quoted_string row (x STRING) RETURNS BOOLEAN -> x = 'O''Brien\n😀'
+unsupported_user_attribute row (x STRING) RETURNS BOOLEAN -> x = user_attribute('region')
+quoted_identifier row ("Customer Region" STRING) RETURNS BOOLEAN -> "Customer Region" = 'US'
+nan row (x DOUBLE) RETURNS BOOLEAN -> is_nan(x)
+date_part row (x DATE) RETURNS BOOLEAN -> year(x) = 2026 AND month(x) = 3 OR day(x) = 15
+date row (x DATE) RETURNS BOOLEAN -> x = DATE '2024-02-29'
+time row (x TIME) RETURNS BOOLEAN -> x = TIME '12:30:00.123456'
+timestamp row (x TIMESTAMP) RETURNS BOOLEAN -> x = TIMESTAMP '2026-01-01 12:30:00'
+timestamp_zone row (x TIMESTAMP WITH TIME ZONE) RETURNS BOOLEAN -> x = TIMESTAMP WITH TIME ZONE '2026-01-01 12:30:00+00:00'
+integer_min row (x INTEGER) RETURNS BOOLEAN -> x = -2147483648
+long_max row (x LONG) RETURNS BOOLEAN -> x = 9223372036854775807
+decimal row (x DECIMAL(4,2)) RETURNS BOOLEAN -> x = 99.99
+mask_alphanum mask (value STRING) RETURNS STRING -> mask_alphanum(value)
+show_first_4 mask (value STRING) RETURNS STRING -> show_first_4(value)
+show_last_4 mask (value STRING) RETURNS STRING -> show_last_4(value)
+mask_to_fixed_value mask (value STRING) RETURNS STRING -> mask_to_fixed_value(value)
+replace_with_null mask (value STRING) RETURNS STRING -> replace_with_null(value)
+sha256_global mask (value STRING) RETURNS STRING -> sha256_global(value)
+sha256_query_local mask (value STRING) RETURNS STRING -> sha256_query_local(value)
+mask_nested mask (value STRING) RETURNS STRING -> show_last_4(mask_alphanum(value))
+mask_case mask (value STRING) RETURNS STRING -> CASE WHEN CURRENT_USER() = 'alice' THEN value ELSE NULL END
+truncate_to_year mask (value TIMESTAMP WITH TIME ZONE) RETURNS TIMESTAMP WITH TIME ZONE -> truncate_to_year(value)
+truncate_to_month mask (value TIMESTAMP WITH TIME ZONE) RETURNS TIMESTAMP WITH TIME ZONE -> truncate_to_month(value)
+invalid_rego row filter := true
+missing_declarations row TRUE
+duplicate_parameters row (x STRING, X STRING) RETURNS BOOLEAN -> TRUE
+undeclared row () RETURNS BOOLEAN -> x = 1
+non_boolean row () RETURNS BOOLEAN -> 1
+invalid_branch row () RETURNS BOOLEAN -> CASE WHEN TRUE THEN TRUE ELSE 1 END
+invalid_mask mask (value STRING) RETURNS STRING -> show_last_4(value, 4)
+unknown_function row () RETURNS BOOLEAN -> unknown()
+integer_overflow row (x INTEGER) RETURNS BOOLEAN -> x = 2147483648
+fractional_integer row (x INTEGER) RETURNS BOOLEAN -> x = 1.1
+invalid_date row () RETURNS BOOLEAN -> DATE '2025-02-29' IS NULL
+invalid_precision row (x TIME(3)) RETURNS BOOLEAN -> TRUE
+invalid_pattern row () RETURNS BOOLEAN -> 'x' LIKE '%x'
+chained_comparison row () RETURNS BOOLEAN -> 1 < 2 < 3
+numeric_boundary row () RETURNS BOOLEAN -> 1and TRUE
+sql_comment row () RETURNS BOOLEAN -> TRUE -- comment
+invalid_quote row () RETURNS BOOLEAN -> 'unterminated
+unsupported_user_attribute_mask mask (value STRING) RETURNS STRING -> user_attribute('region')
+unsupported_user_attribute_unselected row () RETURNS BOOLEAN -> CASE WHEN TRUE THEN TRUE ELSE user_attribute('active') END
diff --git a/dev/release/maven/LICENSE.antlr4 b/dev/release/maven/LICENSE.antlr4
new file mode 100644
index 0000000000..5d27694155
--- /dev/null
+++ b/dev/release/maven/LICENSE.antlr4
@@ -0,0 +1,28 @@
+Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+1. Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright
+notice, this list of conditions and the following disclaimer in the
+documentation and/or other materials provided with the distribution.
+
+3. Neither name of copyright holders nor the names of its contributors
+may be used to endorse or promote products derived from this software
+without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
+CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/dev/release/maven/README.md b/dev/release/maven/README.md
index fa82fbfbb5..9503d6be95 100644
--- a/dev/release/maven/README.md
+++ b/dev/release/maven/README.md
@@ -51,6 +51,8 @@ inventory. A dependency's POM license declaration may omit embedded third-party
## Sources for supplements
+- ANTLR runtime 4.13.2: [BSD-3-Clause LICENSE](https://github.com/antlr/antlr4/blob/4.13.2/LICENSE.txt);
+ the binary runtime JAR omits this text.
- Aliyun OSS 3.10.2/3.13.0: the exact Maven Central source JARs contain the same
BSD-2-Clause header in `com/aliyun/oss/common/utils/IniEditor.java`.
- Google API Client 1.24.1: its exact Maven Central source JAR contains a separate
diff --git a/dev/release/maven/dependencies.txt b/dev/release/maven/dependencies.txt
index f387c69da8..5c00ffe493 100644
--- a/dev/release/maven/dependencies.txt
+++ b/dev/release/maven/dependencies.txt
@@ -17,6 +17,7 @@
#
# Supplement only dependencies actually included in the artifact.
# Sources and audited versions are documented in README.md.
+org.antlr:antlr4-runtime:4.13.2=LICENSE.antlr4 | ANTLR4 runtime (BSD-3-Clause)
com.aliyun.oss:aliyun-sdk-oss:3.10.2=LICENSE.aliyun-inieditor | Aliyun OSS (Apache-2.0), including IniEditor (BSD-2-Clause)
com.aliyun.oss:aliyun-sdk-oss:3.13.0=LICENSE.aliyun-inieditor | Aliyun OSS (Apache-2.0), including IniEditor (BSD-2-Clause)
com.google.api-client:google-api-client:1.24.1=LICENSE.google-cloudshell | Google API Client (Apache-2.0), including CloudShellCredential (BSD-3-Clause)
diff --git a/docs/open-api/policies.yaml b/docs/open-api/policies.yaml
index 924eba053b..d8a8361017 100644
--- a/docs/open-api/policies.yaml
+++ b/docs/open-api/policies.yaml
@@ -577,11 +577,11 @@ components:
minLength: 1
pattern: '[\s\S]*\S[\s\S]*'
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.
+ A complete restricted-sql-v1 definition such as
+ `(region STRING) RETURNS BOOLEAN -> region = 'US'`.
+ Parameters must be declared and the body must return BOOLEAN. SQL CASE, predicates,
+ and allowlisted context and scalar functions are supported. The UTF-8 source must
+ not exceed 16 KiB; see the Policies documentation for grammar, types and limits.
ColumnMaskContent:
type: object
@@ -594,11 +594,12 @@ components:
minLength: 1
pattern: '[\s\S]*\S[\s\S]*'
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.
+ A complete restricted-sql-v1 definition such as
+ `(value STRING) RETURNS STRING -> show_last_4(value)`.
+ Exactly one parameter is required; its type must equal the return type. Its local
+ name is independent of the selected column name. The body may use SQL CASE,
+ literals, NULL, and allowlisted functions. The UTF-8 source must not exceed 16 KiB;
+ see the Policies documentation for grammar, types and limits.
AccessControlContent:
type: object
diff --git a/docs/policies.md b/docs/policies.md
index 3183612f6a..81954f9b61 100644
--- a/docs/policies.md
+++ b/docs/policies.md
@@ -40,79 +40,240 @@ policy. A table with only `data_domain=risk` does not.
| `system_iceberg_compaction` | Compaction thresholds and scheduling | Table maintenance service |
| `system_iceberg_rewrite_manifests` | Manifest count and average-size thresholds | Table maintenance service |
| `system_iceberg_orphan_file_removal` | Orphan-file cleanup options | Table maintenance service |
-| `system_row_filter` | Row-filter expression | Not enforced yet |
-| `system_column_mask` | Column-mask expression | Not enforced yet |
+| `system_row_filter` | Row-filter expression | Experimental Iceberg REST |
+| `system_column_mask` | Column-mask expression | Experimental Iceberg REST |
| `system_access_control` | Privileges and applicable roles | Not enforced yet |
| `custom` | A free-form map that you define | A system that you provide |
-The row-filter, column-mask, and access-control policy types can be created and associated with
-tags, but Gravitino does not enforce them yet. Until enforcement is available, these policy types
-do not restrict data access.
+Row-filter and column-mask policies can be associated with tags and returned as read restrictions
+by the experimental Iceberg REST service. Compatible readers enforce those restrictions. The
+stable service does not load the experimental provider by default. Access-control policy
+enforcement remains separate.
### 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.
+Row-filter and column-mask expressions use `restricted-sql-v1`. A complete definition declares
+its parameters and result type before the SQL body:
-The complete grammar is:
+```sql
+(region STRING, owner STRING) RETURNS BOOLEAN -> CASE
+ WHEN is_group_member('auditors') THEN region = 'US'
+ ELSE owner = CURRENT_USER()
+END
+```
+
+```sql
+(value STRING) RETURNS STRING -> CASE
+ WHEN CURRENT_USER() = 'alice' THEN value
+ ELSE show_last_4(value)
+END
+```
+
+The server validates complete definitions on policy creation and content updates. Ordinary policy
+metadata reads, renames, and comment updates do not reparse source. The experimental Iceberg REST
+loader binds applicable SQL definitions to the request identity and table schema, validates target
+nullability, and converts supported expressions to closed Iceberg read restrictions.
+
+#### Types and Operators
+
+Supported declaration types are `BOOLEAN`, signed `INTEGER` and `LONG`, `FLOAT`, `DOUBLE`,
+`DECIMAL(p,s)`, `STRING`, `BINARY`, `DATE`, `TIME(6)` and `TIMESTAMP(6)` with or without time zone.
+Decimal precision is 1–38 and scale is 0–precision. Omitted temporal precision means 6.
+Numeric literals retain exact decimal text until conversion. Overflow, rounding, and implicit
+cross-family conversions are rejected. Temporal literals use `DATE '2026-01-01'`, `TIME '12:30:00'`,
+`TIMESTAMP '2026-01-01 12:30:00'`, or
+`TIMESTAMP WITH TIME ZONE '2026-01-01 12:30:00+00:00'`.
+
+The expression body supports:
+
+- Comparisons `=`, `<>` (`!=`), `<`, `<=`, `>`, `>=` between compatible scalar values.
+- `IS NULL` and `IS NOT NULL`; Boolean equality and membership, without ordering.
+- `IN` and `NOT IN` with non-empty literal lists, including NULL members.
+- Inclusive `BETWEEN` and `NOT BETWEEN` ranges.
+- `LIKE` and `NOT LIKE` with a non-empty fixed prefix followed by exactly one `%`.
+ Other `%` positions, `_` wildcards and `ESCAPE` are rejected.
+- `NOT`, `AND`, `OR`, in that precedence order after predicates; parentheses may nest.
+- Searched `CASE WHEN condition THEN result ... ELSE result END` and simple
+ `CASE selector WHEN match THEN result ... ELSE result END`. ELSE is optional.
+
+#### Identifiers and Literals
+
+Keywords and built-in function names are case-insensitive. Unquoted identifiers use ASCII
+letters or underscore followed by letters, digits or underscores, and normalize to uppercase.
+Double-quoted identifiers preserve case; double a quote to escape it. Parameter names must be
+unique after normalization. String literals use single quotes, with doubled single quotes for
+escaping. Backslashes are literal and Unicode is preserved; isolated surrogates and NUL are rejected.
+Comments, statements, semicolons, casts, arithmetic, qualified names, nested fields, subqueries,
+unknown functions, exponents, leading `+`, leading zeroes and trailing decimal points are rejected.
+
+#### Resource Limits
+
+Limits apply before normalization and serve different purposes:
+
+| Resource | Limit |
+| ------------------------------------------------------------- | --------------- |
+| Complete definition, including declarations | 16 KiB of UTF-8 |
+| Expression nodes | 1024 |
+| Operation depth, including CASE and function calls | 16 |
+| IN elements, both per list and across the complete definition | 1000 |
+| Parenthesis nesting | 64 |
+| Declared parameters | 256 |
+| Each decoded quoted identifier or string literal | 4 KiB of UTF-8 |
+| Each numeric literal | 256 bytes |
+
+Node and IN limits allow ordinary SQL predicates and membership lists while bounding parsing and
+validation work. Depth limits bound recursive operations independently of expression width. A
+consecutive AND/OR chain is one n-ary operation; parentheses alone add no AST nodes or operation
+depth. Literal lists and every CASE arm count toward the node limit even if a branch is unreachable.
+
+#### Complete SQL Grammar
+
+The stored definition must match this grammar and consume the complete input. Keywords and
+allowlisted function names are case-insensitive; arbitrary function names remain invalid.
```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
+definition := "(" (parameter ("," parameter)*)? ")" RETURNS type "->" expr EOF
+parameter := identifier type
+type := BOOLEAN | INTEGER | LONG | FLOAT | DOUBLE | STRING | BINARY | DATE
+ | DECIMAL "(" unsignedInteger "," unsignedInteger ")"
+ | TIME ("(" "6" ")")?
+ | TIMESTAMP ("(" "6" ")")? ((WITH | WITHOUT) TIME ZONE)?
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"
+orExpr := andExpr (OR andExpr)*
+andExpr := notExpr (AND notExpr)*
+notExpr := NOT* predicate
+predicate := scalar (compareOp scalar
+ | IS NOT? NULL
+ | NOT? IN "(" literal ("," literal)* ")"
+ | NOT? BETWEEN scalar AND scalar
+ | NOT? LIKE string)?
+scalar := identifier | literal | functionCall | caseExpr | "(" expr ")"
+functionCall := identifier "(" (expr ("," expr)*)? ")"
+caseExpr := CASE expr? (WHEN expr THEN expr)+ (ELSE expr)? END
+compareOp := "=" | "<>" | "!=" | "<" | "<=" | ">" | ">="
+literal := string | number | TRUE | FALSE | NULL | temporal
+temporal := (DATE | TIME | TIMESTAMP) string | TIMESTAMP WITH TIME ZONE string
number := "-"? ("0" | nonZeroDigit digit*) ("." digit+)?
+unsignedInteger := "0" | nonZeroDigit digit*
digit := "0" | nonZeroDigit
nonZeroDigit := "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
+identifier := unquotedIdentifier | quotedIdentifier
+unquotedIdentifier := (asciiLetter | "_") (asciiLetter | digit | "_")*
+quotedIdentifier := '"' (nonDoubleQuote | '""')+ '"'
+string := "'" (nonSingleQuote | "''")* "'"
```
-For example, a row-filter program can select the first matching predicate:
+`asciiLetter` means A–Z or a–z. Keywords shown in the grammar are reserved; quote them when used
+as parameter names. Quoted identifiers and strings preserve Unicode and decode doubled quotes
+once. There is no backslash escape layer inside SQL literals. Every number must end at a token
+boundary: `1and TRUE` is invalid. The `AND` in `BETWEEN` separates its two scalar bounds;
+`NOT active = TRUE` means `NOT (active = TRUE)`. Chained comparisons are invalid.
-```restricted-rego-v1
-filter := col("region") == "US" if is_group_member("auditors")
-else := col("owner") == session_user()
-```
+#### Result Types and Binding Contract
-This column-mask program selects a masking action in the same way:
+A row filter declares zero or more parameters and returns BOOLEAN. Each input must resolve to
+exactly one table column under the identifier matching rules; each declared type must match exactly.
+Missing, ambiguous or mismatched inputs are errors. A context-only filter can declare no inputs:
-```restricted-rego-v1
-mask := action("show-last-4") if is_group_member("support")
-else := action("replace-with-null")
+```sql
+() RETURNS BOOLEAN -> is_group_member('auditors')
```
-When the experimental Iceberg REST read-restriction loader resolves several row-filter policies
-for one table, a filter that resolves to `true` adds no restriction and is ignored. Identical
-effective filters are deduplicated. Distinct restrictive filters conflict and cause the load-table
-request to fail; the loader does not combine them.
+A column mask has exactly one local parameter and the same result type, including decimal
+precision/scale and timestamp time-zone characteristics. Binding applies that parameter to the
+selected column regardless of its physical name and inherits that column's nullability. A physical
+name that was not declared is not an alias. For example, this can mask either `phone_number` or
+`card`, provided its selected column has type STRING:
+
+```sql
+(value STRING) RETURNS STRING -> show_last_4(value)
+```
-If the selected column-mask action is not applicable to a column type, the experimental loader
-fails the load-table request rather than omitting the mask and exposing the original values.
-Unselected actions do not need to be applicable to that column. For example, `replace-with-null`
-cannot apply to a required column when that action is selected.
+BINARY supports null tests and compatible scalar masks, but no value comparisons. BOOLEAN
+supports equality and membership; all other supported predicate types also support ordering and
+ranges. Temporal literals require matching type keywords, valid calendar/clock values and at most
+six fractional digits; timestamp-with-timezone literals require an explicit offset. Integer
+literals must fit the signed range and be mathematical integers. Decimals must fit without
+rounding. Floating-point literals retain negative zero and reject overflow, infinity and NaN.
+Strings compare lexicographically by Unicode code point, case-sensitively and without Unicode
+normalization. Constant/context comparisons and bound STRING column predicates use the same order.
+
+#### CASE and SQL NULL Semantics
+
+A searched CASE evaluates conditions in source order; only TRUE selects a branch. FALSE and
+UNKNOWN skip it. A simple CASE compares its selector with each match using SQL equality, so a
+NULL selector does not match a NULL match value. Only the selected result is evaluated. If no arm
+matches, CASE returns ELSE, or SQL NULL when ELSE is absent. Every result arm is statically type
+checked, including unreachable arms. Nested CASE and function calls obey the same limits.
+
+A filter retains rows only when its result is TRUE. These are SQL three-valued rules:
+
+| Expression | Result |
+| ----------------------------------------- | --------------- |
+| `NULL IS NULL` / `NULL IS NOT NULL` | TRUE / FALSE |
+| Comparison with a NULL operand | UNKNOWN |
+| `NOT NULL` | UNKNOWN |
+| `FALSE AND NULL` / `TRUE AND NULL` | FALSE / UNKNOWN |
+| `TRUE OR NULL` / `FALSE OR NULL` | TRUE / UNKNOWN |
+| NULL input to IN, BETWEEN, LIKE or is_nan | UNKNOWN |
+| Nonmatching IN list containing NULL | UNKNOWN |
+| Nonmatching NOT IN list containing NULL | UNKNOWN |
+
+For example, both `region <> 'US'` and `NOT (region = 'US')` exclude null regions. Use
+`region IS NULL OR region <> 'US'` to include them. A constant FALSE filter returns no rows.
+All mask result arms must match the declared type. A mask that can return NULL, including an
+unselected NULL arm or an omitted ELSE, requires a nullable target. Schema binding rejects such a
+mask for a required column. Target conversion and context lookups evaluate only selected CASE
+results and stop evaluating later conditions after a match.
+
+#### Function Contract
+
+`CURRENT_USER()` returns the non-null STRING name of the trusted effective subject. Context
+values remain stable for a conversion.
+`is_group_member('group')` returns BOOLEAN for exact flat membership in the current metalake.
+An unknown group, unavailable subject or failed lookup is an error; an existing group without
+the subject returns FALSE. Group names must be non-empty string literals. Nested group expansion
+is unsupported.
+
+User attributes and implicit string-to-number conversions are unsupported.
+
+The predicate `is_nan(value)` accepts FLOAT or DOUBLE and preserves null input. Date parts
+`year`, `month`, and `day` accept DATE or TIMESTAMP, return INTEGER and preserve null input.
+Timestamp-with-timezone values use UTC; timestamps without timezone use their recorded calendar
+fields. Dates use the proleptic Gregorian calendar. `month(order_date) = 3` means March in any year.
+
+Mask function behavior is as follows; each call takes one compatible scalar argument and preserves
+its input logical type:
+
+| Function | Input type | Behavior |
+| ---------------------------------------- | --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
+| `mask_alphanum` | STRING | ASCII digits become `n`; `(),.@-` are preserved; other Unicode code points become `x` |
+| `show_first_4` / `show_last_4` | STRING | Preserve the first/last four code points and mask the remainder as above; strings of four or fewer code points are unchanged |
+| `mask_to_fixed_value` | STRING, numeric, BOOLEAN, DATE or TIMESTAMP | Return `XXXXXXXX` for STRING, zero for numeric values, FALSE for BOOLEAN, or the epoch date/timestamp, including for null input |
+| `replace_with_null` | Any typed scalar | Return a typed null |
+| `truncate_to_year` / `truncate_to_month` | DATE or TIMESTAMP | Truncate to the start of the year/month, using UTC for timestamps with time zone |
+| `sha256_global` / `sha256_query_local` | STRING, signed INTEGER, signed LONG or BINARY | Type-preserving SHA-256; the query-local variant prepends a cryptographically random salt of at least 16 bytes, shared within one query |
+
+All masks except `mask_to_fixed_value` preserve null input. Hash input encoding is UTF-8 for
+strings, little-endian two's-complement for signed integers, and raw bytes for BINARY. STRING
+results are 64 lowercase hexadecimal characters; INTEGER/LONG results are the first four/eight
+digest bytes interpreted as signed little-endian; BINARY results contain the complete 32-byte
+digest. Separate queries require independent query-local salts.
+
+#### Validation Boundary
+
+ANTLR parses the complete stored definition, then an AST visitor builds separate typed operation
+nodes. Static validation checks parameter/result declarations, unique names, available local
+references, every CASE arm, operand types, allowlisted calls and arguments, exact literal ranges,
+and source limits. Golden fixtures pin parsed ASTs and rejected-input diagnostics.
+
+The parser does not execute expressions. The experimental converter binds every declared input
+before selecting branches, checks exact schema types and mask nullability, snapshots the effective
+subject, and caches trusted group lookups for a conversion. Any binding, translation or
+capability error fails the governed load; an unsupported restriction never becomes an unrestricted
+response.
+
+#### Experimental Iceberg Conversion
Experimental Iceberg REST read restrictions require authorization to be enabled with
`gravitino.authorization.enable=true` and a policy dispatcher to be available. When a policy dispatcher
@@ -133,92 +294,49 @@ metadata-object API reserves `.` as a qualified-name separator, so a tag cannot
directly to such an object. The loader returns HTTP 400 for these names even when no policy is
assigned. A standalone service without a policy dispatcher does not perform policy resolution.
-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,
-[Iceberg manifest rewrite policy](./iceberg-rewrite-manifests-policy.md) for manifest thresholds, and
-[Table maintenance service](./table-maintenance-service/optimizer.md) for a worked example.
-
-Policy content also has `properties` and `supportedObjectTypes`. Properties describe the policy
-itself, such as its owner or consumer. `supportedObjectTypes` is required when creating a custom
-policy. A custom policy content update replaces the whole content and can change this field; for a
-built-in policy, the field cannot be changed after creation. Object policy lookup does not filter
-by this field; each consumer decides whether a policy type applies to the object it is processing.
+When the experimental Iceberg REST read-restriction loader resolves several row-filter policies
+for one table, a filter that resolves to `true` adds no restriction and is ignored. Identical
+effective filters are deduplicated. Distinct restrictive filters conflict and cause the load-table
+request to fail; the loader does not combine them.
+
+The current converter supports the following enforcement subset of the shared SQL grammar:
+
+| SQL form | Iceberg conversion |
+| ------------------------------------------------------------------------ | ----------------------------------------------------------------------- |
+| Column and compatible literal/context scalar comparison | Bound field-ID predicate, preserving SQL NULL semantics |
+| Boolean inputs, AND/OR/NOT and Boolean comparisons | Three-valued lowering; only TRUE retains a row |
+| IN/NOT IN, BETWEEN/NOT BETWEEN, null tests, prefix LIKE and NaN tests | Closed native predicates with explicit unknown handling |
+| Searched/simple Boolean CASE and scalar CASE inside supported predicates | Ordered conditional lowering; false and unknown conditions fall through |
+| `year(date_or_timestamp_column)` | Iceberg year transform with calendar-year literal adjustment |
+| `month`/`day` on constant temporal values | Evaluated as scalar constants |
+| Mask returning its local input | No projection, preserving the original selected column |
+| NULL or `replace_with_null` | Null projection on a nullable column |
+| One of the nine direct mask functions applied to the local input | Corresponding Iceberg projection |
+| A literal equal to the target type's fixed mask value | Fixed-value projection |
+| Mask CASE using conditions that resolve to constants after binding | First matching compatible projection |
+
+General column-to-column comparisons, month/day extraction from row values, row-dependent mask
+selection, composed mask calls and arbitrary literal mask values are not representable by the
+current closed target and are rejected. An incompatible selected mask fails the table load. A SQL
+mask parameter binds to the selected column by field ID, independently of its local name. Quoted
+row-filter declarations match exact physical names; unquoted declarations match case-folded names
+and reject ambiguous matches.
+
+Source limits still apply. Conversion additionally bounds generated Iceberg expressions to 16384
+nodes and depth 256, and bounds compilation work. This protects conditional lowering and
+serialization independently of source width. Exceeding a target limit rejects the load. Closed
+filters and mask projections are canonicalized deterministically for deduplication, conflict
+checks and response ETags.
### Policy-to-Tag Associations
Each association connects one policy to one tag and stores a selector. The selector determines
whether that association contributes the policy to an object's lookup result.
-| Selector | When it matches |
-|--------------|--------------------------------------------------------------------------|
-| `ALL_VALUES` | The effective tag is present, including an assignment without a value. |
-| `TAG_VALUE` | One of the effective tag assignment values equals the specified value. |
+| Selector | When it matches |
+| ------------ | ---------------------------------------------------------------------- |
+| `ALL_VALUES` | The effective tag is present, including an assignment without a value. |
+| `TAG_VALUE` | One of the effective tag assignment values equals the specified value. |
A policy may be associated with multiple tags. Association listings show those direct relations
and their selectors, even if no object currently matches them. An object policy lookup returns each
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 0c90a42a6f..80fabd5aaa 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -17,6 +17,7 @@
# under the License.
#
[versions]
+antlr = "4.13.2"
db-scheduler = "16.12.0"
awssdk = "2.31.73"
azure-identity = "1.13.1"
@@ -194,6 +195,9 @@ aspectj = "1.9.24"
ql-expression = "4.0.3"
[libraries]
+jsr305 = { module = "com.google.code.findbugs:jsr305", version = "3.0.2" }
+antlr-tool = { module = "org.antlr:antlr4", version.ref = "antlr" }
+antlr-runtime = { module = "org.antlr:antlr4-runtime", version.ref = "antlr" }
db-scheduler = { group = "com.github.kagkarlsson", name = "db-scheduler", version.ref = "db-scheduler" }
aspectj-aspectjrt = { group = "org.aspectj", name = "aspectjrt", version.ref = "aspectj" }
aws-dynamodb = { group = "software.amazon.awssdk", name = "dynamodb", version.ref = "awssdk" }
diff --git a/iceberg/iceberg-rest-server-experiment/build.gradle.kts b/iceberg/iceberg-rest-server-experiment/build.gradle.kts
index e83528a56f..49937bfb29 100644
--- a/iceberg/iceberg-rest-server-experiment/build.gradle.kts
+++ b/iceberg/iceberg-rest-server-experiment/build.gradle.kts
@@ -51,6 +51,7 @@ configurations.configureEach {
}
dependencies {
+ compileOnly(libs.jsr305)
implementation(project(":api"))
implementation(project(":common")) {
exclude("*")
@@ -66,6 +67,7 @@ dependencies {
testImplementation(libs.junit.jupiter.api)
testImplementation(libs.mockito.core)
+ testCompileOnly(libs.jsr305)
testRuntimeOnly(libs.junit.jupiter.engine)
}
diff --git a/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/ExperimentalIcebergReadRestrictionLoader.java b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/ExperimentalIcebergReadRestrictionLoader.java
index 19b13ac185..e02c73af61 100644
--- a/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/ExperimentalIcebergReadRestrictionLoader.java
+++ b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/ExperimentalIcebergReadRestrictionLoader.java
@@ -44,9 +44,8 @@ import org.apache.gravitino.policy.ColumnMaskContent;
import org.apache.gravitino.policy.Policy;
import org.apache.gravitino.policy.PolicyDispatcher;
import org.apache.gravitino.policy.RowFilterContent;
-import org.apache.gravitino.policy.rego.RestrictedRegoExpressionParserFacade;
-import org.apache.gravitino.policy.rego.RestrictedRegoProgram.ColumnMask;
-import org.apache.gravitino.policy.rego.RestrictedRegoProgram.RowFilter;
+import org.apache.gravitino.policy.sql.RestrictedSqlExpressionParserFacade;
+import org.apache.gravitino.policy.sql.SqlDefinition;
import org.apache.gravitino.utils.HierarchicalSchemaUtil;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.PrincipalUtils;
@@ -155,8 +154,8 @@ public final class ExperimentalIcebergReadRestrictionLoader
Map<Integer, PolicyEntity[]> columnPolicies,
Schema schema,
IcebergReadRestrictionConverter.BindingContext bindingContext) {
- Optional<RowFilter> rowFilter = resolveRowFilter(tablePolicies, schema, bindingContext);
- Map<Integer, ColumnMask> columnMasks =
+ Optional<SqlDefinition> rowFilter = resolveRowFilter(tablePolicies, schema, bindingContext);
+ Map<Integer, SqlDefinition> columnMasks =
resolveColumnMasks(columnPolicies, schema, bindingContext);
return IcebergReadRestrictionConverter.convert(rowFilter, columnMasks, schema, bindingContext);
}
@@ -175,17 +174,17 @@ public final class ExperimentalIcebergReadRestrictionLoader
}
}
- private static Optional<RowFilter> resolveRowFilter(
+ private static Optional<SqlDefinition> resolveRowFilter(
PolicyEntity[] policies,
Schema schema,
IcebergReadRestrictionConverter.BindingContext bindingContext) {
- Map<String, RowFilter> distinct = new LinkedHashMap<>();
+ Map<String, SqlDefinition> distinct = new LinkedHashMap<>();
for (PolicyEntity policy : policies) {
if (policy.policyType() != Policy.BuiltInType.ROW_FILTER) {
continue;
}
- RowFilter program =
- RestrictedRegoExpressionParserFacade.parseRowFilter(
+ SqlDefinition program =
+ RestrictedSqlExpressionParserFacade.parseRowFilter(
((RowFilterContent) policy.content()).expression());
ReadRestrictions resolved =
IcebergReadRestrictionConverter.convert(
@@ -202,21 +201,21 @@ public final class ExperimentalIcebergReadRestrictionLoader
return distinct.values().stream().findFirst();
}
- private static Map<Integer, ColumnMask> resolveColumnMasks(
+ private static Map<Integer, SqlDefinition> resolveColumnMasks(
Map<Integer, PolicyEntity[]> policiesByField,
Schema schema,
IcebergReadRestrictionConverter.BindingContext bindingContext) {
- Map<Integer, ColumnMask> resolvedMasks = new HashMap<>();
+ Map<Integer, SqlDefinition> resolvedMasks = new HashMap<>();
List<Integer> fieldIds = new ArrayList<>(policiesByField.keySet());
Collections.sort(fieldIds);
for (Integer fieldId : fieldIds) {
- Map<String, ColumnMask> distinct = new LinkedHashMap<>();
+ Map<String, SqlDefinition> distinct = new LinkedHashMap<>();
for (PolicyEntity policy : policiesByField.get(fieldId)) {
if (policy.policyType() != Policy.BuiltInType.COLUMN_MASK) {
continue;
}
- ColumnMask program =
- RestrictedRegoExpressionParserFacade.parseColumnMask(
+ SqlDefinition program =
+ RestrictedSqlExpressionParserFacade.parseColumnMask(
((ColumnMaskContent) policy.content()).expression());
ReadRestrictions resolved =
IcebergReadRestrictionConverter.convert(
diff --git a/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/IcebergReadRestrictionConverter.java b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/IcebergReadRestrictionConverter.java
index 38a26cfb79..c3dc7b4c3f 100644
--- a/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/IcebergReadRestrictionConverter.java
+++ b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/IcebergReadRestrictionConverter.java
@@ -18,749 +18,95 @@
*/
package org.apache.gravitino.iceberg.service.restriction;
-import java.math.BigDecimal;
-import java.math.RoundingMode;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.LocalTime;
-import java.time.format.DateTimeParseException;
-import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
-import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
-import java.util.TreeMap;
-import org.apache.gravitino.policy.rego.CanonicalExpression;
-import org.apache.gravitino.policy.rego.Column;
-import org.apache.gravitino.policy.rego.Comparison;
-import org.apache.gravitino.policy.rego.ComparisonOperator;
-import org.apache.gravitino.policy.rego.GroupMembership;
-import org.apache.gravitino.policy.rego.Literal;
-import org.apache.gravitino.policy.rego.LiteralArray;
-import org.apache.gravitino.policy.rego.LiteralType;
-import org.apache.gravitino.policy.rego.LogicalExpression;
-import org.apache.gravitino.policy.rego.LogicalOperator;
-import org.apache.gravitino.policy.rego.Not;
-import org.apache.gravitino.policy.rego.RestrictedRegoProgram.ColumnMask;
-import org.apache.gravitino.policy.rego.RestrictedRegoProgram.MaskAction;
-import org.apache.gravitino.policy.rego.RestrictedRegoProgram.MaskBranch;
-import org.apache.gravitino.policy.rego.RestrictedRegoProgram.RowFilter;
-import org.apache.gravitino.policy.rego.SessionUser;
+import org.apache.gravitino.policy.sql.SqlDefinition;
import org.apache.iceberg.Schema;
-import org.apache.iceberg.expressions.Binder;
import org.apache.iceberg.expressions.Expression;
-import org.apache.iceberg.expressions.ExpressionParser;
-import org.apache.iceberg.expressions.Expressions;
import org.apache.iceberg.functions.IcebergFunction;
-import org.apache.iceberg.functions.IcebergFunctions;
import org.apache.iceberg.rest.restrictions.ReadRestrictions;
-import org.apache.iceberg.types.Type;
import org.apache.iceberg.types.Types;
-/** Converts validated restricted Rego programs to closed Iceberg read restrictions. */
+/** Converts validated typed SQL definitions to closed Iceberg read restrictions. */
public final class IcebergReadRestrictionConverter {
-
private IcebergReadRestrictionConverter() {}
- /** Trusted request context used while binding a restriction. */
+ /** Trusted request-scoped identity and group lookups used while binding SQL expressions. */
public interface BindingContext {
-
/**
- * Returns the authenticated effective user name.
+ * Returns the authenticated effective user's name.
*
- * @return non-empty effective user name
+ * @return the non-empty authenticated effective user name
*/
String sessionUser();
/**
* Resolves exact flat membership in the current metalake.
*
- * <p>An empty result means that the group is unknown or membership could not be resolved. The
- * converter treats that result as an error rather than non-membership.
- *
- * @param group exact group name from the policy expression
- * @return membership when the group and identity snapshot were resolved
+ * @param group exact group name
+ * @return membership, or empty when the group or identity could not be resolved
*/
Optional<Boolean> groupMembership(String group);
}
/**
- * Binds parsed policy programs to a request context and table schema.
+ * Binds SQL policies to a trusted identity and concrete top-level schema fields. SQL three-valued
+ * logic is preserved; only TRUE retains a row. Identity masks and constant-true filters are
+ * omitted. Unsupported target expressions fail conversion instead of removing a required
+ * restriction.
*
- * <p>The returned restriction contains no symbolic column names or context functions. Constant
- * true row filters are omitted, while constant false filters are retained.
- *
- * @param rowFilter optional effective row-filter program
- * @param columnMasks effective column-mask programs keyed by top-level Iceberg field ID
- * @param schema concrete Iceberg table schema
- * @param context trusted request context
- * @return closed Iceberg read restrictions
- * @throws IllegalArgumentException if any applicable restriction cannot be bound exactly
+ * @param rowFilter optional validated row-filter definition
+ * @param columnMasks validated mask definitions keyed by selected top-level field ID
+ * @param schema target Iceberg schema
+ * @param context trusted identity and group provider
+ * @return closed read restrictions with stable field IDs
+ * @throws IllegalArgumentException if binding or exact target translation is unavailable
*/
public static ReadRestrictions convert(
- Optional<RowFilter> rowFilter,
- Map<Integer, ColumnMask> columnMasks,
+ Optional<SqlDefinition> rowFilter,
+ Map<Integer, SqlDefinition> columnMasks,
Schema schema,
BindingContext context) {
Objects.requireNonNull(rowFilter, "rowFilter cannot be null");
Objects.requireNonNull(columnMasks, "columnMasks cannot be null");
Objects.requireNonNull(schema, "schema cannot be null");
- ResolutionContext resolutionContext = new ResolutionContext(context);
-
- Expression resolvedRowFilter = null;
+ SqlRestrictionBinding.Context snapshot = new SqlRestrictionBinding.Context(context);
+ Expression filter = null;
if (rowFilter.isPresent()) {
- RowFilter filter = rowFilter.get();
- filter.validate();
- ResolvedPredicate resolved = resolvePredicate(filter.lower(), schema, resolutionContext);
- if (resolved.expression().op() != Expression.Operation.TRUE) {
- resolvedRowFilter = resolved.expression();
+ SqlDefinition definition = rowFilter.get();
+ SqlRestrictionBinding binding = new SqlRestrictionBinding(definition, schema, snapshot, null);
+ Expression converted =
+ new SqlRestrictionPredicates(binding).resolve(definition.body()).trueExpression();
+ converted = SqlRestrictionCanonicalizer.canonicalize(converted);
+ if (converted.op() != Expression.Operation.TRUE) {
+ filter = converted;
}
}
-
- List<Map.Entry<Integer, ColumnMask>> orderedMasks = new ArrayList<>(columnMasks.entrySet());
- for (Map.Entry<Integer, ColumnMask> entry : orderedMasks) {
+ List<Map.Entry<Integer, SqlDefinition>> ordered = new ArrayList<>(columnMasks.entrySet());
+ for (Map.Entry<Integer, SqlDefinition> entry : ordered) {
if (entry.getKey() == null || entry.getValue() == null) {
- throw new IllegalArgumentException("column mask field ID and program cannot be null");
+ throw new IllegalArgumentException("Mask field ID and definition cannot be null");
}
}
- orderedMasks.sort(Map.Entry.comparingByKey());
-
+ ordered.sort(Map.Entry.comparingByKey());
List<IcebergFunction<?, ?>> projections = new ArrayList<>();
- for (Map.Entry<Integer, ColumnMask> entry : orderedMasks) {
- Types.NestedField field = topLevelField(schema, entry.getKey());
- MaskAction action = resolveMaskAction(entry.getValue(), schema, resolutionContext);
- projections.add(toIcebergFunction(action, field));
- }
-
- ReadRestrictions restrictions = ReadRestrictions.of(resolvedRowFilter, projections);
+ for (Map.Entry<Integer, SqlDefinition> entry : ordered) {
+ Types.NestedField field = SqlRestrictionBinding.field(schema, entry.getKey());
+ SqlRestrictionBinding binding =
+ new SqlRestrictionBinding(entry.getValue(), schema, snapshot, field);
+ IcebergFunction<?, ?> projection =
+ new SqlRestrictionMasks(field, new SqlRestrictionPredicates(binding))
+ .resolve(entry.getValue().body());
+ if (projection != null) {
+ projections.add(projection);
+ }
+ }
+ ReadRestrictions restrictions = ReadRestrictions.of(filter, projections);
restrictions.validate(Collections.singletonMap(schema.schemaId(), schema));
return restrictions;
}
-
- private static ResolvedPredicate resolvePredicate(
- CanonicalExpression expression, Schema schema, ResolutionContext context) {
- expression.validate();
- if (expression instanceof Literal) {
- Literal literal = (Literal) expression;
- if (literal.literalType() != LiteralType.BOOLEAN) {
- throw new IllegalArgumentException("row-filter literal must be Boolean");
- }
- return constant((Boolean) literal.value());
- }
- if (expression instanceof GroupMembership) {
- return constant(resolveGroup((GroupMembership) expression, context));
- }
- if (expression instanceof Comparison) {
- return resolveComparison((Comparison) expression, schema, context);
- }
- if (expression instanceof Not) {
- ResolvedPredicate child = resolvePredicate(((Not) expression).operand(), schema, context);
- if (child.expression().op() == Expression.Operation.TRUE) {
- return constant(false);
- }
- if (child.expression().op() == Expression.Operation.FALSE) {
- return constant(true);
- }
- return resolved(Expressions.not(child.expression()));
- }
- if (expression instanceof LogicalExpression) {
- return resolveLogical((LogicalExpression) expression, schema, context);
- }
- throw new IllegalArgumentException(
- "Unsupported predicate node after restricted Rego parsing: "
- + expression.getClass().getSimpleName());
- }
-
- private static ResolvedPredicate resolveLogical(
- LogicalExpression logical, Schema schema, ResolutionContext context) {
- List<ResolvedPredicate> resolvedChildren = new ArrayList<>();
- for (CanonicalExpression operand : logical.operands()) {
- resolvedChildren.add(resolvePredicate(operand, schema, context));
- }
-
- Map<String, ResolvedPredicate> children = new TreeMap<>();
- boolean absorbingConstant = false;
- for (ResolvedPredicate child : resolvedChildren) {
- if (logical.operator() == LogicalOperator.AND) {
- if (child.expression().op() == Expression.Operation.FALSE) {
- absorbingConstant = true;
- continue;
- }
- if (child.expression().op() == Expression.Operation.TRUE) {
- continue;
- }
- } else {
- if (child.expression().op() == Expression.Operation.TRUE) {
- absorbingConstant = true;
- continue;
- }
- if (child.expression().op() == Expression.Operation.FALSE) {
- continue;
- }
- }
- children.put(child.signature(), child);
- }
-
- if (absorbingConstant) {
- return constant(logical.operator() == LogicalOperator.OR);
- }
-
- if (children.isEmpty()) {
- return constant(logical.operator() == LogicalOperator.AND);
- }
- if (children.size() == 1) {
- return children.values().iterator().next();
- }
-
- Expression combined = null;
- for (ResolvedPredicate child : children.values()) {
- if (combined == null) {
- combined = child.expression();
- } else if (logical.operator() == LogicalOperator.AND) {
- combined = Expressions.and(combined, child.expression());
- } else {
- combined = Expressions.or(combined, child.expression());
- }
- }
- return resolved(Objects.requireNonNull(combined, "logical expression cannot be empty"));
- }
-
- private static ResolvedPredicate resolveComparison(
- Comparison comparison, Schema schema, ResolutionContext context) {
- CanonicalExpression left = comparison.left();
- CanonicalExpression right = comparison.right();
- ComparisonOperator operator = comparison.operator();
-
- if (left instanceof SessionUser) {
- return resolveSessionComparison(operator, right, true, schema, context);
- }
- if (right instanceof SessionUser) {
- return resolveSessionComparison(operator, left, false, schema, context);
- }
- if (left instanceof Column) {
- return resolveColumnComparison((Column) left, operator, right, schema, false);
- }
- if (right instanceof Column) {
- if (operator == ComparisonOperator.IN) {
- throw new IllegalArgumentException("in requires the column on the left");
- }
- return resolveColumnComparison((Column) right, invert(operator), left, schema, false);
- }
- throw new IllegalArgumentException("comparison must contain a column or session_user()");
- }
-
- private static ResolvedPredicate resolveSessionComparison(
- ComparisonOperator operator,
- CanonicalExpression other,
- boolean sessionOnLeft,
- Schema schema,
- ResolutionContext context) {
- String sessionUser = context.sessionUser();
- if (other instanceof Column) {
- ComparisonOperator normalized = sessionOnLeft ? invert(operator) : operator;
- return resolveColumnComparison(
- (Column) other, normalized, SourceValue.sessionUser(sessionUser), schema, true);
- }
- if (other instanceof Literal) {
- Literal literal = (Literal) other;
- if (literal.literalType() != LiteralType.STRING
- || (operator != ComparisonOperator.EQ && operator != ComparisonOperator.NEQ)) {
- throw new IllegalArgumentException(
- "session_user() supports only equality with a string literal or column");
- }
- boolean equal = sessionUser.equals(literal.value());
- return constant(operator == ComparisonOperator.EQ ? equal : !equal);
- }
- if (other instanceof LiteralArray && sessionOnLeft && operator == ComparisonOperator.IN) {
- LiteralArray values = (LiteralArray) other;
- if (values.elementType() != LiteralType.STRING) {
- throw new IllegalArgumentException("session_user() in requires a string array");
- }
- boolean matched = false;
- for (Literal value : values.values()) {
- matched |= sessionUser.equals(value.value());
- }
- return constant(matched);
- }
- throw new IllegalArgumentException(
- "Unsupported session_user() comparison after restricted Rego parsing");
- }
-
- private static ResolvedPredicate resolveColumnComparison(
- Column column,
- ComparisonOperator operator,
- CanonicalExpression other,
- Schema schema,
- boolean sessionValue) {
- if (other instanceof Literal) {
- return resolveColumnComparison(
- column, operator, SourceValue.literal((Literal) other), schema, sessionValue);
- }
- if (other instanceof LiteralArray) {
- if (operator != ComparisonOperator.IN) {
- throw new IllegalArgumentException("literal arrays are valid only with in");
- }
- return resolveColumnIn(column, (LiteralArray) other, schema);
- }
- throw new IllegalArgumentException("column comparison requires a literal or session_user()");
- }
-
- private static ResolvedPredicate resolveColumnComparison(
- Column column,
- ComparisonOperator operator,
- SourceValue sourceValue,
- Schema schema,
- boolean sessionValue) {
- Types.NestedField field = topLevelField(schema, column.name());
- if (sessionValue && operator != ComparisonOperator.EQ && operator != ComparisonOperator.NEQ) {
- throw new IllegalArgumentException(
- "session_user() supports only equality with a string column");
- }
- if (sourceValue.literalType() == LiteralType.NULL) {
- if (operator != ComparisonOperator.EQ && operator != ComparisonOperator.NEQ) {
- throw new IllegalArgumentException("null supports only equality comparisons");
- }
- if (field.isRequired()) {
- throw new IllegalArgumentException(
- "null comparison requires an optional field: " + field.name());
- }
- Expression unbound =
- operator == ComparisonOperator.EQ
- ? Expressions.isNull(field.name())
- : Expressions.notNull(field.name());
- return resolved(bind(schema, field, unbound));
- }
-
- validateOperator(field.type(), operator);
- Object value = typedValue(sourceValue, field.type());
- Expression unbound = predicate(field.name(), operator, value);
- return resolved(bind(schema, field, unbound));
- }
-
- private static ResolvedPredicate resolveColumnIn(
- Column column, LiteralArray array, Schema schema) {
- Types.NestedField field = topLevelField(schema, column.name());
- validateOperator(field.type(), ComparisonOperator.IN);
-
- Map<String, Object> values = new TreeMap<>();
- for (Literal literal : array.values()) {
- Object value = typedValue(SourceValue.literal(literal), field.type());
- values.put(canonicalValue(value), value);
- }
- Expression unbound = Expressions.in(field.name(), values.values());
- return resolved(bind(schema, field, unbound));
- }
-
- private static Expression predicate(String fieldName, ComparisonOperator operator, Object value) {
- switch (operator) {
- case EQ:
- return Expressions.equal(fieldName, value);
- case NEQ:
- return Expressions.notEqual(fieldName, value);
- case LT:
- return Expressions.lessThan(fieldName, value);
- case LTE:
- return Expressions.lessThanOrEqual(fieldName, value);
- case GT:
- return Expressions.greaterThan(fieldName, value);
- case GTE:
- return Expressions.greaterThanOrEqual(fieldName, value);
- default:
- throw new IllegalArgumentException("Unsupported scalar comparison operator: " + operator);
- }
- }
-
- private static Expression bind(
- Schema schema, Types.NestedField expectedField, Expression expression) {
- Types.NestedField resolvedByIceberg = schema.findField(expectedField.name());
- if (resolvedByIceberg == null || resolvedByIceberg.fieldId() != expectedField.fieldId()) {
- throw new IllegalArgumentException(
- "Column name cannot be bound unambiguously as a top-level field: "
- + expectedField.name());
- }
- Expression bound = Binder.bind(schema.asStruct(), expression, true);
- if (!Binder.boundReferences(schema.asStruct(), bound, true)
- .equals(Collections.singleton(expectedField.fieldId()))) {
- throw new IllegalArgumentException(
- "Bound predicate did not preserve field ID " + expectedField.fieldId());
- }
- return bound;
- }
-
- private static void validateOperator(Type type, ComparisonOperator operator) {
- switch (type.typeId()) {
- case BOOLEAN:
- if (operator != ComparisonOperator.EQ
- && operator != ComparisonOperator.NEQ
- && operator != ComparisonOperator.IN) {
- throw new IllegalArgumentException("Boolean fields do not support ordering predicates");
- }
- return;
- case INTEGER:
- case LONG:
- case FLOAT:
- case DOUBLE:
- case DECIMAL:
- case DATE:
- case TIME:
- case STRING:
- return;
- case TIMESTAMP:
- if (((Types.TimestampType) type).shouldAdjustToUTC()) {
- throw new IllegalArgumentException(
- "Timestamp-with-timezone fields are not supported by read restrictions");
- }
- return;
- default:
- throw new IllegalArgumentException("Unsupported read-restriction field type: " + type);
- }
- }
-
- private static Object typedValue(SourceValue source, Type type) {
- switch (type.typeId()) {
- case BOOLEAN:
- requireLiteralType(source, LiteralType.BOOLEAN, type);
- return source.value();
- case INTEGER:
- requireLiteralType(source, LiteralType.NUMBER, type);
- try {
- return ((BigDecimal) source.value()).intValueExact();
- } catch (ArithmeticException exception) {
- throw invalidLiteral(source, type, exception);
- }
- case LONG:
- requireLiteralType(source, LiteralType.NUMBER, type);
- try {
- return ((BigDecimal) source.value()).longValueExact();
- } catch (ArithmeticException exception) {
- throw invalidLiteral(source, type, exception);
- }
- case FLOAT:
- requireLiteralType(source, LiteralType.NUMBER, type);
- return exactFloat(source);
- case DOUBLE:
- requireLiteralType(source, LiteralType.NUMBER, type);
- return exactDouble(source);
- case DECIMAL:
- requireLiteralType(source, LiteralType.NUMBER, type);
- return exactDecimal(source, (Types.DecimalType) type);
- case STRING:
- requireLiteralType(source, LiteralType.STRING, type);
- return source.value();
- case DATE:
- requireLiteralType(source, LiteralType.STRING, type);
- validateDate((String) source.value(), type);
- return source.value();
- case TIME:
- requireLiteralType(source, LiteralType.STRING, type);
- validateTime((String) source.value(), type);
- return source.value();
- case TIMESTAMP:
- if (((Types.TimestampType) type).shouldAdjustToUTC()) {
- throw new IllegalArgumentException(
- "Timestamp-with-timezone fields are not supported by read restrictions");
- }
- requireLiteralType(source, LiteralType.STRING, type);
- validateTimestamp((String) source.value(), type);
- return source.value();
- default:
- throw new IllegalArgumentException("Unsupported read-restriction field type: " + type);
- }
- }
-
- private static Float exactFloat(SourceValue source) {
- BigDecimal decimal = (BigDecimal) source.value();
- float value = decimal.floatValue();
- if (!Float.isFinite(value) || new BigDecimal((double) value).compareTo(decimal) != 0) {
- throw invalidLiteral(source, Types.FloatType.get(), null);
- }
- return source.negativeZero() ? -0.0F : value;
- }
-
- private static Double exactDouble(SourceValue source) {
- BigDecimal decimal = (BigDecimal) source.value();
- double value = decimal.doubleValue();
- if (!Double.isFinite(value) || new BigDecimal(value).compareTo(decimal) != 0) {
- throw invalidLiteral(source, Types.DoubleType.get(), null);
- }
- return source.negativeZero() ? -0.0D : value;
- }
-
- private static BigDecimal exactDecimal(SourceValue source, Types.DecimalType type) {
- BigDecimal value;
- try {
- value = ((BigDecimal) source.value()).setScale(type.scale(), RoundingMode.UNNECESSARY);
- } catch (ArithmeticException exception) {
- throw invalidLiteral(source, type, exception);
- }
- if (value.precision() > type.precision()) {
- throw invalidLiteral(source, type, null);
- }
- return value;
- }
-
- private static void validateDate(String value, Type type) {
- try {
- LocalDate.parse(value);
- } catch (DateTimeParseException exception) {
- throw invalidLiteral(SourceValue.string(value), type, exception);
- }
- }
-
- private static void validateTime(String value, Type type) {
- try {
- LocalTime parsed = LocalTime.parse(value);
- if (!parsed.equals(parsed.truncatedTo(ChronoUnit.MICROS))) {
- throw invalidLiteral(SourceValue.string(value), type, null);
- }
- } catch (DateTimeParseException exception) {
- throw invalidLiteral(SourceValue.string(value), type, exception);
- }
- }
-
- private static void validateTimestamp(String value, Type type) {
- try {
- LocalDateTime parsed = LocalDateTime.parse(value);
- if (!parsed.equals(parsed.truncatedTo(ChronoUnit.MICROS))) {
- throw invalidLiteral(SourceValue.string(value), type, null);
- }
- } catch (DateTimeParseException exception) {
- throw invalidLiteral(SourceValue.string(value), type, exception);
- }
- }
-
- private static void requireLiteralType(SourceValue source, LiteralType expected, Type fieldType) {
- if (source.literalType() != expected) {
- throw invalidLiteral(source, fieldType, null);
- }
- }
-
- private static IllegalArgumentException invalidLiteral(
- SourceValue source, Type type, Exception cause) {
- String message =
- String.format(
- "Literal %s cannot be represented exactly as Iceberg %s", source.value(), type);
- return cause == null
- ? new IllegalArgumentException(message)
- : new IllegalArgumentException(message, cause);
- }
-
- private static boolean resolveGroup(GroupMembership membership, ResolutionContext context) {
- return context.groupMembership(membership.group());
- }
-
- private static MaskAction resolveMaskAction(
- ColumnMask mask, Schema schema, ResolutionContext context) {
- mask.validate();
- for (MaskBranch branch : mask.branches()) {
- ResolvedPredicate condition = resolvePredicate(branch.condition(), schema, context);
- if (condition.expression().op() != Expression.Operation.TRUE
- && condition.expression().op() != Expression.Operation.FALSE) {
- throw new IllegalArgumentException("column-mask condition did not resolve to a constant");
- }
- if (condition.expression().op() == Expression.Operation.TRUE) {
- return branch.action();
- }
- }
- return mask.fallback();
- }
-
- private static IcebergFunction<?, ?> toIcebergFunction(
- MaskAction action, Types.NestedField field) {
- IcebergFunction<?, ?> function;
- switch (action) {
- case MASK_ALPHANUM:
- function = IcebergFunctions.maskAlphanum(field.fieldId());
- break;
- case MASK_TO_FIXED_VALUE:
- function = IcebergFunctions.maskToFixedValue(field.fieldId());
- break;
- case REPLACE_WITH_NULL:
- if (field.isRequired()) {
- throw new IllegalArgumentException(
- "replace-with-null is invalid for required field " + field.fieldId());
- }
- function = IcebergFunctions.replaceWithNull(field.fieldId());
- break;
- case SHOW_FIRST_4:
- function = IcebergFunctions.showFirst4(field.fieldId());
- break;
- case SHOW_LAST_4:
- function = IcebergFunctions.showLast4(field.fieldId());
- break;
- case TRUNCATE_TO_YEAR:
- function = IcebergFunctions.truncateToYear(field.fieldId());
- break;
- case TRUNCATE_TO_MONTH:
- function = IcebergFunctions.truncateToMonth(field.fieldId());
- break;
- case SHA_256_GLOBAL:
- function = IcebergFunctions.sha256Global(field.fieldId());
- break;
- case SHA_256_QUERY_LOCAL:
- function = IcebergFunctions.sha256QueryLocal(field.fieldId());
- break;
- default:
- throw new IllegalArgumentException("Unsupported mask action: " + action);
- }
- if (!function.canBind(field.type())) {
- throw new IllegalArgumentException(
- String.format(
- "Mask action %s is incompatible with field %s of type %s",
- action.value(), field.fieldId(), field.type()));
- }
- return function;
- }
-
- private static Types.NestedField topLevelField(Schema schema, String name) {
- Types.NestedField match = null;
- for (Types.NestedField field : schema.columns()) {
- if (field.name().equals(name)) {
- if (match != null) {
- throw new IllegalArgumentException("Ambiguous top-level column: " + name);
- }
- match = field;
- }
- }
- if (match == null) {
- throw new IllegalArgumentException("Cannot find top-level column: " + name);
- }
- return match;
- }
-
- private static Types.NestedField topLevelField(Schema schema, int fieldId) {
- for (Types.NestedField field : schema.columns()) {
- if (field.fieldId() == fieldId) {
- return field;
- }
- }
- throw new IllegalArgumentException("Cannot find top-level field ID: " + fieldId);
- }
-
- private static ComparisonOperator invert(ComparisonOperator operator) {
- switch (operator) {
- case EQ:
- case NEQ:
- return operator;
- case LT:
- return ComparisonOperator.GT;
- case LTE:
- return ComparisonOperator.GTE;
- case GT:
- return ComparisonOperator.LT;
- case GTE:
- return ComparisonOperator.LTE;
- default:
- throw new IllegalArgumentException("Cannot invert comparison operator: " + operator);
- }
- }
-
- private static String canonicalValue(Object value) {
- if (value instanceof BigDecimal) {
- return ((BigDecimal) value).toPlainString();
- }
- if (value instanceof Float) {
- return Integer.toUnsignedString(Float.floatToIntBits((Float) value));
- }
- if (value instanceof Double) {
- return Long.toUnsignedString(Double.doubleToLongBits((Double) value));
- }
- return String.valueOf(value);
- }
-
- private static ResolvedPredicate constant(boolean value) {
- return resolved(value ? Expressions.alwaysTrue() : Expressions.alwaysFalse());
- }
-
- private static ResolvedPredicate resolved(Expression expression) {
- return new ResolvedPredicate(expression, ExpressionParser.toJson(expression));
- }
-
- private static final class ResolvedPredicate {
- private final Expression expression;
- private final String signature;
-
- private ResolvedPredicate(Expression expression, String signature) {
- this.expression = expression;
- this.signature = signature;
- }
-
- private Expression expression() {
- return expression;
- }
-
- private String signature() {
- return signature;
- }
- }
-
- private static final class SourceValue {
- private final LiteralType literalType;
- private final Object value;
- private final boolean negativeZero;
-
- private SourceValue(LiteralType literalType, Object value, boolean negativeZero) {
- this.literalType = literalType;
- this.value = value;
- this.negativeZero = negativeZero;
- }
-
- private static SourceValue literal(Literal literal) {
- return new SourceValue(literal.literalType(), literal.value(), literal.negativeZero());
- }
-
- private static SourceValue sessionUser(String value) {
- return string(value);
- }
-
- private static SourceValue string(String value) {
- return new SourceValue(LiteralType.STRING, value, false);
- }
-
- private LiteralType literalType() {
- return literalType;
- }
-
- private Object value() {
- return value;
- }
-
- private boolean negativeZero() {
- return negativeZero;
- }
- }
-
- private static final class ResolutionContext {
- private final BindingContext delegate;
- private final String sessionUser;
- private final Map<String, Boolean> groupMemberships = new HashMap<>();
-
- private ResolutionContext(BindingContext delegate) {
- this.delegate = Objects.requireNonNull(delegate, "context cannot be null");
- this.sessionUser = delegate.sessionUser();
- if (sessionUser == null || sessionUser.isEmpty()) {
- throw new IllegalArgumentException("authenticated session user cannot be null or empty");
- }
- }
-
- private String sessionUser() {
- return sessionUser;
- }
-
- private boolean groupMembership(String group) {
- if (groupMemberships.containsKey(group)) {
- return groupMemberships.get(group);
- }
- Optional<Boolean> result = delegate.groupMembership(group);
- if (result == null || !result.isPresent()) {
- throw new IllegalArgumentException(
- "Cannot resolve group membership for the applicable read restriction");
- }
- groupMemberships.put(group, result.get());
- return result.get();
- }
- }
}
diff --git a/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlPredicateResult.java b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlPredicateResult.java
new file mode 100644
index 0000000000..353f09ce89
--- /dev/null
+++ b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlPredicateResult.java
@@ -0,0 +1,90 @@
+/*
+ * 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.iceberg.service.restriction;
+
+import javax.annotation.Nullable;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+
+/**
+ * A SQL Boolean result represented by two disjoint Iceberg predicates.
+ *
+ * <p>The true expression selects rows where the SQL result is TRUE; the false expression selects
+ * rows where it is FALSE. Rows where the result is UNKNOWN match neither expression. For example,
+ * when lowering {@code region = 'US'}, a null region matches neither predicate. The false
+ * expression therefore cannot be obtained by simply negating the true expression.
+ *
+ * <p>Keeping both predicates preserves UNKNOWN through SQL NOT, AND, OR and CASE evaluation.
+ */
+final class SqlPredicateResult {
+ private final Expression trueExpression;
+ private final Expression falseExpression;
+
+ /** Creates a result from predicates whose matching row sets are disjoint. */
+ SqlPredicateResult(Expression trueExpression, Expression falseExpression) {
+ this.trueExpression = trueExpression;
+ this.falseExpression = falseExpression;
+ }
+
+ /** Creates a constant SQL result; null represents UNKNOWN and matches neither predicate. */
+ static SqlPredicateResult constant(@Nullable Boolean value) {
+ return new SqlPredicateResult(
+ Boolean.TRUE.equals(value) ? Expressions.alwaysTrue() : Expressions.alwaysFalse(),
+ Boolean.FALSE.equals(value) ? Expressions.alwaysTrue() : Expressions.alwaysFalse());
+ }
+
+ /** Returns the predicate selecting rows where the SQL result is TRUE. */
+ Expression trueExpression() {
+ return trueExpression;
+ }
+
+ /** Returns the predicate selecting rows where the SQL result is FALSE. */
+ Expression falseExpression() {
+ return falseExpression;
+ }
+
+ /** Returns whether both predicates are constant, including the UNKNOWN result. */
+ boolean isConstant() {
+ return (trueExpression.op() == Expression.Operation.TRUE
+ || trueExpression.op() == Expression.Operation.FALSE)
+ && (falseExpression.op() == Expression.Operation.TRUE
+ || falseExpression.op() == Expression.Operation.FALSE);
+ }
+
+ /** Applies SQL NOT by swapping TRUE and FALSE, leaving UNKNOWN unmatched. */
+ SqlPredicateResult not() {
+ return new SqlPredicateResult(falseExpression, trueExpression);
+ }
+
+ /** Applies SQL AND: both operands must be TRUE, while either FALSE operand makes FALSE. */
+ SqlPredicateResult and(SqlPredicateResult other) {
+ return new SqlPredicateResult(
+ Expressions.and(trueExpression, other.trueExpression),
+ Expressions.or(falseExpression, other.falseExpression));
+ }
+
+ /**
+ * Applies SQL OR: either TRUE operand makes TRUE, while both operands must be FALSE for FALSE.
+ */
+ SqlPredicateResult or(SqlPredicateResult other) {
+ return new SqlPredicateResult(
+ Expressions.or(trueExpression, other.trueExpression),
+ Expressions.and(falseExpression, other.falseExpression));
+ }
+}
diff --git a/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlRestrictionBinding.java b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlRestrictionBinding.java
new file mode 100644
index 0000000000..816468a77d
--- /dev/null
+++ b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlRestrictionBinding.java
@@ -0,0 +1,254 @@
+/*
+ * 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.iceberg.service.restriction;
+
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import javax.annotation.Nullable;
+import org.apache.gravitino.iceberg.service.restriction.IcebergReadRestrictionConverter.BindingContext;
+import org.apache.gravitino.policy.sql.FunctionCall;
+import org.apache.gravitino.policy.sql.InputReference;
+import org.apache.gravitino.policy.sql.Literal;
+import org.apache.gravitino.policy.sql.LiteralType;
+import org.apache.gravitino.policy.sql.SqlDefinition;
+import org.apache.gravitino.policy.sql.SqlExpression;
+import org.apache.gravitino.policy.sql.SqlFunction;
+import org.apache.gravitino.policy.sql.SqlType;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.expressions.Binder;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.UnboundTerm;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.Types;
+
+/** Binds all declared inputs before evaluating context-dependent SQL branches. */
+final class SqlRestrictionBinding {
+ private final Schema schema;
+ private final Context context;
+ private final Map<String, Types.NestedField> inputs = new LinkedHashMap<>();
+
+ SqlRestrictionBinding(
+ SqlDefinition definition,
+ Schema schema,
+ Context context,
+ @Nullable Types.NestedField maskField) {
+ this.schema = schema;
+ this.context = context;
+ if (definition.isColumnMask() != (maskField != null)) {
+ throw new IllegalArgumentException("SQL definition does not match restriction target");
+ }
+ for (Map.Entry<String, SqlType> parameter : definition.parameters().entrySet()) {
+ Types.NestedField field =
+ maskField == null
+ ? findField(
+ schema, parameter.getKey(), definition.isQuotedParameter(parameter.getKey()))
+ : maskField;
+ if (!SqlRestrictionLiterals.type(parameter.getValue()).equals(field.type())) {
+ throw new IllegalArgumentException(
+ "Declared SQL type does not match column " + field.name());
+ }
+ inputs.put(parameter.getKey(), field);
+ }
+ if (maskField != null
+ && !SqlRestrictionLiterals.type(definition.resultType()).equals(maskField.type())) {
+ throw new IllegalArgumentException("Mask result type does not match selected column");
+ }
+ if (maskField == null && !definition.resultType().equals(SqlType.BOOLEAN)) {
+ throw new IllegalArgumentException("Row filter must return BOOLEAN");
+ }
+ }
+
+ Term term(SqlExpression expression) {
+ if (expression instanceof InputReference) {
+ Types.NestedField field = inputs.get(((InputReference) expression).name());
+ if (field == null) {
+ throw new IllegalArgumentException("Unbound SQL parameter");
+ }
+ return new Term(field, Expressions.ref(field.name()), field.type(), false);
+ }
+ if (expression instanceof FunctionCall) {
+ FunctionCall call = (FunctionCall) expression;
+ if (call.function() == SqlFunction.YEAR
+ && call.arguments().get(0) instanceof InputReference) {
+ Term input = term(call.arguments().get(0));
+ return new Term(
+ input.field, Expressions.year(input.field.name()), Types.IntegerType.get(), true);
+ }
+ }
+ throw unsupported("the scalar input or date-part function");
+ }
+
+ Literal constant(SqlExpression expression) {
+ if (expression instanceof Literal) {
+ return (Literal) expression;
+ }
+ if (!(expression instanceof FunctionCall)) {
+ throw unsupported("a row-dependent scalar value");
+ }
+ FunctionCall call = (FunctionCall) expression;
+ switch (call.function()) {
+ case CURRENT_USER:
+ return new Literal(LiteralType.STRING, context.user, SqlType.STRING);
+ case IS_GROUP_MEMBER:
+ return bool(context.group(((Literal) call.arguments().get(0)).value()));
+ case YEAR:
+ case MONTH:
+ case DAY:
+ Literal input = constant(call.arguments().get(0));
+ if (input.literalType() == LiteralType.NULL) {
+ return nullLiteral();
+ }
+ if (input.type() == null || !input.type().temporal()) {
+ throw new IllegalArgumentException("Date part requires a typed temporal value");
+ }
+ SqlRestrictionLiterals.value(input, SqlRestrictionLiterals.type(input.type()));
+ LocalDate date;
+ if (input.type().name().equals("DATE")) {
+ date = LocalDate.parse(input.value());
+ } else if (input.type().withTimeZone()) {
+ date =
+ OffsetDateTime.parse(input.value().replace(' ', 'T'))
+ .withOffsetSameInstant(ZoneOffset.UTC)
+ .toLocalDate();
+ } else {
+ date = LocalDateTime.parse(input.value().replace(' ', 'T')).toLocalDate();
+ }
+ int part =
+ call.function() == SqlFunction.YEAR
+ ? date.getYear()
+ : call.function() == SqlFunction.MONTH
+ ? date.getMonthValue()
+ : date.getDayOfMonth();
+ return new Literal(LiteralType.NUMBER, Integer.toString(part), SqlType.INTEGER);
+ default:
+ throw unsupported("the scalar function " + call.function());
+ }
+ }
+
+ Expression bind(Term term, Expression predicate) {
+ Types.NestedField byName = schema.findField(term.field.name());
+ if (byName == null || byName.fieldId() != term.field.fieldId()) {
+ throw new IllegalArgumentException(
+ "Cannot bind top-level field unambiguously: " + term.field.name());
+ }
+ Expression result = Binder.bind(schema.asStruct(), predicate, true);
+ if (result.op() != Expression.Operation.TRUE
+ && result.op() != Expression.Operation.FALSE
+ && !Binder.boundReferences(schema.asStruct(), result, true)
+ .equals(Collections.singleton(term.field.fieldId()))) {
+ throw new IllegalArgumentException("Bound expression did not preserve the selected field ID");
+ }
+ return result;
+ }
+
+ static Types.NestedField field(Schema schema, int id) {
+ for (Types.NestedField field : schema.columns()) {
+ if (field.fieldId() == id) {
+ return field;
+ }
+ }
+ throw new IllegalArgumentException("Cannot find top-level field ID: " + id);
+ }
+
+ static IllegalArgumentException unsupported(String feature) {
+ return new IllegalArgumentException("Iceberg read restrictions cannot represent " + feature);
+ }
+
+ static Literal bool(boolean value) {
+ return new Literal(LiteralType.BOOLEAN, Boolean.toString(value), SqlType.BOOLEAN);
+ }
+
+ static Literal nullLiteral() {
+ return new Literal(LiteralType.NULL, "", null);
+ }
+
+ private static Types.NestedField findField(Schema schema, String name, boolean quoted) {
+ Types.NestedField match = null;
+ for (Types.NestedField field : schema.columns()) {
+ boolean matches =
+ quoted ? field.name().equals(name) : field.name().toUpperCase(Locale.ROOT).equals(name);
+ if (matches) {
+ if (match != null) {
+ throw new IllegalArgumentException("Ambiguous top-level SQL parameter: " + name);
+ }
+ match = field;
+ }
+ }
+ if (match == null) {
+ throw new IllegalArgumentException("Cannot find top-level SQL parameter: " + name);
+ }
+ return match;
+ }
+
+ static final class Term {
+ final Types.NestedField field;
+ final UnboundTerm<Object> expression;
+ final Type type;
+ private final boolean calendarYear;
+
+ Term(Types.NestedField field, UnboundTerm<Object> expression, Type type, boolean calendarYear) {
+ this.field = field;
+ this.expression = expression;
+ this.type = type;
+ this.calendarYear = calendarYear;
+ }
+
+ Object value(Literal literal) {
+ Object value = SqlRestrictionLiterals.value(literal, type);
+ return calendarYear && value != null ? Math.subtractExact((Integer) value, 1970) : value;
+ }
+ }
+
+ static final class Context {
+ private final BindingContext delegate;
+ private final String user;
+ private final Map<String, Boolean> groups = new HashMap<>();
+
+ Context(BindingContext delegate) {
+ this.delegate = Objects.requireNonNull(delegate, "context cannot be null");
+ this.user = delegate.sessionUser();
+ if (user == null || user.isEmpty()) {
+ throw new IllegalArgumentException("Authenticated user cannot be null or empty");
+ }
+ }
+
+ boolean group(String name) {
+ return groups.computeIfAbsent(
+ name,
+ key -> {
+ Optional<Boolean> result = delegate.groupMembership(key);
+ if (result == null || !result.isPresent()) {
+ throw new IllegalArgumentException(
+ "Cannot resolve group membership for read restriction");
+ }
+ return result.get();
+ });
+ }
+ }
+}
diff --git a/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlRestrictionCanonicalizer.java b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlRestrictionCanonicalizer.java
new file mode 100644
index 0000000000..016d6c709e
--- /dev/null
+++ b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlRestrictionCanonicalizer.java
@@ -0,0 +1,142 @@
+/*
+ * 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.iceberg.service.restriction;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+import org.apache.iceberg.expressions.And;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.ExpressionParser;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Not;
+import org.apache.iceberg.expressions.Or;
+
+/** Canonicalizes closed predicates with a separate bound on generated restriction complexity. */
+final class SqlRestrictionCanonicalizer {
+ private static final int MAX_NODES = 16384;
+ private static final int MAX_DEPTH = 256;
+
+ private SqlRestrictionCanonicalizer() {}
+
+ static Expression canonicalize(Expression expression) {
+ validateBudget(expression);
+ Expression rewritten = Expressions.rewriteNot(expression);
+ validateBudget(rewritten);
+ return canonical(rewritten);
+ }
+
+ static Expression combine(boolean conjunction, List<Expression> children) {
+ if (children.isEmpty()) {
+ return conjunction ? Expressions.alwaysTrue() : Expressions.alwaysFalse();
+ }
+ return balanced(conjunction, children, 0, children.size());
+ }
+
+ private static Expression canonical(Expression expression) {
+ if (expression.op() != Expression.Operation.AND && expression.op() != Expression.Operation.OR) {
+ return expression;
+ }
+ boolean conjunction = expression.op() == Expression.Operation.AND;
+ Deque<Expression> pending = new ArrayDeque<>();
+ pending.push(expression);
+ Map<String, Expression> children = new TreeMap<>();
+ boolean absorbing = false;
+ while (!pending.isEmpty()) {
+ Expression child = pending.pop();
+ if (child.op() == expression.op()) {
+ children(child).forEach(pending::push);
+ } else {
+ Expression normalized = canonical(child);
+ if (normalized.op()
+ == (conjunction ? Expression.Operation.FALSE : Expression.Operation.TRUE)) {
+ absorbing = true;
+ } else if (normalized.op()
+ != (conjunction ? Expression.Operation.TRUE : Expression.Operation.FALSE)) {
+ children.put(ExpressionParser.toJson(normalized), normalized);
+ }
+ }
+ }
+ if (absorbing) {
+ return conjunction ? Expressions.alwaysFalse() : Expressions.alwaysTrue();
+ }
+ return combine(conjunction, new ArrayList<>(children.values()));
+ }
+
+ private static Expression balanced(
+ boolean conjunction, List<Expression> children, int from, int to) {
+ if (to - from == 1) {
+ return children.get(from);
+ }
+ int middle = (from + to) >>> 1;
+ Expression left = balanced(conjunction, children, from, middle);
+ Expression right = balanced(conjunction, children, middle, to);
+ return conjunction ? Expressions.and(left, right) : Expressions.or(left, right);
+ }
+
+ private static void validateBudget(Expression root) {
+ IdentityHashMap<Expression, int[]> sizes = new IdentityHashMap<>();
+ Deque<Expression> pending = new ArrayDeque<>();
+ pending.push(root);
+ while (!pending.isEmpty()) {
+ Expression expression = pending.peek();
+ List<Expression> children = children(expression);
+ boolean ready = true;
+ for (Expression child : children) {
+ if (!sizes.containsKey(child)) {
+ pending.push(child);
+ ready = false;
+ }
+ }
+ if (!ready) {
+ continue;
+ }
+ int count = 1;
+ int depth = 1;
+ for (Expression child : children) {
+ count += sizes.get(child)[0];
+ depth = Math.max(depth, 1 + sizes.get(child)[1]);
+ }
+ if (count > MAX_NODES || depth > MAX_DEPTH) {
+ throw new IllegalArgumentException(
+ "Converted SQL restriction exceeds Iceberg expression complexity limits");
+ }
+ sizes.put(expression, new int[] {count, depth});
+ pending.pop();
+ }
+ }
+
+ private static List<Expression> children(Expression expression) {
+ List<Expression> children = new ArrayList<>(2);
+ if (expression instanceof And) {
+ children.add(((And) expression).left());
+ children.add(((And) expression).right());
+ } else if (expression instanceof Or) {
+ children.add(((Or) expression).left());
+ children.add(((Or) expression).right());
+ } else if (expression instanceof Not) {
+ children.add(((Not) expression).child());
+ }
+ return children;
+ }
+}
diff --git a/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlRestrictionLiterals.java b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlRestrictionLiterals.java
new file mode 100644
index 0000000000..fc19686f87
--- /dev/null
+++ b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlRestrictionLiterals.java
@@ -0,0 +1,203 @@
+/*
+ * 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.iceberg.service.restriction;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.time.DateTimeException;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.time.temporal.ChronoUnit;
+import javax.annotation.Nullable;
+import org.apache.gravitino.policy.sql.Literal;
+import org.apache.gravitino.policy.sql.LiteralType;
+import org.apache.gravitino.policy.sql.SqlType;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.Types;
+
+/** Exact logical-type and literal binding shared by SQL predicates and masks. */
+final class SqlRestrictionLiterals {
+ private SqlRestrictionLiterals() {}
+
+ static Type type(SqlType declared) {
+ switch (declared.name()) {
+ case "BOOLEAN":
+ return Types.BooleanType.get();
+ case "INTEGER":
+ return Types.IntegerType.get();
+ case "LONG":
+ return Types.LongType.get();
+ case "FLOAT":
+ return Types.FloatType.get();
+ case "DOUBLE":
+ return Types.DoubleType.get();
+ case "STRING":
+ return Types.StringType.get();
+ case "BINARY":
+ return Types.BinaryType.get();
+ case "DATE":
+ return Types.DateType.get();
+ case "DECIMAL":
+ return Types.DecimalType.of(declared.precision(), declared.scale());
+ case "TIME":
+ temporalPrecision(declared);
+ return Types.TimeType.get();
+ case "TIMESTAMP":
+ temporalPrecision(declared);
+ return declared.withTimeZone()
+ ? Types.TimestampType.withZone()
+ : Types.TimestampType.withoutZone();
+ default:
+ throw new IllegalArgumentException("Unsupported declared SQL type: " + declared);
+ }
+ }
+
+ @Nullable
+ static Object value(Literal source, Type expected) {
+ if (source.type() != null && !type(source.type()).equals(expected)) {
+ throw new IllegalArgumentException("Literal or context type does not match " + expected);
+ }
+ if (source.literalType() == LiteralType.NULL) {
+ return null;
+ }
+ try {
+ switch (expected.typeId()) {
+ case BOOLEAN:
+ kind(source, LiteralType.BOOLEAN);
+ if (!source.value().equalsIgnoreCase("TRUE")
+ && !source.value().equalsIgnoreCase("FALSE")) {
+ throw new IllegalArgumentException("Invalid Boolean literal");
+ }
+ return Boolean.parseBoolean(source.value());
+ case STRING:
+ kind(source, LiteralType.STRING);
+ return source.value();
+ case INTEGER:
+ kind(source, LiteralType.NUMBER);
+ return new BigDecimal(source.value()).intValueExact();
+ case LONG:
+ kind(source, LiteralType.NUMBER);
+ return new BigDecimal(source.value()).longValueExact();
+ case FLOAT:
+ kind(source, LiteralType.NUMBER);
+ BigDecimal floatDecimal = new BigDecimal(source.value());
+ float floatValue = Float.parseFloat(source.value());
+ if (!Float.isFinite(floatValue)
+ || new BigDecimal((double) floatValue).compareTo(floatDecimal) != 0) {
+ throw new IllegalArgumentException("Inexact FLOAT literal");
+ }
+ return floatValue;
+ case DOUBLE:
+ kind(source, LiteralType.NUMBER);
+ BigDecimal doubleDecimal = new BigDecimal(source.value());
+ double doubleValue = Double.parseDouble(source.value());
+ if (!Double.isFinite(doubleValue)
+ || new BigDecimal(doubleValue).compareTo(doubleDecimal) != 0) {
+ throw new IllegalArgumentException("Inexact DOUBLE literal");
+ }
+ return doubleValue;
+ case DECIMAL:
+ kind(source, LiteralType.NUMBER);
+ Types.DecimalType decimalType = (Types.DecimalType) expected;
+ BigDecimal decimal =
+ new BigDecimal(source.value())
+ .setScale(decimalType.scale(), RoundingMode.UNNECESSARY);
+ if (decimal.precision() > decimalType.precision()) {
+ throw new IllegalArgumentException("Decimal precision overflow");
+ }
+ return decimal;
+ case DATE:
+ kind(source, LiteralType.TEMPORAL);
+ return Math.toIntExact(LocalDate.parse(source.value()).toEpochDay());
+ case TIME:
+ kind(source, LiteralType.TEMPORAL);
+ LocalTime time = LocalTime.parse(source.value());
+ if (!time.equals(time.truncatedTo(ChronoUnit.MICROS))) {
+ throw new IllegalArgumentException("Unsupported temporal precision");
+ }
+ return time.toNanoOfDay() / 1000;
+ case TIMESTAMP:
+ kind(source, LiteralType.TEMPORAL);
+ String text = source.value().replace(' ', 'T');
+ boolean zoned = ((Types.TimestampType) expected).shouldAdjustToUTC();
+ LocalDateTime timestamp =
+ zoned
+ ? OffsetDateTime.parse(text)
+ .withOffsetSameInstant(ZoneOffset.UTC)
+ .toLocalDateTime()
+ : LocalDateTime.parse(text);
+ if (!timestamp.equals(timestamp.truncatedTo(ChronoUnit.MICROS))) {
+ throw new IllegalArgumentException("Unsupported temporal precision");
+ }
+ return ChronoUnit.MICROS.between(LocalDateTime.of(1970, 1, 1, 0, 0), timestamp);
+ default:
+ throw new IllegalArgumentException("Unsupported literal target: " + expected);
+ }
+ } catch (ArithmeticException | DateTimeException exception) {
+ throw new IllegalArgumentException(
+ "Literal cannot be represented exactly as " + expected, exception);
+ }
+ }
+
+ static String canonicalValue(Object value) {
+ if (value instanceof Float) {
+ return Integer.toUnsignedString(Float.floatToRawIntBits((Float) value));
+ }
+ if (value instanceof Double) {
+ return Long.toUnsignedString(Double.doubleToRawLongBits((Double) value));
+ }
+ if (value instanceof BigDecimal) {
+ return ((BigDecimal) value).toPlainString();
+ }
+ return value.toString();
+ }
+
+ @SuppressWarnings("unchecked")
+ static int compare(Object left, Object right) {
+ if (left instanceof CharSequence) {
+ return Comparators.charSequences().compare((CharSequence) left, (CharSequence) right);
+ }
+ if (left instanceof BigDecimal) {
+ return ((BigDecimal) left).compareTo((BigDecimal) right);
+ }
+ if (left instanceof Float && (Float) left == 0F && (Float) right == 0F) {
+ return 0;
+ }
+ if (left instanceof Double && (Double) left == 0D && (Double) right == 0D) {
+ return 0;
+ }
+ return ((Comparable<Object>) left).compareTo(right);
+ }
+
+ private static void temporalPrecision(SqlType type) {
+ if (type.precision() != 0 && type.precision() != 6) {
+ throw new IllegalArgumentException("Only microsecond temporal precision is supported");
+ }
+ }
+
+ private static void kind(Literal source, LiteralType expected) {
+ if (source.literalType() != expected) {
+ throw new IllegalArgumentException("Literal kind does not match target type");
+ }
+ }
+}
diff --git a/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlRestrictionMasks.java b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlRestrictionMasks.java
new file mode 100644
index 0000000000..4e10ca017e
--- /dev/null
+++ b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlRestrictionMasks.java
@@ -0,0 +1,201 @@
+/*
+ * 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.iceberg.service.restriction;
+
+import java.math.BigDecimal;
+import java.util.Objects;
+import javax.annotation.Nullable;
+import org.apache.gravitino.policy.sql.Between;
+import org.apache.gravitino.policy.sql.CaseBranch;
+import org.apache.gravitino.policy.sql.CaseExpression;
+import org.apache.gravitino.policy.sql.Comparison;
+import org.apache.gravitino.policy.sql.FunctionCall;
+import org.apache.gravitino.policy.sql.In;
+import org.apache.gravitino.policy.sql.InputReference;
+import org.apache.gravitino.policy.sql.IsNull;
+import org.apache.gravitino.policy.sql.Like;
+import org.apache.gravitino.policy.sql.Literal;
+import org.apache.gravitino.policy.sql.LiteralType;
+import org.apache.gravitino.policy.sql.LogicalExpression;
+import org.apache.gravitino.policy.sql.Not;
+import org.apache.gravitino.policy.sql.SqlExpression;
+import org.apache.gravitino.policy.sql.SqlFunction;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.functions.IcebergFunction;
+import org.apache.iceberg.functions.IcebergFunctions;
+import org.apache.iceberg.types.Types;
+
+/** Converts selected scalar SQL mask results to one supported Iceberg projection per field. */
+final class SqlRestrictionMasks {
+ private final Types.NestedField field;
+ private final SqlRestrictionPredicates predicates;
+
+ SqlRestrictionMasks(Types.NestedField field, SqlRestrictionPredicates predicates) {
+ this.field = field;
+ this.predicates = predicates;
+ }
+
+ @Nullable
+ IcebergFunction<?, ?> resolve(SqlExpression body) {
+ if (field.isRequired() && nullable(body)) {
+ throw new IllegalArgumentException(
+ "Nullable SQL mask result is invalid for required field " + field.fieldId());
+ }
+ return selected(body);
+ }
+
+ @Nullable
+ private IcebergFunction<?, ?> selected(SqlExpression body) {
+ if (body instanceof InputReference) {
+ return null;
+ }
+ if (body instanceof CaseExpression) {
+ CaseExpression choice = (CaseExpression) body;
+ for (CaseBranch branch : choice.branches()) {
+ SqlPredicateResult condition =
+ choice.selector() == null
+ ? predicates.resolve(branch.condition())
+ : equality(choice.selector(), branch.condition());
+ if (!condition.isConstant()) {
+ throw SqlRestrictionBinding.unsupported("row-dependent mask selection");
+ }
+ if (condition.trueExpression().op() == Expression.Operation.TRUE) {
+ return selected(branch.result());
+ }
+ }
+ return choice.fallback() == null
+ ? checked(IcebergFunctions.replaceWithNull(field.fieldId()))
+ : selected(choice.fallback());
+ }
+ if (body instanceof FunctionCall) {
+ FunctionCall call = (FunctionCall) body;
+ if (call.arguments().size() == 1 && call.arguments().get(0) instanceof InputReference) {
+ return checked(mask(call.function()));
+ }
+ }
+ Literal literal = predicates.constantScalar(body);
+ Object value = SqlRestrictionLiterals.value(literal, field.type());
+ if (value == null) {
+ return checked(IcebergFunctions.replaceWithNull(field.fieldId()));
+ }
+ IcebergFunction<?, ?> fixed = checked(IcebergFunctions.maskToFixedValue(field.fieldId()));
+ Object fixedValue = fixed.bind(field.type()).apply(null);
+ boolean same =
+ value instanceof BigDecimal && fixedValue instanceof BigDecimal
+ ? ((BigDecimal) value).compareTo((BigDecimal) fixedValue) == 0
+ : Objects.equals(value, fixedValue);
+ if (!same) {
+ throw SqlRestrictionBinding.unsupported("an arbitrary constant mask value");
+ }
+ return fixed;
+ }
+
+ private SqlPredicateResult equality(SqlExpression selector, SqlExpression match) {
+ return predicates.equal(selector, match);
+ }
+
+ private IcebergFunction<?, ?> mask(SqlFunction function) {
+ switch (function) {
+ case MASK_ALPHANUM:
+ return IcebergFunctions.maskAlphanum(field.fieldId());
+ case SHOW_FIRST_4:
+ return IcebergFunctions.showFirst4(field.fieldId());
+ case SHOW_LAST_4:
+ return IcebergFunctions.showLast4(field.fieldId());
+ case MASK_TO_FIXED_VALUE:
+ return IcebergFunctions.maskToFixedValue(field.fieldId());
+ case REPLACE_WITH_NULL:
+ return IcebergFunctions.replaceWithNull(field.fieldId());
+ case TRUNCATE_TO_YEAR:
+ return IcebergFunctions.truncateToYear(field.fieldId());
+ case TRUNCATE_TO_MONTH:
+ return IcebergFunctions.truncateToMonth(field.fieldId());
+ case SHA256_GLOBAL:
+ return IcebergFunctions.sha256Global(field.fieldId());
+ case SHA256_QUERY_LOCAL:
+ return IcebergFunctions.sha256QueryLocal(field.fieldId());
+ default:
+ throw SqlRestrictionBinding.unsupported("the selected mask function " + function);
+ }
+ }
+
+ private IcebergFunction<?, ?> checked(IcebergFunction<?, ?> function) {
+ if (function.name().equals("replace-with-null") && field.isRequired()) {
+ throw new IllegalArgumentException(
+ "NULL mask is invalid for required field " + field.fieldId());
+ }
+ if (!function.canBind(field.type())) {
+ throw new IllegalArgumentException(
+ "Mask " + function.name() + " is incompatible with selected field type " + field.type());
+ }
+ return function;
+ }
+
+ private boolean nullable(SqlExpression expression) {
+ if (expression instanceof Literal) {
+ return ((Literal) expression).literalType() == LiteralType.NULL;
+ }
+ if (expression instanceof InputReference) {
+ return field.isOptional();
+ }
+ if (expression instanceof IsNull) {
+ // IS NULL and IS NOT NULL return a non-null Boolean, even for a nullable operand.
+ return false;
+ }
+ if (expression instanceof Not
+ || expression instanceof LogicalExpression
+ || expression instanceof Comparison
+ || expression instanceof In
+ || expression instanceof Between
+ || expression instanceof Like) {
+ return expression.children().stream().anyMatch(this::nullable);
+ }
+ if (expression instanceof CaseExpression) {
+ CaseExpression choice = (CaseExpression) expression;
+ if (choice.fallback() == null || nullable(choice.fallback())) {
+ return true;
+ }
+ for (CaseBranch branch : choice.branches()) {
+ if (nullable(branch.result())) {
+ return true;
+ }
+ }
+ return false;
+ }
+ if (expression instanceof FunctionCall) {
+ FunctionCall call = (FunctionCall) expression;
+ switch (call.function()) {
+ case CURRENT_USER:
+ case IS_GROUP_MEMBER:
+ case MASK_TO_FIXED_VALUE:
+ return false;
+ case REPLACE_WITH_NULL:
+ return true;
+ default:
+ for (SqlExpression argument : call.arguments()) {
+ if (nullable(argument)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+ return true;
+ }
+}
diff --git a/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlRestrictionPredicates.java b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlRestrictionPredicates.java
new file mode 100644
index 0000000000..a7c13a1180
--- /dev/null
+++ b/iceberg/iceberg-rest-server-experiment/src/main/java/org/apache/gravitino/iceberg/service/restriction/SqlRestrictionPredicates.java
@@ -0,0 +1,449 @@
+/*
+ * 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.iceberg.service.restriction;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.function.Function;
+import org.apache.gravitino.iceberg.service.restriction.SqlRestrictionBinding.Term;
+import org.apache.gravitino.policy.sql.Between;
+import org.apache.gravitino.policy.sql.CaseBranch;
+import org.apache.gravitino.policy.sql.CaseExpression;
+import org.apache.gravitino.policy.sql.Comparison;
+import org.apache.gravitino.policy.sql.ComparisonOperator;
+import org.apache.gravitino.policy.sql.FunctionCall;
+import org.apache.gravitino.policy.sql.In;
+import org.apache.gravitino.policy.sql.InputReference;
+import org.apache.gravitino.policy.sql.IsNull;
+import org.apache.gravitino.policy.sql.Like;
+import org.apache.gravitino.policy.sql.Literal;
+import org.apache.gravitino.policy.sql.LiteralType;
+import org.apache.gravitino.policy.sql.LogicalExpression;
+import org.apache.gravitino.policy.sql.LogicalOperator;
+import org.apache.gravitino.policy.sql.Not;
+import org.apache.gravitino.policy.sql.SqlExpression;
+import org.apache.gravitino.policy.sql.SqlFunction;
+import org.apache.gravitino.policy.sql.SqlType;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.Types;
+
+/** Lowers SQL three-valued predicates to disjoint Iceberg true/false predicates. */
+final class SqlRestrictionPredicates {
+ private final SqlRestrictionBinding binding;
+ private int work;
+
+ SqlRestrictionPredicates(SqlRestrictionBinding binding) {
+ this.binding = binding;
+ }
+
+ SqlPredicateResult resolve(SqlExpression expression) {
+ step();
+ if (expression instanceof Not) {
+ return resolve(((Not) expression).operand()).not();
+ }
+ if (expression instanceof LogicalExpression) {
+ LogicalExpression logical = (LogicalExpression) expression;
+ List<Expression> trueExpressions = new ArrayList<>();
+ List<Expression> falseExpressions = new ArrayList<>();
+ for (SqlExpression operand : logical.operands()) {
+ SqlPredicateResult child = resolve(operand);
+ trueExpressions.add(child.trueExpression());
+ falseExpressions.add(child.falseExpression());
+ }
+ boolean and = logical.operator() == LogicalOperator.AND;
+ return new SqlPredicateResult(
+ SqlRestrictionCanonicalizer.combine(and, trueExpressions),
+ SqlRestrictionCanonicalizer.combine(!and, falseExpressions));
+ }
+ if (expression instanceof CaseExpression) {
+ return resolveCase((CaseExpression) expression, this::resolve);
+ }
+ if (expression instanceof Comparison) {
+ Comparison comparison = (Comparison) expression;
+ return comparison(comparison.operator(), comparison.left(), comparison.right());
+ }
+ if (expression instanceof IsNull) {
+ IsNull test = (IsNull) expression;
+ SqlPredicateResult result = isNull(test.operand());
+ return test.negated() ? result.not() : result;
+ }
+ if (expression instanceof In) {
+ In in = (In) expression;
+ return in(in.operand(), in.values());
+ }
+ if (expression instanceof Between) {
+ Between between = (Between) expression;
+ return comparison(ComparisonOperator.GTE, between.operand(), between.lower())
+ .and(comparison(ComparisonOperator.LTE, between.operand(), between.upper()));
+ }
+ if (expression instanceof Like) {
+ Like like = (Like) expression;
+ return like(like.operand(), like.pattern().value());
+ }
+ if (expression instanceof FunctionCall
+ && ((FunctionCall) expression).function() == SqlFunction.IS_NAN) {
+ return isNaN(((FunctionCall) expression).arguments().get(0));
+ }
+ if (expression instanceof InputReference) {
+ Term term = binding.term(expression);
+ return new SqlPredicateResult(
+ binding.bind(term, Expressions.equal(term.expression, true)),
+ binding.bind(term, Expressions.equal(term.expression, false)));
+ }
+ Literal literal = binding.constant(expression);
+ Object value = SqlRestrictionLiterals.value(literal, Types.BooleanType.get());
+ return SqlPredicateResult.constant((Boolean) value);
+ }
+
+ Literal constantScalar(SqlExpression expression) {
+ if (expression instanceof CaseExpression) {
+ CaseExpression choice = (CaseExpression) expression;
+ for (CaseBranch branch : choice.branches()) {
+ SqlPredicateResult condition =
+ choice.selector() == null
+ ? resolve(branch.condition())
+ : comparison(ComparisonOperator.EQ, choice.selector(), branch.condition());
+ if (!condition.isConstant()) {
+ throw SqlRestrictionBinding.unsupported("a row-dependent scalar CASE");
+ }
+ if (condition.trueExpression().op() == Expression.Operation.TRUE) {
+ return constantScalar(branch.result());
+ }
+ }
+ return choice.fallback() == null
+ ? SqlRestrictionBinding.nullLiteral()
+ : constantScalar(choice.fallback());
+ }
+ if (expression instanceof Literal
+ || expression instanceof FunctionCall
+ && ((FunctionCall) expression).function() != SqlFunction.IS_NAN) {
+ return binding.constant(expression);
+ }
+ SqlPredicateResult value = resolve(expression);
+ if (!value.isConstant()) {
+ throw SqlRestrictionBinding.unsupported("a row-dependent scalar result");
+ }
+ if (value.trueExpression().op() == Expression.Operation.TRUE) {
+ return SqlRestrictionBinding.bool(true);
+ }
+ if (value.falseExpression().op() == Expression.Operation.TRUE) {
+ return SqlRestrictionBinding.bool(false);
+ }
+ return SqlRestrictionBinding.nullLiteral();
+ }
+
+ SqlPredicateResult equal(SqlExpression left, SqlExpression right) {
+ return comparison(ComparisonOperator.EQ, left, right);
+ }
+
+ private void step() {
+ if (++work > 16384) {
+ throw new IllegalArgumentException("SQL restriction compilation exceeds work limit");
+ }
+ }
+
+ private SqlPredicateResult comparison(
+ ComparisonOperator operator, SqlExpression left, SqlExpression right) {
+ step();
+ if (left instanceof CaseExpression) {
+ return resolveCase((CaseExpression) left, value -> comparison(operator, value, right));
+ }
+ if (right instanceof CaseExpression) {
+ return resolveCase((CaseExpression) right, value -> comparison(operator, left, value));
+ }
+ if (booleanShape(left) || booleanShape(right)) {
+ SqlPredicateResult a = resolve(left);
+ SqlPredicateResult b = resolve(right);
+ SqlPredicateResult equality =
+ new SqlPredicateResult(
+ Expressions.or(
+ Expressions.and(a.trueExpression(), b.trueExpression()),
+ Expressions.and(a.falseExpression(), b.falseExpression())),
+ Expressions.or(
+ Expressions.and(a.trueExpression(), b.falseExpression()),
+ Expressions.and(a.falseExpression(), b.trueExpression())));
+ return operator == ComparisonOperator.EQ ? equality : equality.not();
+ }
+ boolean leftRow = rowDependent(left);
+ boolean rightRow = rowDependent(right);
+ if (leftRow && rightRow) {
+ throw SqlRestrictionBinding.unsupported("column-to-column comparisons");
+ }
+ if (leftRow || rightRow) {
+ Term term = binding.term(leftRow ? left : right);
+ Literal literal = constantScalar(leftRow ? right : left);
+ Object value = term.value(literal);
+ if (value == null) {
+ return SqlPredicateResult.constant(null);
+ }
+ ComparisonOperator normalized = leftRow ? operator : invert(operator);
+ Expression predicate = binding.bind(term, predicate(normalized, term, value));
+ Expression present = binding.bind(term, Expressions.notNull(term.field.name()));
+ // Iceberg EQ is false for null, while several negated/ordering operations include null.
+ Expression trueExpression =
+ normalized == ComparisonOperator.EQ ? predicate : Expressions.and(present, predicate);
+ return new SqlPredicateResult(
+ trueExpression, Expressions.and(present, Expressions.not(predicate)));
+ }
+ Literal a = constantScalar(left);
+ Literal b = constantScalar(right);
+ Type type =
+ a.type() == null
+ ? b.type() == null ? null : SqlRestrictionLiterals.type(b.type())
+ : SqlRestrictionLiterals.type(a.type());
+ if (type != null
+ && (type.typeId() == Type.TypeID.BINARY
+ || type.typeId() == Type.TypeID.BOOLEAN && operator.ordered())) {
+ throw new IllegalArgumentException("Unsupported value comparison for " + type);
+ }
+ Object av =
+ type == null
+ ? a.literalType() == LiteralType.NULL ? null : new BigDecimal(a.value())
+ : SqlRestrictionLiterals.value(a, type);
+ Object bv =
+ type == null
+ ? b.literalType() == LiteralType.NULL ? null : new BigDecimal(b.value())
+ : SqlRestrictionLiterals.value(b, type);
+ if (av == null || bv == null) {
+ return SqlPredicateResult.constant(null);
+ }
+ int result = SqlRestrictionLiterals.compare(av, bv);
+ switch (operator) {
+ case EQ:
+ return SqlPredicateResult.constant(result == 0);
+ case NEQ:
+ return SqlPredicateResult.constant(result != 0);
+ case LT:
+ return SqlPredicateResult.constant(result < 0);
+ case LTE:
+ return SqlPredicateResult.constant(result <= 0);
+ case GT:
+ return SqlPredicateResult.constant(result > 0);
+ case GTE:
+ return SqlPredicateResult.constant(result >= 0);
+ default:
+ throw new IllegalArgumentException("Unsupported comparison operator");
+ }
+ }
+
+ private SqlPredicateResult isNull(SqlExpression operand) {
+ if (operand instanceof CaseExpression) {
+ return resolveCase((CaseExpression) operand, this::isNull);
+ }
+ if (rowDependent(operand)) {
+ Term term = binding.term(operand);
+ return new SqlPredicateResult(
+ binding.bind(term, Expressions.isNull(term.field.name())),
+ binding.bind(term, Expressions.notNull(term.field.name())));
+ }
+ return SqlPredicateResult.constant(constantScalar(operand).literalType() == LiteralType.NULL);
+ }
+
+ private SqlPredicateResult in(SqlExpression operand, List<SqlExpression> elements) {
+ if (operand instanceof CaseExpression) {
+ return resolveCase((CaseExpression) operand, value -> in(value, elements));
+ }
+ List<SqlPredicateResult> equalities = new ArrayList<>();
+ if (!rowDependent(operand)) {
+ SqlPredicateResult result = SqlPredicateResult.constant(false);
+ for (SqlExpression element : elements) {
+ equalities.add(comparison(ComparisonOperator.EQ, operand, element));
+ }
+ for (SqlPredicateResult equality : equalities) {
+ result = result.or(equality);
+ }
+ return result;
+ }
+ Term term = binding.term(operand);
+ Map<String, Object> values = new TreeMap<>();
+ boolean containsNull = false;
+ for (SqlExpression element : elements) {
+ Object value = term.value((Literal) element);
+ if (value == null) {
+ containsNull = true;
+ } else {
+ values.put(SqlRestrictionLiterals.canonicalValue(value), value);
+ }
+ }
+ if (values.isEmpty()) {
+ return SqlPredicateResult.constant(null);
+ }
+ Expression trueExpression =
+ binding.bind(term, Expressions.in(term.expression, values.values()));
+ Expression falseExpression =
+ containsNull
+ ? Expressions.alwaysFalse()
+ : Expressions.and(
+ binding.bind(term, Expressions.notNull(term.field.name())),
+ binding.bind(term, Expressions.notIn(term.expression, values.values())));
+ return new SqlPredicateResult(trueExpression, falseExpression);
+ }
+
+ private SqlPredicateResult like(SqlExpression operand, String pattern) {
+ if (operand instanceof CaseExpression) {
+ return resolveCase((CaseExpression) operand, value -> like(value, pattern));
+ }
+ String prefix = pattern.substring(0, pattern.length() - 1);
+ if (!rowDependent(operand)) {
+ Object value = SqlRestrictionLiterals.value(constantScalar(operand), Types.StringType.get());
+ return value == null
+ ? SqlPredicateResult.constant(null)
+ : SqlPredicateResult.constant(((String) value).startsWith(prefix));
+ }
+ Term term = binding.term(operand);
+ Expression raw = binding.bind(term, Expressions.startsWith(term.field.name(), prefix));
+ Expression present = binding.bind(term, Expressions.notNull(term.field.name()));
+ return new SqlPredicateResult(
+ Expressions.and(present, raw), Expressions.and(present, Expressions.not(raw)));
+ }
+
+ private SqlPredicateResult isNaN(SqlExpression operand) {
+ if (operand instanceof CaseExpression) {
+ return resolveCase((CaseExpression) operand, this::isNaN);
+ }
+ if (!rowDependent(operand)) {
+ Literal literal = constantScalar(operand);
+ if (literal.literalType() == LiteralType.NULL) {
+ return SqlPredicateResult.constant(null);
+ }
+ Object value =
+ SqlRestrictionLiterals.value(literal, SqlRestrictionLiterals.type(literal.type()));
+ return SqlPredicateResult.constant(
+ value instanceof Float ? Float.isNaN((Float) value) : Double.isNaN((Double) value));
+ }
+ Term term = binding.term(operand);
+ Expression present = binding.bind(term, Expressions.notNull(term.field.name()));
+ return new SqlPredicateResult(
+ binding.bind(term, Expressions.isNaN(term.expression)),
+ Expressions.and(present, binding.bind(term, Expressions.notNaN(term.expression))));
+ }
+
+ private SqlPredicateResult resolveCase(
+ CaseExpression choice, Function<SqlExpression, SqlPredicateResult> result) {
+ List<SqlPredicateResult> conditions = new ArrayList<>();
+ List<SqlPredicateResult> values = new ArrayList<>();
+ SqlPredicateResult fallback = null;
+ for (CaseBranch branch : choice.branches()) {
+ SqlPredicateResult condition =
+ choice.selector() == null
+ ? resolve(branch.condition())
+ : comparison(ComparisonOperator.EQ, choice.selector(), branch.condition());
+ if (condition.trueExpression().op() == Expression.Operation.FALSE) {
+ continue;
+ }
+ SqlPredicateResult value = result.apply(branch.result());
+ if (condition.trueExpression().op() == Expression.Operation.TRUE) {
+ fallback = value;
+ break;
+ }
+ conditions.add(condition);
+ values.add(value);
+ }
+ if (fallback == null) {
+ fallback =
+ choice.fallback() == null
+ ? result.apply(SqlRestrictionBinding.nullLiteral())
+ : result.apply(choice.fallback());
+ }
+ for (int i = conditions.size() - 1; i >= 0; i--) {
+ Expression selected = conditions.get(i).trueExpression();
+ SqlPredicateResult value = values.get(i);
+ fallback =
+ new SqlPredicateResult(
+ Expressions.or(
+ Expressions.and(selected, value.trueExpression()),
+ Expressions.and(Expressions.not(selected), fallback.trueExpression())),
+ Expressions.or(
+ Expressions.and(selected, value.falseExpression()),
+ Expressions.and(Expressions.not(selected), fallback.falseExpression())));
+ }
+ return fallback;
+ }
+
+ private static boolean rowDependent(SqlExpression expression) {
+ if (expression instanceof InputReference) {
+ return true;
+ }
+ for (SqlExpression child : expression.children()) {
+ if (rowDependent(child)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static boolean booleanShape(SqlExpression expression) {
+ if (expression instanceof Literal) {
+ return ((Literal) expression).literalType() == LiteralType.BOOLEAN;
+ }
+ if (expression instanceof InputReference) {
+ return SqlType.BOOLEAN.equals(expression.type());
+ }
+ if (expression instanceof FunctionCall) {
+ SqlFunction function = ((FunctionCall) expression).function();
+ return function == SqlFunction.IS_GROUP_MEMBER || function == SqlFunction.IS_NAN;
+ }
+ return expression instanceof LogicalExpression
+ || expression instanceof Not
+ || expression instanceof Comparison
+ || expression instanceof In
+ || expression instanceof Between
+ || expression instanceof Like
+ || expression instanceof IsNull;
+ }
+
+ private static Expression predicate(ComparisonOperator operator, Term term, Object value) {
+ switch (operator) {
+ case EQ:
+ return Expressions.equal(term.expression, value);
+ case NEQ:
+ return Expressions.notEqual(term.expression, value);
+ case LT:
+ return Expressions.lessThan(term.expression, value);
+ case LTE:
+ return Expressions.lessThanOrEqual(term.expression, value);
+ case GT:
+ return Expressions.greaterThan(term.expression, value);
+ case GTE:
+ return Expressions.greaterThanOrEqual(term.expression, value);
+ default:
+ throw new IllegalArgumentException("Unsupported comparison operator");
+ }
+ }
+
+ private static ComparisonOperator invert(ComparisonOperator operator) {
+ switch (operator) {
+ case LT:
+ return ComparisonOperator.GT;
+ case LTE:
+ return ComparisonOperator.GTE;
+ case GT:
+ return ComparisonOperator.LT;
+ case GTE:
+ return ComparisonOperator.LTE;
+ default:
+ return operator;
+ }
+ }
+}
diff --git a/iceberg/iceberg-rest-server-experiment/src/test/java/org/apache/gravitino/iceberg/service/restriction/TestExperimentalIcebergReadRestrictionLoader.java b/iceberg/iceberg-rest-server-experiment/src/test/java/org/apache/gravitino/iceberg/service/restriction/TestExperimentalIcebergReadRestrictionLoader.java
index 2b4b5893cf..78d4096df7 100644
--- a/iceberg/iceberg-rest-server-experiment/src/test/java/org/apache/gravitino/iceberg/service/restriction/TestExperimentalIcebergReadRestrictionLoader.java
+++ b/iceberg/iceberg-rest-server-experiment/src/test/java/org/apache/gravitino/iceberg/service/restriction/TestExperimentalIcebergReadRestrictionLoader.java
@@ -206,12 +206,13 @@ public class TestExperimentalIcebergReadRestrictionLoader {
MetadataObject object = invocation.getArgument(1);
if (object.type() == MetadataObject.Type.TABLE) {
return new PolicyEntity[] {
- rowPolicy(1, "regional", "filter := col(\"region\") == \"US\"")
+ rowPolicy(1, "regional", "(region STRING) RETURNS BOOLEAN -> region = 'US'")
};
}
if (object.type() == MetadataObject.Type.COLUMN && "region".equals(object.name())) {
return new PolicyEntity[] {
- maskPolicy(2, "regional_mask", "mask := action(\"show-last-4\")")
+ maskPolicy(
+ 2, "regional_mask", "(value STRING) RETURNS STRING -> show_last_4(value)")
};
}
return new PolicyEntity[0];
@@ -301,15 +302,21 @@ public class TestExperimentalIcebergReadRestrictionLoader {
void testResolvesAndDeduplicatesCanonicalPolicies() {
PolicyEntity[] rowPolicies =
new PolicyEntity[] {
- rowPolicy(1, "first", "filter := col(\"region\") == \"US\" and col(\"id\") in [2, 1]"),
- rowPolicy(2, "second", "filter := col(\"id\") in [1, 2] and col(\"region\") == \"US\"")
+ rowPolicy(
+ 1,
+ "first",
+ "(region STRING, id INTEGER) RETURNS BOOLEAN -> region = 'US' AND id IN (2, 1)"),
+ rowPolicy(
+ 2,
+ "second",
+ "(id INTEGER, region STRING) RETURNS BOOLEAN -> id IN (1, 2) AND region = 'US'")
};
Map<Integer, PolicyEntity[]> columnPolicies = new LinkedHashMap<>();
columnPolicies.put(
2,
new PolicyEntity[] {
- maskPolicy(3, "mask_one", "mask := action(\"show-last-4\")"),
- maskPolicy(4, "mask_two", "mask := action(\"show-last-4\")")
+ maskPolicy(3, "mask_one", "(value STRING) RETURNS STRING -> show_last_4(value)"),
+ maskPolicy(4, "mask_two", "(value STRING) RETURNS STRING -> show_last_4(value)")
});
ReadRestrictions restrictions =
@@ -324,7 +331,8 @@ public class TestExperimentalIcebergReadRestrictionLoader {
@Test
void testRejectsTableMaskOnIncompatibleFieldTypes() {
- PolicyEntity mask = maskPolicy(1, "string_mask", "mask := action(\"show-last-4\")");
+ PolicyEntity mask =
+ maskPolicy(1, "string_mask", "(value STRING) RETURNS STRING -> show_last_4(value)");
Map<Integer, PolicyEntity[]> policiesByField = new LinkedHashMap<>();
for (int fieldId = 1; fieldId <= 3; fieldId++) {
policiesByField.put(fieldId, new PolicyEntity[] {mask});
@@ -342,7 +350,8 @@ public class TestExperimentalIcebergReadRestrictionLoader {
@Test
void testRejectsReplaceWithNullOnRequiredField() {
- PolicyEntity mask = maskPolicy(1, "null_mask", "mask := action(\"replace-with-null\")");
+ PolicyEntity mask =
+ maskPolicy(1, "null_mask", "(value INTEGER) RETURNS INTEGER -> replace_with_null(value)");
Map<Integer, PolicyEntity[]> policiesByField = new LinkedHashMap<>();
policiesByField.put(1, new PolicyEntity[] {mask});
policiesByField.put(2, new PolicyEntity[] {mask});
@@ -355,29 +364,28 @@ public class TestExperimentalIcebergReadRestrictionLoader {
}
@Test
- void testUnselectedIncompatibleMaskDoesNotRejectTable() {
+ void testRejectsNullableMaskResultForRequiredColumn() {
PolicyEntity mask =
maskPolicy(
1,
"conditional_mask",
- "mask := action(\"mask-to-fixed-value\") if true "
- + "else := action(\"replace-with-null\")");
+ "(value INTEGER) RETURNS INTEGER -> CASE WHEN TRUE THEN mask_to_fixed_value(value) ELSE replace_with_null(value) END");
Map<Integer, PolicyEntity[]> policiesByField = new LinkedHashMap<>();
policiesByField.put(1, new PolicyEntity[] {mask});
- ReadRestrictions restrictions =
- ExperimentalIcebergReadRestrictionLoader.resolve(
- new PolicyEntity[0], policiesByField, SCHEMA, context("alice"));
-
- assertEquals(1, restrictions.columnProjections().size());
- assertEquals("mask-to-fixed-value", restrictions.columnProjections().get(0).name());
- assertEquals(1, restrictions.columnProjections().get(0).fieldId());
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ ExperimentalIcebergReadRestrictionLoader.resolve(
+ new PolicyEntity[0], policiesByField, SCHEMA, context("alice")));
}
@Test
void testBindsSubjectForRowFilterAndMask() {
PolicyEntity[] rowPolicies =
- new PolicyEntity[] {rowPolicy(1, "owner", "filter := col(\"owner\") == session_user()")};
+ new PolicyEntity[] {
+ rowPolicy(1, "owner", "(owner STRING) RETURNS BOOLEAN -> owner = CURRENT_USER()")
+ };
Map<Integer, PolicyEntity[]> columnPolicies = new LinkedHashMap<>();
columnPolicies.put(
2,
@@ -385,8 +393,7 @@ public class TestExperimentalIcebergReadRestrictionLoader {
maskPolicy(
2,
"conditional_mask",
- "mask := action(\"show-last-4\") if is_group_member(\"auditors\") "
- + "else := action(\"replace-with-null\")")
+ "(value STRING) RETURNS STRING -> CASE WHEN is_group_member('auditors') THEN show_last_4(value) ELSE replace_with_null(value) END")
});
ReadRestrictions restrictions =
@@ -406,8 +413,8 @@ public class TestExperimentalIcebergReadRestrictionLoader {
void testRejectsDistinctRowFilters() {
PolicyEntity[] policies =
new PolicyEntity[] {
- rowPolicy(1, "us", "filter := col(\"region\") == \"US\""),
- rowPolicy(2, "eu", "filter := col(\"region\") == \"EU\"")
+ rowPolicy(1, "us", "(region STRING) RETURNS BOOLEAN -> region = 'US'"),
+ rowPolicy(2, "eu", "(region STRING) RETURNS BOOLEAN -> region = 'EU'")
};
IllegalArgumentException exception =
@@ -425,8 +432,8 @@ public class TestExperimentalIcebergReadRestrictionLoader {
void testIgnoresAllowAllAlongsideRowFilter() {
PolicyEntity[] policies =
new PolicyEntity[] {
- rowPolicy(1, "allow", "filter := true"),
- rowPolicy(2, "us", "filter := col(\"region\") == \"US\"")
+ rowPolicy(1, "allow", "() RETURNS BOOLEAN -> TRUE"),
+ rowPolicy(2, "us", "(region STRING) RETURNS BOOLEAN -> region = 'US'")
};
ReadRestrictions restrictions =
@@ -439,7 +446,8 @@ public class TestExperimentalIcebergReadRestrictionLoader {
void testAllAllowAllRowFiltersAreUnrestricted() {
PolicyEntity[] policies =
new PolicyEntity[] {
- rowPolicy(1, "first", "filter := true"), rowPolicy(2, "second", "filter := true")
+ rowPolicy(1, "first", "() RETURNS BOOLEAN -> TRUE"),
+ rowPolicy(2, "second", "() RETURNS BOOLEAN -> TRUE")
};
ReadRestrictions restrictions =
@@ -452,7 +460,10 @@ public class TestExperimentalIcebergReadRestrictionLoader {
void testLoadErrorDoesNotExposePolicyContent() {
PolicyEntity[] policies =
new PolicyEntity[] {
- rowPolicy(1, "secret_policy", "filter := col(\"secret_column\") == \"secret_value\"")
+ rowPolicy(
+ 1,
+ "secret_policy",
+ "(secret_column STRING) RETURNS BOOLEAN -> secret_column = 'secret_value'")
};
IllegalStateException exception =
@@ -483,7 +494,7 @@ public class TestExperimentalIcebergReadRestrictionLoader {
rowPolicy(
1,
"restrict_members",
- "filter := false if is_group_member(\"auditors\") else := true")
+ "() RETURNS BOOLEAN -> CASE WHEN is_group_member('auditors') THEN FALSE ELSE TRUE END")
},
Collections.emptyMap(),
SCHEMA,
@@ -496,8 +507,7 @@ public class TestExperimentalIcebergReadRestrictionLoader {
rowPolicy(
2,
"restrict_non_members",
- "filter := true if is_group_member(\"auditors\") "
- + "else := col(\"owner\") == session_user()")
+ "(owner STRING) RETURNS BOOLEAN -> CASE WHEN is_group_member('auditors') THEN TRUE ELSE owner = CURRENT_USER() END")
},
Collections.emptyMap(),
SCHEMA,
@@ -537,8 +547,8 @@ public class TestExperimentalIcebergReadRestrictionLoader {
policies.put(
2,
new PolicyEntity[] {
- maskPolicy(1, "first", "mask := action(\"show-first-4\")"),
- maskPolicy(2, "last", "mask := action(\"show-last-4\")")
+ maskPolicy(1, "first", "(value STRING) RETURNS STRING -> show_first_4(value)"),
+ maskPolicy(2, "last", "(value STRING) RETURNS STRING -> show_last_4(value)")
});
IllegalArgumentException exception =
@@ -554,7 +564,7 @@ public class TestExperimentalIcebergReadRestrictionLoader {
void testOmitsConstantTrueRowFilter() {
ReadRestrictions restrictions =
ExperimentalIcebergReadRestrictionLoader.resolve(
- new PolicyEntity[] {rowPolicy(1, "allow", "filter := true")},
+ new PolicyEntity[] {rowPolicy(1, "allow", "() RETURNS BOOLEAN -> TRUE")},
Collections.emptyMap(),
SCHEMA,
context("alice"));
diff --git a/iceberg/iceberg-rest-server-experiment/src/test/java/org/apache/gravitino/iceberg/service/restriction/TestIcebergReadRestrictionConverter.java b/iceberg/iceberg-rest-server-experiment/src/test/java/org/apache/gravitino/iceberg/service/restriction/TestIcebergReadRestrictionConverter.java
index c76d4bacc0..59e169ac15 100644
--- a/iceberg/iceberg-rest-server-experiment/src/test/java/org/apache/gravitino/iceberg/service/restriction/TestIcebergReadRestrictionConverter.java
+++ b/iceberg/iceberg-rest-server-experiment/src/test/java/org/apache/gravitino/iceberg/service/restriction/TestIcebergReadRestrictionConverter.java
@@ -18,37 +18,34 @@
*/
package org.apache.gravitino.iceberg.service.restriction;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
+import java.time.LocalDate;
+import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
import org.apache.gravitino.iceberg.service.restriction.IcebergReadRestrictionConverter.BindingContext;
-import org.apache.gravitino.policy.rego.RestrictedRegoExpressionParserFacade;
-import org.apache.gravitino.policy.rego.RestrictedRegoProgram.ColumnMask;
-import org.apache.gravitino.policy.rego.RestrictedRegoProgram.RowFilter;
+import org.apache.gravitino.policy.sql.RestrictedSqlExpressionParserFacade;
+import org.apache.gravitino.policy.sql.SqlDefinition;
import org.apache.iceberg.Schema;
+import org.apache.iceberg.StructLike;
import org.apache.iceberg.expressions.Binder;
import org.apache.iceberg.expressions.BoundLiteralPredicate;
+import org.apache.iceberg.expressions.BoundPredicate;
import org.apache.iceberg.expressions.Expression;
-import org.apache.iceberg.expressions.ExpressionParser;
-import org.apache.iceberg.functions.IcebergFunction;
+import org.apache.iceberg.expressions.ExpressionVisitors;
import org.apache.iceberg.rest.restrictions.ReadRestrictions;
import org.apache.iceberg.rest.restrictions.ReadRestrictionsParser;
import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
-/** Tests design-contract binding from restricted Rego to Iceberg read restrictions. */
+/** Executes converted SQL predicates against actual Iceberg bound predicates and field IDs. */
public class TestIcebergReadRestrictionConverter {
-
private static final Schema SCHEMA =
new Schema(
Types.NestedField.required(1, "id", Types.IntegerType.get()),
@@ -64,356 +61,684 @@ public class TestIcebergReadRestrictionConverter {
10,
"nested",
Types.StructType.of(Types.NestedField.optional(11, "value", Types.StringType.get()))),
- Types.NestedField.optional(12, "double_score", Types.DoubleType.get()));
+ Types.NestedField.optional(12, "double_score", Types.DoubleType.get()),
+ Types.NestedField.optional(13, "flag", Types.BooleanType.get()),
+ Types.NestedField.optional(14, "zoned", Types.TimestampType.withZone()),
+ Types.NestedField.optional(15, "bytes", Types.BinaryType.get()),
+ Types.NestedField.optional(16, "counter", Types.LongType.get()),
+ Types.NestedField.optional(17, "other_flag", Types.BooleanType.get()));
@Test
- void testBindsContextAndColumnToClosedFieldIdPredicate() {
- RowFilter filter =
- RestrictedRegoExpressionParserFacade.parseRowFilter(
- "filter := col(\"region\") == \"US\" if is_group_member(\"auditors\") "
- + "else := col(\"owner\") == session_user()");
-
- ReadRestrictions restrictions =
- IcebergReadRestrictionConverter.convert(
- Optional.of(filter),
- Collections.emptyMap(),
- SCHEMA,
- context("alice", Collections.singletonMap("auditors", false)));
-
- assertNotNull(restrictions.rowFilter());
- assertTrue(Binder.isBound(restrictions.rowFilter()));
- assertEquals(Expression.Operation.EQ, restrictions.rowFilter().op());
- BoundLiteralPredicate<?> predicate = (BoundLiteralPredicate<?>) restrictions.rowFilter();
- assertEquals(3, predicate.ref().fieldId());
- assertEquals("alice", predicate.literal().value().toString());
-
- String json = ReadRestrictionsParser.toJson(restrictions);
- assertTrue(json.contains("\"id\":3"));
- assertTrue(json.contains("alice"), json);
- assertFalse(json.contains("session_user"));
- assertFalse(json.contains("owner"));
+ void testBindsDeclaredParametersAndSubjectToFieldIds() {
+ ReadRestrictions result = filter("owner STRING", "owner = CURRENT_USER()");
+ BoundLiteralPredicate<?> predicate = (BoundLiteralPredicate<?>) result.rowFilter();
+ Assertions.assertEquals(3, predicate.ref().fieldId());
+ Assertions.assertEquals("alice", predicate.literal().value().toString());
+ Assertions.assertTrue(Binder.isBound(result.rowFilter()));
+ String json = ReadRestrictionsParser.toJson(result);
+ Assertions.assertFalse(json.contains("CURRENT_USER"));
+ Assertions.assertFalse(json.contains("owner"));
+ Assertions.assertEquals(json, reboundJson(json));
}
@Test
- void testOmitsTrueAndPreservesFalse() {
- ReadRestrictions allowAll = convertFilter("filter := true", context("alice"));
- assertNull(allowAll.rowFilter());
- assertTrue(allowAll.isEmpty());
-
- ReadRestrictions denyAll = convertFilter("filter := false", context("alice"));
- assertNotNull(denyAll.rowFilter());
- assertEquals(Expression.Operation.FALSE, denyAll.rowFilter().op());
+ void testOmitsTrueRetainsFalseAndUnknown() {
+ Assertions.assertTrue(filter("", "TRUE").isEmpty());
+ Assertions.assertEquals(Expression.Operation.FALSE, filter("", "FALSE").rowFilter().op());
+ Assertions.assertEquals(Expression.Operation.FALSE, filter("", "NULL").rowFilter().op());
+ Assertions.assertTrue(filter("", "NULL OR TRUE").isEmpty());
+ Assertions.assertEquals(Expression.Operation.FALSE, filter("", "NOT NULL").rowFilter().op());
+ Assertions.assertTrue(filter("", "NOT (FALSE AND NULL)").isEmpty());
}
@Test
- void testCanonicalizesLogicalChildrenAndInValues() {
- ReadRestrictions first =
- convertFilter(
- "filter := col(\"id\") in [2, 1, 2] and col(\"region\") == \"US\" "
- + "and col(\"region\") == \"US\"",
- context("alice"));
- ReadRestrictions second =
- convertFilter(
- "filter := col(\"region\") == \"US\" and col(\"id\") in [1, 2]", context("alice"));
-
- assertEquals(
- ExpressionParser.toJson(first.rowFilter()), ExpressionParser.toJson(second.rowFilter()));
+ void testSqlComparisonsAndNegationExcludeNulls() {
+ for (String body :
+ Arrays.asList(
+ "region <> 'US'",
+ "NOT region = 'US'",
+ "NOT NOT region <> 'US'",
+ "region < 'ZZ'",
+ "region <= 'ZZ'",
+ "region > 'AA'",
+ "region >= 'AA'")) {
+ ReadRestrictions result = filter("region STRING", body);
+ Assertions.assertFalse(eval(result, row(2, null)), body);
+ Assertions.assertTrue(eval(result, row(2, "CA")), body);
+ }
+ Assertions.assertTrue(
+ eval(filter("region STRING", "region IS NULL OR region <> 'US'"), row(2, null)));
+ Assertions.assertFalse(eval(filter("region STRING", "region = NULL"), row(2, "US")));
+ Assertions.assertFalse(eval(filter("region STRING", "region <> NULL"), row(2, "US")));
}
@Test
- void testBindsEverySupportedLiteralFamily() {
- String source =
- "filter := col(\"id\") == 7"
- + " and col(\"amount\") == 12.30"
- + " and col(\"event_date\") == \"2026-10-12\""
- + " and col(\"event_time\") == \"12:34:56.123456\""
- + " and col(\"event_ts\") == \"2026-10-12T12:34:56.123456\""
- + " and col(\"score\") == 0.5"
- + " and col(\"double_score\") == 0.5";
-
- ReadRestrictions restrictions = convertFilter(source, context("alice"));
+ void testUnicodeStringOrderingMatchesBoundPredicates() {
+ String bmp = "\uE000";
+ String supplementary = "\uD800\uDC00";
+ Assertions.assertTrue(
+ eval(filter("region STRING", "region < '" + supplementary + "'"), row(2, bmp)));
+ String[][] pairs = {
+ {bmp, supplementary},
+ {supplementary, bmp},
+ {bmp, bmp},
+ {"prefix" + bmp, "prefix" + supplementary},
+ {supplementary, supplementary + "suffix"}
+ };
+ for (String[] pair : pairs) {
+ for (String operator : Arrays.asList("=", "<>", "<", "<=", ">", ">=")) {
+ String comparison = "'" + pair[0] + "' " + operator + " '" + pair[1] + "'";
+ boolean columnResult =
+ eval(
+ filter("region STRING", "region " + operator + " '" + pair[1] + "'"),
+ row(2, pair[0]));
+ Assertions.assertEquals(columnResult, eval(filter("", comparison), row()), comparison);
+ Assertions.assertEquals(
+ columnResult,
+ eval(filter("", "CASE WHEN " + comparison + " THEN TRUE ELSE FALSE END"), row()),
+ comparison);
+ }
+ }
+ String range = " BETWEEN '\uD7FF' AND '" + supplementary + "'";
+ Assertions.assertTrue(eval(filter("region STRING", "region" + range), row(2, bmp)));
+ Assertions.assertTrue(eval(filter("", "'" + bmp + "'" + range), row()));
+ Assertions.assertFalse(eval(filter("", "'" + bmp + "' NOT" + range), row()));
+ }
- assertNotNull(restrictions.rowFilter());
- assertTrue(Binder.isBound(restrictions.rowFilter()));
- String json = ReadRestrictionsParser.toJson(restrictions);
- assertNotNull(ReadRestrictionsParser.fromJson(json, SCHEMA).rowFilter());
+ @Test
+ void testUnicodeContextComparisonSelectsConsistentMask() {
+ String bmp = "\uE000";
+ String supplementary = "\uD800\uDC00";
+ ReadRestrictions result =
+ IcebergReadRestrictionConverter.convert(
+ Optional.empty(),
+ Collections.singletonMap(
+ 2,
+ mask(
+ "STRING",
+ "CASE WHEN CURRENT_USER() < '"
+ + supplementary
+ + "' THEN show_last_4(value) ELSE show_first_4(value) END")),
+ SCHEMA,
+ context(bmp));
+ Assertions.assertEquals("show-last-4", result.columnProjections().get(0).name());
}
@Test
- void testRejectsInexactAndUnsupportedLiterals() {
- assertThrows(
- IllegalArgumentException.class,
- () -> convertFilter("filter := col(\"id\") == 1.5", context("alice")));
- assertThrows(
- IllegalArgumentException.class,
- () -> convertFilter("filter := col(\"amount\") == 1.234", context("alice")));
- assertThrows(
- IllegalArgumentException.class,
- () -> convertFilter("filter := col(\"score\") == 16777217", context("alice")));
- assertThrows(
- IllegalArgumentException.class,
- () -> convertFilter("filter := col(\"score\") <= 0.1", context("alice")));
- assertThrows(
- IllegalArgumentException.class,
- () -> convertFilter("filter := col(\"double_score\") <= 0.1", context("alice")));
- assertThrows(
- IllegalArgumentException.class,
- () ->
- convertFilter(
- "filter := col(\"event_time\") == \"12:34:56.1234567\"", context("alice")));
- assertThrows(
- IllegalArgumentException.class,
- () ->
- convertFilter(
- "filter := col(\"event_ts\") == \"2026-10-12T12:34:56Z\"", context("alice")));
+ void testBooleanThreeValuedTruthTables() {
+ for (Boolean a : new Boolean[] {true, false, null}) {
+ for (Boolean b : new Boolean[] {true, false, null}) {
+ Map<Integer, Object> row = row(13, a, 17, b);
+ String params = "flag BOOLEAN, other_flag BOOLEAN";
+ Assertions.assertEquals(
+ Boolean.TRUE.equals(a) && Boolean.TRUE.equals(b),
+ eval(filter(params, "flag AND other_flag"), row));
+ Assertions.assertEquals(
+ Boolean.TRUE.equals(a) || Boolean.TRUE.equals(b),
+ eval(filter(params, "flag OR other_flag"), row));
+ Assertions.assertEquals(
+ Boolean.FALSE.equals(a) || Boolean.FALSE.equals(b),
+ eval(filter(params, "NOT (flag AND other_flag)"), row));
+ Assertions.assertEquals(
+ Boolean.FALSE.equals(a) && Boolean.FALSE.equals(b),
+ eval(filter(params, "NOT (flag OR other_flag)"), row));
+ }
+ }
+ Assertions.assertFalse(eval(filter("flag BOOLEAN", "flag = TRUE"), row(13, null)));
+ Assertions.assertTrue(eval(filter("flag BOOLEAN", "flag <> TRUE"), row(13, false)));
}
@Test
- void testPreservesFloatingPointNegativeZero() {
- BoundLiteralPredicate<?> floatPredicate =
- (BoundLiteralPredicate<?>)
- convertFilter("filter := col(\"score\") == -0", context("alice")).rowFilter();
- BoundLiteralPredicate<?> doublePredicate =
- (BoundLiteralPredicate<?>)
- convertFilter("filter := col(\"double_score\") == -0", context("alice")).rowFilter();
-
- assertEquals(
- Float.floatToRawIntBits(-0.0F),
- Float.floatToRawIntBits((Float) floatPredicate.literal().value()));
- assertEquals(
- Double.doubleToRawLongBits(-0.0D),
- Double.doubleToRawLongBits((Double) doublePredicate.literal().value()));
+ void testInAndNotInWithNullElements() {
+ ReadRestrictions in = filter("region STRING", "region IN ('US', NULL)");
+ ReadRestrictions notIn = filter("region STRING", "region NOT IN ('US', NULL)");
+ Assertions.assertTrue(eval(in, row(2, "US")));
+ for (Object value : new Object[] {"CA", null}) {
+ Assertions.assertFalse(eval(in, row(2, value)));
+ Assertions.assertFalse(eval(notIn, row(2, value)));
+ }
+ Assertions.assertFalse(eval(notIn, row(2, "US")));
+ Assertions.assertFalse(eval(filter("region STRING", "NOT region IN (NULL)"), row(2, "US")));
+ Assertions.assertTrue(eval(filter("region STRING", "region NOT IN ('US')"), row(2, "CA")));
+ Assertions.assertTrue(filter("", "'CA' IN ('CA', NULL)").isEmpty());
+ Assertions.assertEquals(
+ Expression.Operation.FALSE, filter("", "'CA' NOT IN ('US', NULL)").rowFilter().op());
}
@Test
- void testRejectsUnknownGroupInsteadOfTreatingItAsNonMembership() {
- RowFilter filter =
- RestrictedRegoExpressionParserFacade.parseRowFilter(
- "filter := true if is_group_member(\"missing\") else := false");
+ void testRangesPrefixAndNaN() {
+ Assertions.assertTrue(eval(filter("id INTEGER", "id BETWEEN 1 AND 3"), row(1, 1)));
+ Assertions.assertTrue(eval(filter("id INTEGER", "id NOT BETWEEN 1 AND 3"), row(1, 4)));
+ Assertions.assertTrue(
+ eval(filter("region STRING", "region LIKE 'Acme%'"), row(2, "Acme Corp")));
+ Assertions.assertFalse(eval(filter("region STRING", "region NOT LIKE 'Acme%'"), row(2, null)));
+ Assertions.assertTrue(eval(filter("score FLOAT", "is_nan(score)"), row(8, Float.NaN)));
+ Assertions.assertFalse(eval(filter("score FLOAT", "NOT is_nan(score)"), row(8, null)));
+ Assertions.assertTrue(eval(filter("score FLOAT", "is_nan(score) = FALSE"), row(8, 0.5F)));
+ }
- assertThrows(
- IllegalArgumentException.class,
- () ->
- IcebergReadRestrictionConverter.convert(
- Optional.of(filter),
- Collections.emptyMap(),
- SCHEMA,
- context("alice", Collections.emptyMap())));
+ @Test
+ void testSearchedSimpleAndNestedCase() {
+ ReadRestrictions searched =
+ filter(
+ "region STRING",
+ "CASE WHEN region = 'US' THEN TRUE WHEN region IS NULL THEN TRUE ELSE FALSE END");
+ Assertions.assertTrue(eval(searched, row(2, null)));
+ Assertions.assertTrue(eval(searched, row(2, "US")));
+ Assertions.assertFalse(eval(searched, row(2, "CA")));
+ ReadRestrictions simple =
+ filter("region STRING", "CASE region WHEN NULL THEN TRUE WHEN 'US' THEN TRUE END");
+ Assertions.assertFalse(eval(simple, row(2, null)));
+ Assertions.assertTrue(eval(simple, row(2, "US")));
+ Assertions.assertFalse(eval(simple, row(2, "CA")));
+ ReadRestrictions negated =
+ filter("region STRING", "NOT CASE WHEN region IS NULL THEN NULL ELSE region = 'US' END");
+ Assertions.assertFalse(eval(negated, row(2, null)));
+ Assertions.assertTrue(eval(negated, row(2, "CA")));
+ Assertions.assertTrue(
+ eval(
+ filter("region STRING", "CASE region WHEN 'US' THEN 'Y' ELSE 'N' END = 'Y'"),
+ row(2, "US")));
+ Assertions.assertTrue(
+ filter("", "CASE WHEN NULL THEN FALSE ELSE CASE 1 WHEN 1 THEN TRUE END END").isEmpty());
}
@Test
- void testBindsUnselectedRowFilterBranchesBeforeFolding() {
- assertThrows(
- IllegalArgumentException.class,
- () ->
- convertFilter(
- "filter := true if true else := col(\"missing\") == 1", context("alice")));
+ void testContextCaseAndFirstMatchSkipUnselectedLookups() {
+ AtomicInteger lookups = new AtomicInteger();
+ BindingContext context =
+ new BindingContext() {
+ @Override
+ public String sessionUser() {
+ return "alice";
+ }
- assertThrows(
+ @Override
+ public Optional<Boolean> groupMembership(String group) {
+ lookups.incrementAndGet();
+ return Optional.empty();
+ }
+ };
+ Assertions.assertTrue(
+ convert(
+ "",
+ "CASE WHEN TRUE THEN TRUE WHEN is_group_member('missing') THEN FALSE END",
+ context)
+ .isEmpty());
+ Assertions.assertEquals(0, lookups.get());
+ Assertions.assertThrows(
IllegalArgumentException.class,
- () -> convertFilter("filter := false and is_group_member(\"missing\")", context("alice")));
+ () -> convert("", "FALSE AND is_group_member('missing')", context));
}
@Test
- void testUsesOneIdentitySnapshotPerConversion() {
- AtomicInteger userLookups = new AtomicInteger();
- AtomicInteger groupLookups = new AtomicInteger();
- BindingContext countingContext =
+ void testContextAndMaskShareOneSnapshot() {
+ AtomicInteger users = new AtomicInteger();
+ AtomicInteger groups = new AtomicInteger();
+ BindingContext context =
new BindingContext() {
@Override
public String sessionUser() {
- userLookups.incrementAndGet();
+ users.incrementAndGet();
return "alice";
}
@Override
- public Optional<Boolean> groupMembership(String group) {
- groupLookups.incrementAndGet();
+ public Optional<Boolean> groupMembership(String name) {
+ groups.incrementAndGet();
return Optional.of(true);
}
};
+ SqlDefinition filter =
+ parse(
+ "region STRING",
+ "region = CURRENT_USER() AND is_group_member('auditors') AND region = CURRENT_USER()");
+ SqlDefinition mask =
+ mask("STRING", "CASE WHEN is_group_member('auditors') THEN value ELSE NULL END");
+ IcebergReadRestrictionConverter.convert(
+ Optional.of(filter), Collections.singletonMap(2, mask), SCHEMA, context);
+ Assertions.assertEquals(1, users.get());
+ Assertions.assertEquals(1, groups.get());
+ }
- convertFilter(
- "filter := col(\"owner\") == session_user() if is_group_member(\"auditors\") "
- + "else := is_group_member(\"auditors\")",
- countingContext);
+ @Test
+ void testUnknownGroupFailsBinding() {
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> filter("", "is_group_member('unknown')"));
+ }
- assertEquals(1, userLookups.get());
- assertEquals(1, groupLookups.get());
+ @Test
+ void testExactDeclarationBindingAndAmbiguity() {
+ for (String params :
+ Arrays.asList(
+ "id LONG",
+ "amount DECIMAL(8,2)",
+ "event_ts TIMESTAMP WITH TIME ZONE",
+ "missing STRING")) {
+ Assertions.assertThrows(IllegalArgumentException.class, () -> filter(params, "TRUE"));
+ }
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> filter("missing STRING", "CASE WHEN TRUE THEN TRUE ELSE missing = 'x' END"));
+ Schema ambiguous =
+ new Schema(
+ Types.NestedField.optional(1, "region", Types.StringType.get()),
+ Types.NestedField.optional(2, "REGION", Types.StringType.get()));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ IcebergReadRestrictionConverter.convert(
+ Optional.of(parse("region STRING", "TRUE")),
+ Collections.emptyMap(),
+ ambiguous,
+ context()));
+ ReadRestrictions exact =
+ IcebergReadRestrictionConverter.convert(
+ Optional.of(parse("\"region\" STRING", "\"region\" = 'US'")),
+ Collections.emptyMap(),
+ ambiguous,
+ context());
+ Assertions.assertEquals(1, ((BoundLiteralPredicate<?>) exact.rowFilter()).ref().fieldId());
+ ReadRestrictions uppercase =
+ IcebergReadRestrictionConverter.convert(
+ Optional.of(parse("\"REGION\" STRING", "\"REGION\" = 'US'")),
+ Collections.emptyMap(),
+ ambiguous,
+ context());
+ Assertions.assertEquals(2, ((BoundLiteralPredicate<?>) uppercase.rowFilter()).ref().fieldId());
}
@Test
- void testSelectsFirstMatchingMaskBranch() {
- ColumnMask mask =
- RestrictedRegoExpressionParserFacade.parseColumnMask(
- "mask := action(\"show-last-4\") if is_group_member(\"auditors\") "
- + "else := action(\"replace-with-null\")");
-
- ReadRestrictions auditor =
- convertMasks(
- Collections.singletonMap(2, mask),
- context("alice", Collections.singletonMap("auditors", true)));
- ReadRestrictions regular =
- convertMasks(
- Collections.singletonMap(2, mask),
- context("alice", Collections.singletonMap("auditors", false)));
-
- assertEquals("show-last-4", auditor.columnProjections().get(0).name());
- assertEquals("replace-with-null", regular.columnProjections().get(0).name());
- assertEquals(2, auditor.columnProjections().get(0).fieldId());
+ void testEveryLiteralFamilyAndCalendarYear() {
+ String params =
+ "id INTEGER, counter LONG, amount DECIMAL(7,2), event_date DATE, event_time TIME, event_ts TIMESTAMP, zoned TIMESTAMP WITH TIME ZONE, score FLOAT, double_score DOUBLE";
+ String body =
+ "id = 7 AND counter = 8 AND amount = 12.30 AND event_date = DATE '2026-10-12' AND event_time = TIME '12:34:56.123456' AND event_ts = TIMESTAMP '2026-10-12 12:34:56.123456' AND zoned = TIMESTAMP WITH TIME ZONE '2026-10-12 08:34:56.123456-04:00' AND score = 0.5 AND double_score = 0.5";
+ ReadRestrictions result = filter(params, body);
+ String json = ReadRestrictionsParser.toJson(result);
+ Assertions.assertEquals(json, reboundJson(json));
+ Assertions.assertTrue(
+ eval(
+ filter("event_date DATE", "year(event_date) = 2026"),
+ row(5, Math.toIntExact(LocalDate.of(2026, 10, 12).toEpochDay()))));
+ Assertions.assertTrue(
+ filter("", "month(DATE '2026-03-12') = 3 AND day(DATE '2026-03-12') = 12").isEmpty());
}
@Test
- void testConvertsEveryMaskAction() {
- Map<String, Integer> actions = new LinkedHashMap<>();
- actions.put("mask-alphanum", 2);
- actions.put("mask-to-fixed-value", 1);
- actions.put("replace-with-null", 2);
- actions.put("show-first-4", 2);
- actions.put("show-last-4", 2);
- actions.put("truncate-to-year", 5);
- actions.put("truncate-to-month", 5);
- actions.put("sha-256-global", 1);
- actions.put("sha-256-query-local", 2);
-
- for (Map.Entry<String, Integer> entry : actions.entrySet()) {
- ColumnMask mask =
- RestrictedRegoExpressionParserFacade.parseColumnMask(
- "mask := action(\"" + entry.getKey() + "\")");
- ReadRestrictions restrictions =
- convertMasks(Collections.singletonMap(entry.getValue(), mask), context("alice"));
- IcebergFunction<?, ?> function = restrictions.columnProjections().get(0);
-
- assertEquals(entry.getKey(), function.name());
- assertEquals(entry.getValue().intValue(), function.fieldId());
- String json = ReadRestrictionsParser.toJson(restrictions);
- assertEquals(
- json, ReadRestrictionsParser.toJson(ReadRestrictionsParser.fromJson(json, SCHEMA)));
+ void testExactNumericBindingAndNegativeZero() {
+ for (String body : Arrays.asList("score = 0.1", "score = 16777217", "double_score = 0.1")) {
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> filter("score FLOAT, double_score DOUBLE", body));
}
+ BoundLiteralPredicate<?> zero =
+ (BoundLiteralPredicate<?>) filter("score FLOAT", "score = -0.0").rowFilter();
+ Assertions.assertEquals(
+ Float.floatToRawIntBits(-0.0F), Float.floatToRawIntBits((Float) zero.literal().value()));
+ BoundLiteralPredicate<?> doubleZero =
+ (BoundLiteralPredicate<?>) filter("double_score DOUBLE", "double_score = -0.0").rowFilter();
+ Assertions.assertEquals(
+ Double.doubleToRawLongBits(-0.0D),
+ Double.doubleToRawLongBits((Double) doubleZero.literal().value()));
}
@Test
- void testMaskValidationFailsClosed() {
- ColumnMask nullMask =
- RestrictedRegoExpressionParserFacade.parseColumnMask(
- "mask := action(\"replace-with-null\")");
- ColumnMask stringMask =
- RestrictedRegoExpressionParserFacade.parseColumnMask("mask := action(\"show-last-4\")");
-
- assertThrows(
- IllegalArgumentException.class,
- () -> convertMasks(Collections.singletonMap(9, nullMask), context("alice")));
- assertThrows(
- IllegalArgumentException.class,
- () -> convertMasks(Collections.singletonMap(1, stringMask), context("alice")));
- assertThrows(
- IllegalArgumentException.class,
- () -> convertMasks(Collections.singletonMap(11, stringMask), context("alice")));
+ void testNullTestsOnRequiredAndOptionalFields() {
+ Assertions.assertEquals(
+ Expression.Operation.FALSE, filter("id INTEGER", "id IS NULL").rowFilter().op());
+ Assertions.assertTrue(filter("id INTEGER", "id IS NOT NULL").isEmpty());
+ Assertions.assertTrue(eval(filter("region STRING", "region IS NULL"), row(2, null)));
+ Assertions.assertFalse(eval(filter("region STRING", "region IS NOT NULL"), row(2, null)));
}
@Test
- void testMaskSkipsUnselectedActionsAndConditions() {
- ColumnMask incompatibleFallback =
- RestrictedRegoExpressionParserFacade.parseColumnMask(
- "mask := action(\"mask-to-fixed-value\") if true " + "else := action(\"show-last-4\")");
- ReadRestrictions selected =
- convertMasks(Collections.singletonMap(1, incompatibleFallback), context("alice"));
- assertEquals("mask-to-fixed-value", selected.columnProjections().get(0).name());
-
- ColumnMask unresolvedUnselectedCondition =
- RestrictedRegoExpressionParserFacade.parseColumnMask(
- "mask := action(\"show-last-4\") if true "
- + "else := action(\"show-first-4\") if is_group_member(\"missing\") "
- + "else := action(\"replace-with-null\")");
- ReadRestrictions firstBranch =
- convertMasks(Collections.singletonMap(2, unresolvedUnselectedCondition), context("alice"));
- assertEquals("show-last-4", firstBranch.columnProjections().get(0).name());
-
- ColumnMask incompatibleUnselectedBranch =
- RestrictedRegoExpressionParserFacade.parseColumnMask(
- "mask := action(\"show-last-4\") if false "
- + "else := action(\"mask-to-fixed-value\") if true "
- + "else := action(\"show-first-4\")");
- ReadRestrictions laterBranch =
- convertMasks(Collections.singletonMap(1, incompatibleUnselectedBranch), context("alice"));
- assertEquals("mask-to-fixed-value", laterBranch.columnProjections().get(0).name());
+ void testDeterministicCanonicalization() {
+ ReadRestrictions a =
+ filter("id INTEGER, region STRING", "id IN (2,1,2) AND region = 'US' AND region = 'US'");
+ ReadRestrictions b = filter("region STRING, id INTEGER", "region = 'US' AND id IN (1,2)");
+ Assertions.assertEquals(ReadRestrictionsParser.toJson(a), ReadRestrictionsParser.toJson(b));
+ Assertions.assertEquals(
+ ReadRestrictionsParser.toJson(filter("region STRING", "NOT region = 'US'")),
+ ReadRestrictionsParser.toJson(filter("region STRING", "region <> 'US'")));
}
@Test
- void testSelectedIncompatibleMaskStillFailsClosed() {
- ColumnMask incompatibleSelectedBranch =
- RestrictedRegoExpressionParserFacade.parseColumnMask(
- "mask := action(\"show-last-4\") if true " + "else := action(\"mask-to-fixed-value\")");
- assertThrows(
+ void testIndependentMaskParameterBindingAndIdentity() {
+ SqlDefinition definition =
+ RestrictedSqlExpressionParserFacade.parseColumnMask(
+ "(xxx STRING) RETURNS STRING -> show_last_4(xxx)");
+ Map<Integer, SqlDefinition> masks = new HashMap<>();
+ masks.put(3, definition);
+ masks.put(2, definition);
+ ReadRestrictions result =
+ IcebergReadRestrictionConverter.convert(Optional.empty(), masks, SCHEMA, context());
+ Assertions.assertEquals(2, result.columnProjections().get(0).fieldId());
+ Assertions.assertEquals(3, result.columnProjections().get(1).fieldId());
+ Assertions.assertTrue(masks(2, mask("STRING", "value")).isEmpty());
+ Assertions.assertThrows(IllegalArgumentException.class, () -> masks(1, definition));
+ Assertions.assertThrows(IllegalArgumentException.class, () -> masks(11, definition));
+ Assertions.assertThrows(
IllegalArgumentException.class,
() ->
- convertMasks(
- Collections.singletonMap(1, incompatibleSelectedBranch), context("alice")));
-
- ColumnMask incompatibleSelectedFallback =
- RestrictedRegoExpressionParserFacade.parseColumnMask(
- "mask := action(\"mask-to-fixed-value\") if false "
- + "else := action(\"show-last-4\")");
- assertThrows(
- IllegalArgumentException.class,
- () ->
- convertMasks(
- Collections.singletonMap(1, incompatibleSelectedFallback), context("alice")));
+ IcebergReadRestrictionConverter.convert(
+ Optional.of(mask("BOOLEAN", "value")), Collections.emptyMap(), SCHEMA, context()));
}
@Test
- void testNullTestsRequireOptionalTopLevelField() {
- ReadRestrictions optional =
- convertFilter("filter := col(\"region\") == null", context("alice"));
- assertEquals(Expression.Operation.IS_NULL, optional.rowFilter().op());
+ void testAllNineMaskFunctionsAndWireRoundTrip() {
+ Map<String, Integer> functions = new LinkedHashMap<>();
+ functions.put("mask_alphanum", 2);
+ functions.put("mask_to_fixed_value", 1);
+ functions.put("replace_with_null", 2);
+ functions.put("show_first_4", 2);
+ functions.put("show_last_4", 2);
+ functions.put("truncate_to_year", 5);
+ functions.put("truncate_to_month", 14);
+ functions.put("sha256_global", 1);
+ functions.put("sha256_query_local", 2);
+ for (Map.Entry<String, Integer> entry : functions.entrySet()) {
+ String type =
+ entry.getValue() == 1
+ ? "INTEGER"
+ : entry.getValue() == 5
+ ? "DATE"
+ : entry.getValue() == 14 ? "TIMESTAMP WITH TIME ZONE" : "STRING";
+ ReadRestrictions result = masks(entry.getValue(), mask(type, entry.getKey() + "(value)"));
+ Assertions.assertEquals(
+ entry.getValue().intValue(), result.columnProjections().get(0).fieldId());
+ String json = ReadRestrictionsParser.toJson(result);
+ Assertions.assertEquals(json, reboundJson(json));
+ }
+ }
- assertThrows(
+ @Test
+ void testMaskCaseSelectionAndNullableResults() {
+ Assertions.assertEquals(
+ "show-last-4",
+ masks(
+ 2,
+ mask(
+ "STRING",
+ "CASE WHEN CURRENT_USER() = 'alice' THEN show_last_4(value) ELSE NULL END"))
+ .columnProjections()
+ .get(0)
+ .name());
+ Assertions.assertEquals(
+ "replace-with-null",
+ masks(2, mask("STRING", "CASE CURRENT_USER() WHEN 'bob' THEN value END"))
+ .columnProjections()
+ .get(0)
+ .name());
+ Assertions.assertEquals(
+ "show-first-4",
+ masks(
+ 2,
+ mask(
+ "STRING",
+ "CASE WHEN NULL THEN show_last_4(value) ELSE show_first_4(value) END"))
+ .columnProjections()
+ .get(0)
+ .name());
+ Assertions.assertThrows(IllegalArgumentException.class, () -> masks(9, mask("STRING", "NULL")));
+ Assertions.assertThrows(
IllegalArgumentException.class,
- () -> convertFilter("filter := col(\"required_text\") == null", context("alice")));
+ () -> masks(9, mask("STRING", "CASE WHEN TRUE THEN value ELSE NULL END")));
+ Assertions.assertEquals(
+ "show-last-4",
+ masks(
+ 2,
+ mask(
+ "STRING",
+ "CASE WHEN TRUE THEN show_last_4(value) WHEN is_group_member('missing') THEN value ELSE NULL END"))
+ .columnProjections()
+ .get(0)
+ .name());
}
@Test
- void testRejectsTimestampWithTimezone() {
- Schema schema =
- new Schema(Types.NestedField.optional(20, "zoned", Types.TimestampType.withZone()));
- RowFilter filter =
- RestrictedRegoExpressionParserFacade.parseRowFilter(
- "filter := col(\"zoned\") == \"2026-10-12T12:34:56Z\"");
-
- assertThrows(
+ void testFixedLiteralsAndUnsupportedScalarMasks() {
+ Assertions.assertEquals(
+ "mask-to-fixed-value",
+ masks(2, mask("STRING", "'XXXXXXXX'")).columnProjections().get(0).name());
+ Assertions.assertEquals(
+ "mask-to-fixed-value", masks(1, mask("INTEGER", "0")).columnProjections().get(0).name());
+ Assertions.assertEquals(
+ "mask-to-fixed-value",
+ masks(4, mask("DECIMAL(7,2)", "0.00")).columnProjections().get(0).name());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> masks(2, mask("STRING", "'REDACTED'")));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> masks(2, mask("STRING", "show_last_4(mask_alphanum(value))")));
+ Assertions.assertThrows(
IllegalArgumentException.class,
() ->
- IcebergReadRestrictionConverter.convert(
- Optional.of(filter), Collections.emptyMap(), schema, context("alice")));
+ masks(
+ 2,
+ mask("STRING", "CASE WHEN value IS NULL THEN NULL ELSE show_last_4(value) END")));
+ }
+
+ @Test
+ void testNonNullableBooleanMaskOperations() {
+ for (String body :
+ Arrays.asList(
+ "value IS NULL",
+ "NULL IS NOT NULL",
+ "NOT TRUE",
+ "NOT (value IS NOT NULL)",
+ "1 = 2",
+ "FALSE AND value",
+ "value IS NULL OR FALSE",
+ "TRUE IN (FALSE)",
+ "2 BETWEEN 3 AND 4",
+ "'abc' LIKE 'z%'",
+ "CASE WHEN TRUE THEN value IS NULL ELSE FALSE END")) {
+ ReadRestrictions result = requiredBooleanMask(body);
+ Assertions.assertEquals(
+ "mask-to-fixed-value", result.columnProjections().get(0).name(), body);
+ Assertions.assertEquals(
+ false, result.columnProjections().get(0).bind(Types.BooleanType.get()).apply(null), body);
+ }
+ }
+
+ @Test
+ void testNullableBooleanMasksStillFailForRequiredColumns() {
+ for (String body :
+ Arrays.asList(
+ "NULL",
+ "NOT NULL",
+ "value = NULL",
+ "value AND NULL",
+ "value OR NULL",
+ "value IN (TRUE, NULL)",
+ "NULL BETWEEN 1 AND 2",
+ "NULL LIKE 'a%'",
+ "CASE WHEN TRUE THEN FALSE ELSE NULL END",
+ "CASE WHEN TRUE THEN value IS NULL END")) {
+ IllegalArgumentException error =
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> requiredBooleanMask(body), body);
+ Assertions.assertTrue(error.getMessage().contains("Nullable SQL mask result"), body);
+ }
+ }
+
+ @Test
+ void testNonNullableBooleanMasksStillRequireSupportedProjection() {
+ for (String body : Arrays.asList("value IS NOT NULL", "NOT value")) {
+ IllegalArgumentException error =
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> requiredBooleanMask(body), body);
+ Assertions.assertTrue(error.getMessage().contains("cannot represent"), error.getMessage());
+ }
+ }
+
+ @Test
+ void testUnsupportedTargetExpressionsFailClosed() {
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> filter("region STRING, owner STRING", "region = owner"));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> filter("event_date DATE", "month(event_date) = 3"));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> filter("event_date DATE", "day(event_date) = 15"));
+ StringBuilder body = new StringBuilder("CASE ");
+ for (int i = 0; i < 130; i++) {
+ body.append("WHEN id = ").append(i).append(" THEN TRUE ");
+ }
+ body.append("END");
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> filter("id INTEGER", body.toString()));
+ Assertions.assertTrue(exception.getMessage().contains("complexity"));
+ }
+
+ @Test
+ void testComparisonCaseExpansionHasBoundedWork() {
+ StringBuilder choice = new StringBuilder("CASE ");
+ for (int i = 0; i < 80; i++) {
+ choice.append("WHEN id = ").append(i).append(" THEN ").append(i).append(' ');
+ }
+ choice.append("END");
+ String body = choice + " = " + choice;
+ // The source fits the SQL node limit; translating both CASE operands would expand its work.
+ SqlDefinition definition = parse("id INTEGER", body);
+ IllegalArgumentException error =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ IcebergReadRestrictionConverter.convert(
+ Optional.of(definition), Collections.emptyMap(), SCHEMA, context()));
+ Assertions.assertTrue(error.getMessage().contains("work limit"));
+ }
+
+ @Test
+ void testWideExpressionsAndThousandElementMembership() {
+ String list =
+ IntStream.range(0, 1000).mapToObj(Integer::toString).collect(Collectors.joining(","));
+ Assertions.assertTrue(eval(filter("id INTEGER", "id IN (" + list + ")"), row(1, 999)));
+ String body = String.join(" OR ", Collections.nCopies(300, "id = 1"));
+ Assertions.assertTrue(eval(filter("id INTEGER", body), row(1, 1)));
+ }
+
+ private static String reboundJson(String json) {
+ ReadRestrictions parsed = ReadRestrictionsParser.fromJson(json, SCHEMA);
+ Expression filter =
+ parsed.rowFilter() == null
+ ? null
+ : Binder.bind(SCHEMA.asStruct(), parsed.rowFilter(), true);
+ return ReadRestrictionsParser.toJson(ReadRestrictions.of(filter, parsed.columnProjections()));
+ }
+
+ private static SqlDefinition parse(String parameters, String body) {
+ return RestrictedSqlExpressionParserFacade.parseRowFilter(
+ "(" + parameters + ") RETURNS BOOLEAN -> " + body);
+ }
+
+ private static SqlDefinition mask(String type, String body) {
+ return RestrictedSqlExpressionParserFacade.parseColumnMask(
+ "(value " + type + ") RETURNS " + type + " -> " + body);
+ }
+
+ private static ReadRestrictions filter(String parameters, String body) {
+ return convert(parameters, body, context());
}
- private static ReadRestrictions convertFilter(String source, BindingContext context) {
- RowFilter filter = RestrictedRegoExpressionParserFacade.parseRowFilter(source);
+ private static ReadRestrictions convert(String parameters, String body, BindingContext context) {
return IcebergReadRestrictionConverter.convert(
- Optional.of(filter), Collections.emptyMap(), SCHEMA, context);
+ Optional.of(parse(parameters, body)), Collections.emptyMap(), SCHEMA, context);
}
- private static ReadRestrictions convertMasks(
- Map<Integer, ColumnMask> masks, BindingContext context) {
- return IcebergReadRestrictionConverter.convert(Optional.empty(), masks, SCHEMA, context);
+ private static ReadRestrictions masks(int field, SqlDefinition mask) {
+ return IcebergReadRestrictionConverter.convert(
+ Optional.empty(), Collections.singletonMap(field, mask), SCHEMA, context());
}
- private static BindingContext context(String sessionUser) {
- return context(sessionUser, Collections.emptyMap());
+ private static ReadRestrictions requiredBooleanMask(String body) {
+ Schema schema = new Schema(Types.NestedField.required(51, "flag", Types.BooleanType.get()));
+ return IcebergReadRestrictionConverter.convert(
+ Optional.empty(), Collections.singletonMap(51, mask("BOOLEAN", body)), schema, context());
}
- private static BindingContext context(String sessionUser, Map<String, Boolean> groupMemberships) {
- Map<String, Boolean> memberships = new HashMap<>(groupMemberships);
+ private static BindingContext context() {
+ return context("alice");
+ }
+
+ private static BindingContext context(String user) {
return new BindingContext() {
@Override
public String sessionUser() {
- return sessionUser;
+ return user;
}
@Override
public Optional<Boolean> groupMembership(String group) {
- return Optional.ofNullable(memberships.get(group));
+ return Optional.empty();
}
};
}
+
+ private static Map<Integer, Object> row(Object... entries) {
+ Map<Integer, Object> values = new HashMap<>();
+ values.put(1, 1);
+ for (int i = 0; i < entries.length; i += 2) {
+ values.put((Integer) entries[i], entries[i + 1]);
+ }
+ return values;
+ }
+
+ private static boolean eval(ReadRestrictions restrictions, Map<Integer, Object> values) {
+ if (restrictions.rowFilter() == null) {
+ return true;
+ }
+ StructLike row =
+ new StructLike() {
+ @Override
+ public int size() {
+ return SCHEMA.columns().size();
+ }
+
+ @Override
+ public <T> T get(int pos, Class<T> type) {
+ return type.cast(values.get(SCHEMA.columns().get(pos).fieldId()));
+ }
+
+ @Override
+ public <T> void set(int pos, T value) {
+ throw new UnsupportedOperationException();
+ }
+ };
+ return ExpressionVisitors.visit(
+ restrictions.rowFilter(),
+ new ExpressionVisitors.ExpressionVisitor<Boolean>() {
+ @Override
+ public Boolean alwaysTrue() {
+ return true;
+ }
+
+ @Override
+ public Boolean alwaysFalse() {
+ return false;
+ }
+
+ @Override
+ public Boolean and(Boolean a, Boolean b) {
+ return a && b;
+ }
+
+ @Override
+ public Boolean or(Boolean a, Boolean b) {
+ return a || b;
+ }
+
+ @Override
+ public Boolean not(Boolean a) {
+ return !a;
+ }
+
+ @Override
+ public <T> Boolean predicate(BoundPredicate<T> predicate) {
+ return predicate.test(row);
+ }
+ });
+ }
}
diff --git a/iceberg/iceberg-rest-server-experiment/src/test/java/org/apache/gravitino/iceberg/service/restriction/TestSqlPredicateResult.java b/iceberg/iceberg-rest-server-experiment/src/test/java/org/apache/gravitino/iceberg/service/restriction/TestSqlPredicateResult.java
new file mode 100644
index 0000000000..3cadc35ff0
--- /dev/null
+++ b/iceberg/iceberg-rest-server-experiment/src/test/java/org/apache/gravitino/iceberg/service/restriction/TestSqlPredicateResult.java
@@ -0,0 +1,127 @@
+/*
+ * 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.iceberg.service.restriction;
+
+import javax.annotation.Nullable;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.expressions.Binder;
+import org.apache.iceberg.expressions.BoundPredicate;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Pins SQL three-valued logic independently of AST conversion and schema binding. */
+class TestSqlPredicateResult {
+ private static final Types.StructType ROW_TYPE =
+ Types.StructType.of(Types.NestedField.optional(1, "flag", Types.BooleanType.get()));
+
+ @Test
+ void testConstantResults() {
+ for (Boolean value : new Boolean[] {true, false, null}) {
+ assertConstant(value, SqlPredicateResult.constant(value));
+ }
+ }
+
+ @Test
+ void testNotPreservesUnknown() {
+ assertConstant(false, SqlPredicateResult.constant(true).not());
+ assertConstant(true, SqlPredicateResult.constant(false).not());
+ assertConstant(null, SqlPredicateResult.constant(null).not());
+ }
+
+ @Test
+ void testAndOrTruthTables() {
+ // Columns: left operand, right operand, expected AND result, expected OR result.
+ Boolean[][] cases = {
+ {true, true, true, true},
+ {true, false, false, true},
+ {true, null, null, true},
+ {false, true, false, true},
+ {false, false, false, false},
+ {false, null, false, null},
+ {null, true, null, true},
+ {null, false, false, null},
+ {null, null, null, null}
+ };
+ for (Boolean[] test : cases) {
+ SqlPredicateResult left = SqlPredicateResult.constant(test[0]);
+ SqlPredicateResult right = SqlPredicateResult.constant(test[1]);
+ assertConstant(test[2], left.and(right));
+ assertConstant(test[3], left.or(right));
+ }
+ }
+
+ @Test
+ void testRowPredicatesDistinguishUnknownFromFalse() {
+ Expression whenTrue = Expressions.equal("flag", true);
+ Expression whenFalse = Expressions.equal("flag", false);
+ SqlPredicateResult result = new SqlPredicateResult(whenTrue, whenFalse);
+ Assertions.assertFalse(result.isConstant());
+ Assertions.assertFalse(
+ new SqlPredicateResult(Expressions.alwaysFalse(), whenFalse).isConstant());
+ Assertions.assertFalse(
+ new SqlPredicateResult(whenTrue, Expressions.alwaysFalse()).isConstant());
+
+ for (Boolean value : new Boolean[] {true, false, null}) {
+ StructLike row = row(value);
+ Assertions.assertEquals(Boolean.TRUE.equals(value), matches(result.trueExpression(), row));
+ Assertions.assertEquals(Boolean.FALSE.equals(value), matches(result.falseExpression(), row));
+ Assertions.assertEquals(
+ Boolean.FALSE.equals(value), matches(result.not().trueExpression(), row));
+ Assertions.assertEquals(
+ Boolean.TRUE.equals(value), matches(result.not().falseExpression(), row));
+ }
+ }
+
+ private static void assertConstant(@Nullable Boolean expected, SqlPredicateResult result) {
+ Assertions.assertTrue(result.isConstant());
+ Assertions.assertEquals(
+ Boolean.TRUE.equals(expected) ? Expression.Operation.TRUE : Expression.Operation.FALSE,
+ result.trueExpression().op());
+ Assertions.assertEquals(
+ Boolean.FALSE.equals(expected) ? Expression.Operation.TRUE : Expression.Operation.FALSE,
+ result.falseExpression().op());
+ }
+
+ private static boolean matches(Expression expression, StructLike row) {
+ BoundPredicate<?> predicate = (BoundPredicate<?>) Binder.bind(ROW_TYPE, expression, true);
+ return predicate.test(row);
+ }
+
+ private static StructLike row(@Nullable Boolean value) {
+ return new StructLike() {
+ @Override
+ public int size() {
+ return 1;
+ }
+
+ @Override
+ public <T> T get(int pos, Class<T> type) {
+ return type.cast(value);
+ }
+
+ @Override
+ public <T> void set(int pos, T value) {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
+}
diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergReadRestrictionIT.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergReadRestrictionIT.java
index e4589dc1c6..9936ebfaf0 100644
--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergReadRestrictionIT.java
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergReadRestrictionIT.java
@@ -87,7 +87,7 @@ public class IcebergReadRestrictionIT extends IcebergAuthorizationIT {
Policy.BuiltInType.ROW_FILTER.policyType(),
null,
true,
- PolicyContents.rowFilter("filter := col(\"col_1\") == 1"));
+ PolicyContents.rowFilter("(col_1 INTEGER) RETURNS BOOLEAN -> col_1 = 1"));
metalakeClientWithAllPrivilege.addPolicyForTag(rowFilterTag, rowFilterPolicy);
String columnMaskTag = "column_mask_tag_" + suffix;
@@ -98,7 +98,7 @@ public class IcebergReadRestrictionIT extends IcebergAuthorizationIT {
Policy.BuiltInType.COLUMN_MASK.policyType(),
null,
true,
- PolicyContents.columnMask("mask := action(\"replace-with-null\")"));
+ PolicyContents.columnMask("(value INTEGER) RETURNS INTEGER -> replace_with_null(value)"));
metalakeClientWithAllPrivilege.addPolicyForTag(columnMaskTag, columnMaskPolicy);
Table gravitinoTable =
diff --git a/spark-connector/v3.5/spark/src/test/java/org/apache/gravitino/spark/connector/TestSqlParserRuntimeIsolation.java b/spark-connector/v3.5/spark/src/test/java/org/apache/gravitino/spark/connector/TestSqlParserRuntimeIsolation.java
new file mode 100644
index 0000000000..db770517f0
--- /dev/null
+++ b/spark-connector/v3.5/spark/src/test/java/org/apache/gravitino/spark/connector/TestSqlParserRuntimeIsolation.java
@@ -0,0 +1,52 @@
+/*
+ * 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.spark.connector;
+
+import org.antlr.v4.runtime.CharStreams;
+import org.antlr.v4.runtime.CommonTokenStream;
+import org.apache.gravitino.policy.sql.RestrictedSqlExpressionParserFacade;
+import org.apache.spark.sql.catalyst.parser.SqlBaseLexer;
+import org.apache.spark.sql.catalyst.parser.SqlBaseParser;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Verifies Gravitino's shaded SQL parser and Spark's ANTLR parser can run in the same JVM. */
+class TestSqlParserRuntimeIsolation {
+ @Test
+ void testSparkAndPolicyParsersCoexist() {
+ // Initialize Spark's ANTLR runtime before loading Gravitino's generated parser.
+ assertSparkSqlParses();
+ Assertions.assertDoesNotThrow(
+ () ->
+ RestrictedSqlExpressionParserFacade.validateRowFilter(
+ "(region STRING) RETURNS BOOLEAN -> region = 'US'"));
+ Assertions.assertDoesNotThrow(
+ () ->
+ RestrictedSqlExpressionParserFacade.validateColumnMask(
+ "(value STRING) RETURNS STRING -> show_last_4(value)"));
+ assertSparkSqlParses();
+ }
+
+ private static void assertSparkSqlParses() {
+ SqlBaseLexer lexer = new SqlBaseLexer(CharStreams.fromString("SELECT 1"));
+ SqlBaseParser parser = new SqlBaseParser(new CommonTokenStream(lexer));
+ Assertions.assertNotNull(parser.singleStatement());
+ Assertions.assertEquals(0, parser.getNumberOfSyntaxErrors());
+ }
+}