Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -2481,6 +2481,15 @@ public String toString() {
"Enable query auth to give Catalog the opportunity to perform "
+ "column level and row level permission validation on queries.");

@ExcludeFromDocumentation("Internal use only")
public static final ConfigOption<String> COMMIT_REWRITE_OPERATION =
key("commit.rewrite-operation")
.stringType()
.noDefaultValue()
.withDescription(
"The rewrite that writes the table. Its commits fail when query auth "
+ "returns row filters or column masks.");

@ExcludeFromDocumentation("Only used internally to support materialized table")
public static final ConfigOption<String> MATERIALIZED_TABLE_DEFINITION_QUERY =
key("materialized-table.definition-query")
Expand Down Expand Up @@ -3862,6 +3871,11 @@ public boolean queryAuthEnabled() {
return options.get(QUERY_AUTH_ENABLED);
}

@Nullable
public String commitRewriteOperation() {
return options.get(COMMIT_REWRITE_OPERATION);
}

public boolean ignoreDelete() {
return options.get(IGNORE_DELETE);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

package org.apache.paimon.catalog;

import org.apache.paimon.CoreOptions;
import org.apache.paimon.data.GenericRow;
import org.apache.paimon.data.InternalRow;
import org.apache.paimon.predicate.And;
Expand All @@ -28,6 +29,8 @@
import org.apache.paimon.predicate.PredicateVisitor;
import org.apache.paimon.predicate.Transform;
import org.apache.paimon.reader.RecordReader;
import org.apache.paimon.table.CatalogEnvironment;
import org.apache.paimon.table.FallbackReadFileStoreTable;
import org.apache.paimon.table.FileStoreTable;
import org.apache.paimon.table.SpecialFields;
import org.apache.paimon.table.Table;
Expand All @@ -36,6 +39,7 @@
import org.apache.paimon.table.source.SnapshotNotExistPlan;
import org.apache.paimon.table.source.Split;
import org.apache.paimon.table.source.TableScan;
import org.apache.paimon.table.system.RowTrackingTable;
import org.apache.paimon.types.DataField;
import org.apache.paimon.types.DataType;
import org.apache.paimon.types.RowType;
Expand Down Expand Up @@ -143,6 +147,68 @@ public static void rejectSearchUnderQueryAuth(@Nullable Table table) {
}
}

/**
* Rejects the rewrite now, and returns a copy of {@code table} to write it with, whose commits
* reject it again. A rule added before the rewrite reads the table is then seen when it
* commits, wherever the read is planned.
*/
public static FileStoreTable rejectRewriteUnderQueryAuthOnCommit(
FileStoreTable table, String operation) {
rejectRewriteUnderQueryAuth(table, operation);
return table.copy(
Collections.singletonMap(CoreOptions.COMMIT_REWRITE_OPERATION.key(), operation));
}

/** See {@link #rejectRewriteUnderQueryAuthOnCommit(FileStoreTable, String)}. */
public static Table rejectRewriteUnderQueryAuthOnCommit(Table table, String operation) {
if (table instanceof FileStoreTable) {
return rejectRewriteUnderQueryAuthOnCommit((FileStoreTable) table, operation);
}
rejectRewriteUnderQueryAuth(table, operation);
return table;
}

public static void rejectRewriteUnderQueryAuth(@Nullable Table table, String operation) {
if (table instanceof RowTrackingTable) {
// Data Evolution rewrites read the table through its row tracking table.
rejectRewriteUnderQueryAuth(((RowTrackingTable) table).wrapped(), operation);
return;
}
if (table instanceof FileStoreTable) {
FileStoreTable fileStoreTable = (FileStoreTable) table;
CoreOptions options = fileStoreTable.coreOptions();
if (options.queryAuthEnabled()) {
CatalogEnvironment environment = fileStoreTable.catalogEnvironment();
rejectRewriteUnderQueryAuthRules(
environment.tableQueryAuth(options).auth(null), operation);
// A chain table reads its branches with the main table's identifier.
Identifier identifier = environment.identifier();
if (identifier != null
&& !identifier.getBranchNameOrDefault().equals(options.branch())) {
Identifier branch =
new Identifier(
identifier.getDatabaseName(),
identifier.getTableName(),
options.branch());
rejectRewriteUnderQueryAuthRules(
environment.copy(branch).tableQueryAuth(options).auth(null), operation);
}
}
if (fileStoreTable instanceof FallbackReadFileStoreTable) {
rejectRewriteUnderQueryAuth(
((FallbackReadFileStoreTable) fileStoreTable).other(), operation);
}
}
}

private static void rejectRewriteUnderQueryAuthRules(
@Nullable TableQueryAuthResult authResult, String operation) {
if (authResult != null && authResult.hasRules()) {
throw new UnsupportedOperationException(
operation + " requires full-table access without row filters or column masks.");
}
}

/**
* Drops the conjuncts of {@code predicate} referencing any of {@code fields}; returns null when
* nothing remains. Used to keep raw-statistics pushdown off masked columns.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@

import static org.apache.paimon.CoreOptions.PATH;
import static org.apache.paimon.CoreOptions.QUERY_AUTH_ENABLED;
import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth;

/** Abstract {@link FileStoreTable}. */
abstract class AbstractFileStoreTable implements FileStoreTable {
Expand Down Expand Up @@ -627,17 +628,25 @@ public ExpireSnapshots newExpireChangelog() {
@Override
public TableCommitImpl newCommit(String commitUser) {
CoreOptions options = coreOptions();
return new TableCommitImpl(
store().newCommit(commitUser, this),
newExpireRunnable(),
options.writeOnly() ? null : store().newPartitionExpire(commitUser, this),
options.writeOnly() ? null : store().newTagAutoManager(this),
options.writeOnly() ? null : CoreOptions.fromMap(options()).consumerExpireTime(),
new ConsumerManager(fileIO, path, snapshotManager().branch()),
options.snapshotExpireExecutionMode(),
name(),
options.forceCreatingSnapshot(),
options.fileOperationThreadNum());
TableCommitImpl commit =
new TableCommitImpl(
store().newCommit(commitUser, this),
newExpireRunnable(),
options.writeOnly() ? null : store().newPartitionExpire(commitUser, this),
options.writeOnly() ? null : store().newTagAutoManager(this),
options.writeOnly()
? null
: CoreOptions.fromMap(options()).consumerExpireTime(),
new ConsumerManager(fileIO, path, snapshotManager().branch()),
options.snapshotExpireExecutionMode(),
name(),
options.forceCreatingSnapshot(),
options.fileOperationThreadNum());
String rewriteOperation = options.commitRewriteOperation();
if (rewriteOperation != null) {
commit.withCommitCheck(() -> rejectRewriteUnderQueryAuth(this, rewriteOperation));
}
return commit;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@
import java.util.Objects;
import java.util.Optional;

import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth;

/** Delegated {@link FileStoreTable}. */
public abstract class DelegatedFileStoreTable implements FileStoreTable {

Expand Down Expand Up @@ -364,7 +366,13 @@ public TableWriteImpl<?> newPostponeFixedBucketWrite(

@Override
public TableCommitImpl newCommit(String commitUser) {
return wrapped.newCommit(commitUser);
TableCommitImpl commit = wrapped.newCommit(commitUser);
String rewriteOperation = coreOptions().commitRewriteOperation();
if (rewriteOperation != null) {
// also covers what this table reads besides the wrapped one, such as a fallback branch
commit.withCommitCheck(() -> rejectRewriteUnderQueryAuth(this, rewriteOperation));
}
return commit;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ public class TableCommitImpl implements InnerTableCommit {
private static final Logger LOG = LoggerFactory.getLogger(TableCommitImpl.class);

private final FileStoreCommit commit;
@Nullable private Runnable commitCheck;
@Nullable private final Runnable expireSnapshots;
@Nullable private final PartitionExpire partitionExpire;
@Nullable private final TagAutoManager tagAutoManager;
Expand Down Expand Up @@ -219,22 +220,37 @@ public void commit(List<CommitMessage> commitMessages) {
commit(COMMIT_IDENTIFIER, commitMessages);
}

/** Runs {@code check} before each commit; a failing check aborts the commit. */
public TableCommitImpl withCommitCheck(@Nullable Runnable check) {
this.commitCheck = check;
return this;
}

private void checkBeforeCommit() {
if (commitCheck != null) {
commitCheck.run();
}
}

@Override
public void truncateTable() {
checkCommitted();
checkBeforeCommit();
commit.withOperation(Snapshot.Operation.TRUNCATE);
commit.truncateTable(COMMIT_IDENTIFIER);
}

@Override
public void truncatePartitions(List<Map<String, String>> partitionSpecs) {
checkBeforeCommit();
commit.withOperation(Snapshot.Operation.TRUNCATE);
commit.dropPartitions(partitionSpecs, COMMIT_IDENTIFIER);
}

@Override
public void truncatePartitions(PartitionPredicate partitionFilter) {
checkNotNull(partitionFilter, "Partition filter cannot be null.");
checkBeforeCommit();
commit.withOperation(Snapshot.Operation.TRUNCATE);
commit.dropPartitions(partitionFilter, COMMIT_IDENTIFIER);
}
Expand Down Expand Up @@ -296,6 +312,7 @@ public void commit(ManifestCommittable committable) {
}

public void commitMultiple(List<ManifestCommittable> committables, boolean checkAppendFiles) {
checkBeforeCommit();
if (overwritePartitionSpec == null && overwriteStaticPartitions == null) {
int newSnapshots = 0;
for (ManifestCommittable committable : committables) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ public RowTrackingTable(FileStoreTable wrapped) {
}
}

public FileStoreTable wrapped() {
return wrapped;
}

@Override
public Optional<Snapshot> latestSnapshot() {
return wrapped.latestSnapshot();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

package org.apache.paimon.catalog;

import org.apache.paimon.CoreOptions;
import org.apache.paimon.data.BinaryString;
import org.apache.paimon.predicate.ConcatWsTransform;
import org.apache.paimon.predicate.Equal;
Expand All @@ -29,6 +30,11 @@
import org.apache.paimon.predicate.Predicate;
import org.apache.paimon.predicate.PredicateBuilder;
import org.apache.paimon.predicate.UpperTransform;
import org.apache.paimon.table.CatalogEnvironment;
import org.apache.paimon.table.FallbackReadFileStoreTable;
import org.apache.paimon.table.FileStoreTable;
import org.apache.paimon.table.Table;
import org.apache.paimon.table.source.TableQueryAuth;
import org.apache.paimon.types.DataTypes;
import org.apache.paimon.types.RowType;
import org.apache.paimon.utils.JsonSerdeUtil;
Expand All @@ -42,10 +48,37 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/** Tests that malformed query-authorization definitions cannot be silently ignored. */
public class TableQueryAuthResultTest {

@Test
void testRewriteChecksFallbackRules() {
FileStoreTable wrapped = mock(FileStoreTable.class);
FileStoreTable fallback = mock(FileStoreTable.class);
CoreOptions unrestricted = CoreOptions.fromMap(Collections.emptyMap());
CoreOptions restricted =
CoreOptions.fromMap(
Collections.singletonMap(CoreOptions.QUERY_AUTH_ENABLED.key(), "true"));
when(wrapped.coreOptions()).thenReturn(unrestricted);
when(fallback.coreOptions()).thenReturn(restricted);
CatalogEnvironment environment = mock(CatalogEnvironment.class);
when(fallback.catalogEnvironment()).thenReturn(environment);
TableQueryAuth queryAuth =
select -> new TableQueryAuthResult(Collections.singletonList(filterJson()), null);
when(environment.tableQueryAuth(restricted)).thenReturn(queryAuth);

Table fallbackTable = new FallbackReadFileStoreTable(wrapped, fallback, true);
assertThatThrownBy(
() ->
TableQueryAuthResult.rejectRewriteUnderQueryAuth(
fallbackTable, "UPDATE"))
.isInstanceOf(UnsupportedOperationException.class)
.hasMessageContaining("UPDATE requires full-table access");
}

@Test
void testInvalidRowFilterFailsClosed() {
assertThatThrownBy(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
import org.apache.paimon.catalog.ModelField;
import org.apache.paimon.catalog.ProviderModelDefinition;
import org.apache.paimon.catalog.TableQueryAuthResult;
import org.apache.paimon.data.BinaryString;
import org.apache.paimon.data.GenericRow;
import org.apache.paimon.fs.Path;
import org.apache.paimon.fs.local.LocalFileIO;
import org.apache.paimon.management.ListPermissionsRequest;
Expand Down Expand Up @@ -70,6 +72,9 @@
import org.apache.paimon.table.FormatTable;
import org.apache.paimon.table.format.FormatTablePartitionManager;
import org.apache.paimon.table.sink.BatchTableCommit;
import org.apache.paimon.table.sink.BatchTableWrite;
import org.apache.paimon.table.sink.BatchWriteBuilder;
import org.apache.paimon.table.sink.CommitMessage;
import org.apache.paimon.types.DataField;
import org.apache.paimon.types.DataTypes;
import org.apache.paimon.types.RowType;
Expand Down Expand Up @@ -1846,6 +1851,56 @@ void testAuthTableQueryResponseWithColumnMasking() throws Exception {
catalog.dropDatabase(identifier.getDatabaseName(), true, true);
}

@Test
void testRewriteCommitAuthorizesAgain() throws Exception {
Identifier identifier = Identifier.create("test_db", "rewrite_table");
catalog.createDatabase(identifier.getDatabaseName(), true);
catalog.createTable(
identifier,
Schema.newBuilder()
.column("col1", DataTypes.INT())
.column("col2", DataTypes.STRING())
.option(CoreOptions.QUERY_AUTH_ENABLED.key(), "true")
.build(),
false);
FileStoreTable table = (FileStoreTable) catalog.getTable(identifier);
BatchWriteBuilder rewrite =
TableQueryAuthResult.rejectRewriteUnderQueryAuthOnCommit(table, "UPDATE")
.newBatchWriteBuilder();
List<CommitMessage> messages;
try (BatchTableWrite write = rewrite.newWrite()) {
write.write(GenericRow.of(1, BinaryString.fromString("a")));
messages = write.prepareCommit();
}

// A rule added after the rewrite started fails its commits.
restCatalogServer.setColumnMaskingAuth(
identifier,
Collections.singletonMap(
"col2",
new UpperTransform(
Collections.singletonList(
new FieldRef(1, "col2", DataTypes.STRING())))));
try (BatchTableCommit commit = rewrite.newCommit()) {
assertThatThrownBy(() -> commit.commit(messages))
.hasMessageContaining("UPDATE requires full-table access");
}
try (BatchTableCommit commit = rewrite.newCommit()) {
assertThatThrownBy(commit::truncateTable)
.hasMessageContaining("UPDATE requires full-table access");
}
assertThat(table.latestSnapshot()).isEmpty();

restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap());
try (BatchTableCommit commit = rewrite.newCommit()) {
commit.commit(messages);
}
assertThat(table.latestSnapshot()).isPresent();

catalog.dropTable(identifier, true);
catalog.dropDatabase(identifier.getDatabaseName(), true, true);
}

private void checkHeader(String headerName, String headerValue) {
// Verify that the header were included in the requests
List<Map<String, String>> receivedHeaders = restCatalogServer.getReceivedHeaders();
Expand Down
Loading
Loading