From 6c0563c2f07b87e48a27b0f697c469d5cd5e8b45 Mon Sep 17 00:00:00 2001 From: Li Jiajia Date: Fri, 30 Oct 2026 19:53:48 -0700 Subject: [PATCH 01/10] [spark][flink] Reject row-level operations and rewrites under query auth rules On a table with query auth, operations that read rows and write data back did not respect the caller's row filter and column masks: - Spark UPDATE, DELETE and MERGE INTO on append and Data Evolution tables read the raw files, so UPDATE t SET note = ssn copied a masked column into a visible one, and rows hidden by the row filter were updated or deleted. - On primary-key tables, Spark and Flink UPDATE and MERGE INTO, and the Flink delete and merge-into actions, read the filtered, masked rows and wrote them back, so masked values were stored as real data and masked keys could delete rows hidden by the row filter. - Spark TRUNCATE TABLE, with or without a PARTITION clause, and Flink truncation removed the rows hidden by the row filter too. - Flink sort compaction and rescale, and Flink and Spark chain table compaction, overwrote partitions with the caller's filtered, masked rows, losing the hidden rows and storing the masks. These operations now fail when query auth gives the caller a row filter or a column mask, through a shared check next to the search rejection, TableQueryAuthResult.rejectRewriteUnderQueryAuth. Users with full access are not affected. The check also covers the fallback branch of a table with scan.fallback-branch. The Flink rewrite actions authorize again when their source plans the scan at job start or restores it from a checkpoint, including the postpone merge-on-read source, so rules added after the action was built are not missed, even when they leave no split to read. Rewrites that read the raw files, such as the Spark sort compaction, clustering and rescale procedures, are unchanged. --- .../paimon/catalog/TableQueryAuthResult.java | 34 ++ .../catalog/TableQueryAuthResultTest.java | 33 ++ .../flink/action/CompactChainTableAction.java | 3 + .../action/DataEvolutionMergeIntoAction.java | 2 + .../paimon/flink/action/DeleteAction.java | 2 + .../paimon/flink/action/MergeIntoAction.java | 2 + .../paimon/flink/action/RescaleAction.java | 4 + .../flink/action/SortCompactAction.java | 4 + .../paimon/flink/sink/FlinkTableSink.java | 3 + ...pportsRowLevelOperationFlinkTableSink.java | 4 + .../flink/source/FlinkSourceBuilder.java | 37 ++- .../source/PostponeMergeInputSource.java | 15 +- .../flink/source/PostponeMergeOnRead.java | 11 +- .../flink/source/StaticFileStoreSource.java | 26 +- .../flink/source/operator/MonitorSource.java | 45 +++ .../paimon/flink/RESTCatalogITCase.java | 307 ++++++++++++++++++ .../MergeIntoPaimonDataEvolutionTable.scala | 2 + .../spark/commands/MergeIntoPaimonTable.scala | 2 + .../procedure/CompactChainTableProcedure.java | 2 + .../spark/PaimonPartitionManagement.scala | 2 + .../paimon/spark/PaimonSparkTableBase.scala | 2 + .../org/apache/paimon/spark/SparkTable.scala | 2 + .../DeleteFromPaimonTableCommand.scala | 2 + .../MergeIntoPaimonDataEvolutionTable.scala | 2 + .../spark/commands/MergeIntoPaimonTable.scala | 2 + ...pdatePaimonDataEvolutionTableCommand.scala | 2 + .../commands/UpdatePaimonTableCommand.scala | 2 + .../TruncatePaimonTableWithFilterExec.scala | 2 + .../spark/SparkCatalogWithRestTest.java | 146 +++++++++ 29 files changed, 686 insertions(+), 16 deletions(-) diff --git a/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java b/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java index 1a064fb7f2f7..47f30d0a4c16 100644 --- a/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java +++ b/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java @@ -28,6 +28,7 @@ import org.apache.paimon.predicate.PredicateVisitor; import org.apache.paimon.predicate.Transform; import org.apache.paimon.reader.RecordReader; +import org.apache.paimon.table.FallbackReadFileStoreTable; import org.apache.paimon.table.FileStoreTable; import org.apache.paimon.table.SpecialFields; import org.apache.paimon.table.Table; @@ -35,6 +36,7 @@ import org.apache.paimon.table.source.QueryAuthSplit; import org.apache.paimon.table.source.SnapshotNotExistPlan; import org.apache.paimon.table.source.Split; +import org.apache.paimon.table.source.Splits; import org.apache.paimon.table.source.TableScan; import org.apache.paimon.types.DataField; import org.apache.paimon.types.DataType; @@ -143,6 +145,38 @@ public static void rejectSearchUnderQueryAuth(@Nullable Table table) { } } + public static void rejectRewriteUnderQueryAuth(@Nullable Table table, String operation) { + if (table instanceof FileStoreTable) { + FileStoreTable fileStoreTable = (FileStoreTable) table; + if (fileStoreTable.coreOptions().queryAuthEnabled()) { + TableQueryAuthResult authResult = + fileStoreTable + .catalogEnvironment() + .tableQueryAuth(fileStoreTable.coreOptions()) + .auth(null); + rejectRewriteUnderQueryAuthRules(authResult, operation); + } + if (fileStoreTable instanceof FallbackReadFileStoreTable) { + rejectRewriteUnderQueryAuth( + ((FallbackReadFileStoreTable) fileStoreTable).other(), operation); + } + } + } + + public static void rejectRewriteUnderQueryAuthRules(List splits, String operation) { + for (Split split : splits) { + rejectRewriteUnderQueryAuthRules(Splits.authResult(split), 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. diff --git a/paimon-core/src/test/java/org/apache/paimon/catalog/TableQueryAuthResultTest.java b/paimon-core/src/test/java/org/apache/paimon/catalog/TableQueryAuthResultTest.java index 241c4377ccec..7925a74dbe0f 100644 --- a/paimon-core/src/test/java/org/apache/paimon/catalog/TableQueryAuthResultTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/catalog/TableQueryAuthResultTest.java @@ -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; @@ -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; @@ -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( diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/CompactChainTableAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/CompactChainTableAction.java index 5dd78e9dabf1..4e084d33d9cc 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/CompactChainTableAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/CompactChainTableAction.java @@ -43,6 +43,7 @@ import java.util.Collections; import java.util.Map; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; import static org.apache.paimon.flink.FlinkConnectorOptions.SCAN_DEDICATED_SPLIT_GENERATION; import static org.apache.paimon.utils.Preconditions.checkArgument; @@ -107,6 +108,7 @@ public void build() throws Exception { ChainGroupReadTable chainTable = (ChainGroupReadTable) ((FallbackReadFileStoreTable) table).other(); + rejectRewriteUnderQueryAuth(chainTable, "Chain table compaction"); FileStoreTable snapshotTable = chainTable.wrapped(); RowType partitionType = snapshotTable.schema().logicalPartitionType(); @@ -133,6 +135,7 @@ public void build() throws Exception { } DataStream source = new FlinkSourceBuilder(chainTable) + .withRewriteOperation("Chain table compaction") .env(env) .sourceBounded(true) .partitionPredicate(predicate) diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java index 46b2b5dff3ee..1c6eb9242eca 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java @@ -87,6 +87,7 @@ import java.util.function.Function; import java.util.stream.Collectors; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; import static org.apache.paimon.format.blob.BlobFileFormat.isBlobFile; import static org.apache.paimon.utils.ParameterUtils.parseCommaSeparatedKeyValues; @@ -256,6 +257,7 @@ public TableResult runInternal() { } public Tuple2, RowType> buildSource() { + rejectRewriteUnderQueryAuth(table, "MERGE INTO"); if (targetTableName().equals(sourceTableName())) { throw new RuntimeException( String.format( diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java index 41e3e49ae669..895ff53eb4d1 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java @@ -39,6 +39,7 @@ import java.util.stream.Collectors; import static org.apache.paimon.CoreOptions.MergeEngine.DEDUPLICATE; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; /** Delete from table action for Flink, dispatching by table type. */ public class DeleteAction extends TableActionBase { @@ -86,6 +87,7 @@ public DeleteAction withSinkParallelism(int sinkParallelism) { @Override public void run() throws Exception { + rejectRewriteUnderQueryAuth(table, "DELETE"); handleSqls(); if (dataEvolutionDelete != null) { dataEvolutionDelete.runInternal().await(); diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java index 7254999797c3..4fa7d61a0e8c 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java @@ -48,6 +48,7 @@ import static org.apache.paimon.CoreOptions.MergeEngine.DEDUPLICATE; import static org.apache.paimon.CoreOptions.MergeEngine.PARTIAL_UPDATE; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; import static org.apache.paimon.utils.ParameterUtils.parseCommaSeparatedKeyValues; /** @@ -253,6 +254,7 @@ public void run() throws Exception { } public DataStream buildDataStream() { + rejectRewriteUnderQueryAuth(table, "MERGE INTO"); // handle aliases handleTargetAlias(); diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java index ed60db636f8e..6509e56d1b54 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java @@ -41,6 +41,8 @@ import java.util.Map; import java.util.Optional; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; + /** Action to rescale one partition of a table. */ public class RescaleAction extends TableActionBase { @@ -75,6 +77,7 @@ public RescaleAction withSinkParallelism(int sinkParallelism) { @Override public void build() throws Exception { + rejectRewriteUnderQueryAuth(table, "Rescale"); Configuration flinkConf = new Configuration(); flinkConf.set(ExecutionOptions.RUNTIME_MODE, RuntimeExecutionMode.BATCH); env.configure(flinkConf); @@ -102,6 +105,7 @@ public void build() throws Exception { DataStream source = new FlinkSourceBuilder(fileStoreTable) + .withRewriteOperation("Rescale") .env(env) .sourceBounded(true) .sourceParallelism( diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java index b491398b7063..457f4e10ca18 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java @@ -42,6 +42,8 @@ import java.util.Map; import java.util.stream.Collectors; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; + /** Compact with sort action. */ public class SortCompactAction extends CompactAction { @@ -67,6 +69,7 @@ public void run() throws Exception { @Override public void build() throws Exception { + rejectRewriteUnderQueryAuth(table, "Sort compaction"); if (bucketsSpecified()) { throw new IllegalArgumentException( "Specifying buckets is not supported for sort compact."); @@ -91,6 +94,7 @@ public void build() throws Exception { Map tableConfig = fileStoreTable.options(); FlinkSourceBuilder sourceBuilder = new FlinkSourceBuilder(fileStoreTable) + .withRewriteOperation("Sort compaction") .sourceName( ObjectIdentifier.of( catalogName, diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkTableSink.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkTableSink.java index 2a50f558fcf2..350b60c763de 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkTableSink.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkTableSink.java @@ -25,6 +25,8 @@ import org.apache.flink.table.connector.sink.abilities.SupportsTruncate; import org.apache.flink.table.factories.DynamicTableFactory; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; + /** Table sink to create sink. */ public class FlinkTableSink extends SupportsRowLevelOperationFlinkTableSink implements SupportsTruncate { @@ -36,6 +38,7 @@ public FlinkTableSink( @Override public void executeTruncation() { + rejectRewriteUnderQueryAuth(table, "TRUNCATE"); try (BatchTableCommit batchTableCommit = table.newBatchWriteBuilder().newCommit()) { batchTableCommit.truncateTable(); } catch (Exception e) { diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/SupportsRowLevelOperationFlinkTableSink.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/SupportsRowLevelOperationFlinkTableSink.java index 1db6769e91f0..142bb160dde6 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/SupportsRowLevelOperationFlinkTableSink.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/SupportsRowLevelOperationFlinkTableSink.java @@ -66,6 +66,7 @@ import static org.apache.paimon.CoreOptions.MERGE_ENGINE; import static org.apache.paimon.CoreOptions.MergeEngine.DEDUPLICATE; import static org.apache.paimon.CoreOptions.MergeEngine.PARTIAL_UPDATE; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; import static org.apache.paimon.table.PrimaryKeyTableUtils.validatePKUpsertDeletable; import static org.apache.paimon.utils.Preconditions.checkArgument; @@ -95,6 +96,7 @@ public DynamicTableSink copy() { @Override public RowLevelUpdateInfo applyRowLevelUpdate( List updatedColumns, @Nullable RowLevelModificationScanContext context) { + rejectRewriteUnderQueryAuth(table, "UPDATE"); rowLevelUpdate = true; // Since only UPDATE_AFTER type messages can be received at present, // AppendOnlyFileStoreTable cannot correctly handle old data, so they are marked as @@ -142,6 +144,7 @@ public RowLevelUpdateInfo applyRowLevelUpdate( @Override public RowLevelDeleteInfo applyRowLevelDelete( @Nullable RowLevelModificationScanContext rowLevelModificationScanContext) { + rejectRewriteUnderQueryAuth(table, "DELETE"); if (isDataEvolutionTable()) { FileStoreTable fileStoreTable = (FileStoreTable) table; DataEvolutionDeleteSink.validateTable(fileStoreTable); @@ -176,6 +179,7 @@ public Optional> requiredColumns() { @Override public boolean applyDeleteFilters(List list) { + rejectRewriteUnderQueryAuth(table, "DELETE"); if (!isDataEvolutionTable()) { validatePKUpsertDeletable(table); } diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/FlinkSourceBuilder.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/FlinkSourceBuilder.java index 4857d40c13a0..232550d0c07b 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/FlinkSourceBuilder.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/FlinkSourceBuilder.java @@ -67,6 +67,7 @@ import java.util.Optional; import static org.apache.flink.table.types.utils.TypeConversions.fromLogicalToDataType; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; import static org.apache.paimon.flink.FlinkConnectorOptions.SOURCE_OPERATOR_UID_SUFFIX; import static org.apache.paimon.flink.FlinkConnectorOptions.generateCustomUid; import static org.apache.paimon.flink.LogicalTypeConversion.toLogicalType; @@ -98,6 +99,7 @@ public class FlinkSourceBuilder { @Nullable private WatermarkStrategy watermarkStrategy; @Nullable private DynamicPartitionFilteringInfo dynamicPartitionFilteringInfo; private boolean skipPreloadTargetSnapshot; + @Nullable private String rewriteOperation; public FlinkSourceBuilder(Table table) { this.table = table; @@ -200,6 +202,11 @@ public FlinkSourceBuilder withSkipPreloadTargetSnapshot(boolean skip) { return this; } + public FlinkSourceBuilder withRewriteOperation(String operation) { + this.rewriteOperation = operation; + return this; + } + private ReadBuilder createReadBuilder(@Nullable org.apache.paimon.types.RowType readType) { ReadBuilder readBuilder = table.newReadBuilder(); if (readType != null) { @@ -238,16 +245,17 @@ private ReadBuilder createReadBuilder(@Nullable org.apache.paimon.types.RowType } Options options = Options.fromMap(table.options()); return new StaticFileStoreSource( - createReadBuilder(projectedRowType()), - limit, - options.get(FlinkConnectorOptions.SCAN_SPLIT_ENUMERATOR_BATCH_SIZE), - options.get(FlinkConnectorOptions.SCAN_SPLIT_ENUMERATOR_ASSIGN_MODE), - dynamicPartitionFilteringInfo, - outerProject(), - SplitWeightUtils.splitWeightFunc(options), - null, - options.get(CoreOptions.BLOB_AS_DESCRIPTOR), - skipPreloadTargetSnapshot); + createReadBuilder(projectedRowType()), + limit, + options.get(FlinkConnectorOptions.SCAN_SPLIT_ENUMERATOR_BATCH_SIZE), + options.get(FlinkConnectorOptions.SCAN_SPLIT_ENUMERATOR_ASSIGN_MODE), + dynamicPartitionFilteringInfo, + outerProject(), + SplitWeightUtils.splitWeightFunc(options), + null, + options.get(CoreOptions.BLOB_AS_DESCRIPTOR), + skipPreloadTargetSnapshot) + .withRewriteOperation(rewriteOperation, table); } TableScanUtils.streamingReadingValidate(table); @@ -283,6 +291,9 @@ private void checkConsumerId() { private @Nullable DataStream buildPostponeMergeSource() { FileStoreTable fileStoreTable = (FileStoreTable) table; + if (rewriteOperation != null) { + rejectRewriteUnderQueryAuth(table, rewriteOperation); + } if (fileStoreTable.coreOptions().startupMode() == CoreOptions.StartupMode.COMPACTED_FULL) { return null; } @@ -316,7 +327,8 @@ private void checkConsumerId() { produceTypeInfo(), outerProject(), limit, - conf.get(CoreOptions.BLOB_AS_DESCRIPTOR)); + conf.get(CoreOptions.BLOB_AS_DESCRIPTOR), + rewriteOperation); } private int basePostponeMergeParallelism() { @@ -580,7 +592,8 @@ private DataStream buildDedicatedSplitGenSource(boolean isBounded) { limit, table, readBuilder.readType(), - conf.get(CoreOptions.BLOB_AS_DESCRIPTOR)); + conf.get(CoreOptions.BLOB_AS_DESCRIPTOR), + rewriteOperation); if (parallelism != null) { dataStream.getTransformation().setParallelism(parallelism); } diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeInputSource.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeInputSource.java index 092af1677827..70fa63fa52dd 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeInputSource.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeInputSource.java @@ -20,6 +20,7 @@ import org.apache.paimon.data.BinaryRow; import org.apache.paimon.io.DataFileMeta; +import org.apache.paimon.table.Table; import org.apache.paimon.table.source.DataSplit; import org.apache.paimon.table.source.DeletionFile; import org.apache.paimon.table.source.PostponeMergePlan; @@ -32,20 +33,29 @@ import org.apache.flink.api.connector.source.SourceReaderContext; import org.apache.flink.core.io.InputStatus; +import javax.annotation.Nullable; + import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; + /** Emits real-bucket markers and writer-grouped postpone splits for merge-on-read. */ final class PostponeMergeInputSource extends AbstractNonCoordinatedSource { private static final long serialVersionUID = 1L; private final List inputs; + private final Table table; + @Nullable private final String rewriteOperation; - PostponeMergeInputSource(PostponeMergePlan plan) { + PostponeMergeInputSource( + PostponeMergePlan plan, Table table, @Nullable String rewriteOperation) { + this.table = table; + this.rewriteOperation = rewriteOperation; this.inputs = new ArrayList<>(); Map, List> realBuckets = new LinkedHashMap<>(); @@ -69,6 +79,9 @@ public Boundedness getBoundedness() { @Override public SourceReader createReader(SourceReaderContext readerContext) { + if (rewriteOperation != null) { + rejectRewriteUnderQueryAuth(table, rewriteOperation); + } return new Reader(); } diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeOnRead.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeOnRead.java index b0054e066db5..f3545495c3c9 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeOnRead.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeOnRead.java @@ -45,6 +45,8 @@ import javax.annotation.Nullable; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; + /** Builds the Flink batch topology for postpone merge-on-read. */ final class PostponeMergeOnRead { @@ -99,8 +101,13 @@ static DataStream build( TypeInformation outputType, @Nullable NestedProjectedRowData outerProject, @Nullable Long limit, - boolean blobAsDescriptor) { - PostponeMergeInputSource inputSource = new PostponeMergeInputSource(plan); + boolean blobAsDescriptor, + @Nullable String rewriteOperation) { + if (rewriteOperation != null) { + rejectRewriteUnderQueryAuth(table, rewriteOperation); + } + PostponeMergeInputSource inputSource = + new PostponeMergeInputSource(plan, table, rewriteOperation); DataStream inputs = env.fromSource( new PaimonDataStreamSource<>(inputSource, table), diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/StaticFileStoreSource.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/StaticFileStoreSource.java index 04facbd49e29..b32f3d7f9379 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/StaticFileStoreSource.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/StaticFileStoreSource.java @@ -24,6 +24,7 @@ import org.apache.paimon.flink.source.assigners.PreAssignSplitAssigner; import org.apache.paimon.flink.source.assigners.SplitAssigner; import org.apache.paimon.table.ChainGroupReadTable; +import org.apache.paimon.table.Table; import org.apache.paimon.table.source.InnerTableScan; import org.apache.paimon.table.source.ReadBuilder; import org.apache.paimon.table.source.TableScan; @@ -38,6 +39,8 @@ import java.util.Collection; import java.util.List; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuthRules; import static org.apache.paimon.flink.FlinkConnectorOptions.SplitAssignMode; /** Bounded {@link FlinkSource} for reading records. It does not monitor new snapshots. */ @@ -57,6 +60,9 @@ public class StaticFileStoreSource extends FlinkSource { private final boolean skipPreloadTargetSnapshot; + @Nullable private String rewriteOperation; + @Nullable private Table rewriteTable; + public StaticFileStoreSource( ReadBuilder readBuilder, @Nullable Long limit, @@ -144,10 +150,23 @@ public Boundedness getBoundedness() { return Boundedness.BOUNDED; } + public StaticFileStoreSource withRewriteOperation(@Nullable String operation) { + this.rewriteOperation = operation; + return this; + } + + public StaticFileStoreSource withRewriteOperation(String operation, Table table) { + this.rewriteTable = table; + return withRewriteOperation(operation); + } + @Override public SplitEnumerator restoreEnumerator( SplitEnumeratorContext context, PendingSplitsCheckpoint checkpoint) { + if (rewriteOperation != null) { + rejectRewriteUnderQueryAuth(rewriteTable, rewriteOperation); + } Collection splits = checkpoint == null ? getSplits(context) : checkpoint.splits(); SplitAssigner splitAssigner = @@ -173,7 +192,12 @@ private List getSplits(SplitEnumeratorContext context) { ((InnerTableScan) scan) .withMetricRegistry(new FlinkMetricRegistry(context.metricGroup())); } - return splitGenerator.createSplits(scan.plan()); + TableScan.Plan plan = scan.plan(); + if (rewriteOperation != null) { + rejectRewriteUnderQueryAuth(rewriteTable, rewriteOperation); + rejectRewriteUnderQueryAuthRules(plan.splits(), rewriteOperation); + } + return splitGenerator.createSplits(plan); } public static SplitAssigner createSplitAssigner( diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java index 1b1ad2392fe1..c7d8b8a6d16a 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java @@ -69,6 +69,9 @@ import java.util.TreeMap; import java.util.concurrent.CompletableFuture; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuthRules; + /** * This is the single (non-parallel) monitoring task, it is responsible for: * @@ -103,6 +106,8 @@ public class MonitorSource extends AbstractNonCoordinatedSource { private final boolean emitSnapshotWatermark; private final boolean isBounded; private final int maxSnapshotCount; + @Nullable private String rewriteOperation; + @Nullable private Table rewriteTable; public MonitorSource( ReadBuilder readBuilder, @@ -237,6 +242,10 @@ public InputStatus pollNext(ReaderOutput readerOutput) throws Exception { boolean isEmpty; try { List splits = isBounded ? batchScan.plan().splits() : scan.plan().splits(); + if (rewriteOperation != null) { + rejectRewriteUnderQueryAuth(rewriteTable, rewriteOperation); + rejectRewriteUnderQueryAuthRules(splits, rewriteOperation); + } isEmpty = splits.isEmpty(); splits.forEach(readerOutput::collect); if (!isBounded && maxSnapshotCount > 0 && !isEmpty) { @@ -357,6 +366,40 @@ public static DataStream buildSource( @Nullable Table table, RowType readType, boolean blobAsDescriptor) { + return buildSource( + env, + name, + typeInfo, + readBuilder, + monitorInterval, + emitSnapshotWatermark, + shuffleBucketWithPartition, + unordered, + nestedProjectedRowData, + isBounded, + limit, + table, + readType, + blobAsDescriptor, + null); + } + + public static DataStream buildSource( + StreamExecutionEnvironment env, + String name, + TypeInformation typeInfo, + ReadBuilder readBuilder, + long monitorInterval, + boolean emitSnapshotWatermark, + boolean shuffleBucketWithPartition, + boolean unordered, + NestedProjectedRowData nestedProjectedRowData, + boolean isBounded, + @Nullable Long limit, + @Nullable Table table, + RowType readType, + boolean blobAsDescriptor, + @Nullable String rewriteOperation) { int maxSnapshotCount = table == null ? -1 @@ -375,6 +418,8 @@ public static DataStream buildSource( emitSnapshotWatermark, isBounded, maxSnapshotCount); + monitorSource.rewriteOperation = rewriteOperation; + monitorSource.rewriteTable = table; Source source = monitorSource; if (table != null) { source = new PaimonDataStreamSource<>(monitorSource, table); diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java index d6e4ec52c5de..b6e107b24f3e 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java @@ -21,6 +21,13 @@ import org.apache.paimon.CoreOptions; import org.apache.paimon.catalog.Identifier; import org.apache.paimon.data.BinaryString; +import org.apache.paimon.flink.action.ActionBase; +import org.apache.paimon.flink.action.CompactChainTableAction; +import org.apache.paimon.flink.action.DataEvolutionMergeIntoAction; +import org.apache.paimon.flink.action.DeleteAction; +import org.apache.paimon.flink.action.MergeIntoAction; +import org.apache.paimon.flink.action.RescaleAction; +import org.apache.paimon.flink.action.SortCompactAction; import org.apache.paimon.partition.Partition; import org.apache.paimon.predicate.ConcatTransform; import org.apache.paimon.predicate.ConcatWsTransform; @@ -38,12 +45,15 @@ import org.apache.paimon.rest.RESTToken; import org.apache.paimon.schema.TableSchema; import org.apache.paimon.table.FileStoreTable; +import org.apache.paimon.table.Table; import org.apache.paimon.types.DataTypes; import org.apache.paimon.utils.BlockingIterator; import org.apache.paimon.shade.guava30.com.google.common.collect.ImmutableList; import org.apache.paimon.shade.guava30.com.google.common.collect.ImmutableMap; +import org.apache.flink.api.common.RuntimeExecutionMode; +import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.catalog.Catalog; import org.apache.flink.table.catalog.CatalogFunction; import org.apache.flink.table.catalog.CatalogFunctionImpl; @@ -53,6 +63,9 @@ import org.apache.flink.table.resource.ResourceUri; import org.apache.flink.types.Row; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; import java.util.Arrays; import java.util.Collections; @@ -65,6 +78,7 @@ import java.util.concurrent.TimeUnit; 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.junit.jupiter.api.Assertions.assertThrows; @@ -260,6 +274,299 @@ private void validateTotalBuckets( } } + @ParameterizedTest + @CsvSource({"false,false", "false,true", "true,false", "true,true"}) + public void testRowLevelOperationsRequireFullTableAccess( + boolean dataEvolution, boolean masking) { + String tableName = DATABASE_NAME + ".t_rewrite"; + batchSql( + "CREATE TABLE " + + tableName + + " (id INT, ssn STRING, note STRING, p INT) PARTITIONED BY (p)" + + " WITH ('query-auth.enabled'='true', " + + (dataEvolution + ? "'bucket'='-1', 'data-evolution.enabled'='true'," + + " 'row-tracking.enabled'='true', 'deletion-vectors.enabled'='true'" + : "'primary-key'='id,p', 'bucket'='1'") + + ")"); + batchSql("INSERT INTO " + tableName + " VALUES (1, 's1', 'n1', 1), (2, 's2', 'n2', 1)"); + Identifier identifier = Identifier.create(DATABASE_NAME, "t_rewrite"); + if (masking) { + restCatalogServer.setColumnMaskingAuth( + identifier, + Collections.singletonMap( + "ssn", + new ConcatTransform( + Collections.singletonList(BinaryString.fromString("****"))))); + } else { + restCatalogServer.setRowFilterAuth( + identifier, + Collections.singletonList( + LeafPredicate.of( + new FieldTransform(new FieldRef(0, "id", DataTypes.INT())), + Equal.INSTANCE, + Collections.singletonList(1)))); + } + assertThatThrownBy(() -> batchSql("UPDATE " + tableName + " SET note = ssn")) + .hasStackTraceContaining("UPDATE requires full-table access"); + for (String filter : Arrays.asList(" WHERE id = 2", " WHERE p = 1", "")) { + assertThatThrownBy(() -> batchSql("DELETE FROM " + tableName + filter)) + .hasStackTraceContaining("DELETE requires full-table access"); + } + + restCatalogServer.setRowFilterAuth(identifier, null); + restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); + assertThat(batchSql("SELECT * FROM " + tableName)) + .containsExactlyInAnyOrder(Row.of(1, "s1", "n1", 1), Row.of(2, "s2", "n2", 1)); + if (!dataEvolution) { + batchSql("UPDATE " + tableName + " SET note = ssn"); + assertThat(batchSql("SELECT note FROM " + tableName)) + .extracting(row -> row.getField(0)) + .containsExactlyInAnyOrder("s1", "s2"); + } + batchSql("DELETE FROM " + tableName + " WHERE id = 2"); + assertThat(batchSql("SELECT id FROM " + tableName)) + .extracting(row -> row.getField(0)) + .containsExactly(1); + batchSql("DELETE FROM " + tableName); + assertThat(batchSql("SELECT * FROM " + tableName)).isEmpty(); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void testRowLevelActionsRequireFullTableAccess(boolean dataEvolution) throws Exception { + String tableName = DATABASE_NAME + ".t_actions"; + batchSql( + "CREATE TABLE " + + tableName + + " (id STRING, note STRING) WITH ('query-auth.enabled'='true', " + + (dataEvolution + ? "'bucket'='-1', 'data-evolution.enabled'='true'," + + " 'row-tracking.enabled'='true', 'deletion-vectors.enabled'='true'" + : "'primary-key'='id', 'bucket'='1'") + + ")"); + batchSql( + "INSERT INTO " + + tableName + + " VALUES ('visible', 'original'), ('hidden', 'original')"); + Identifier identifier = Identifier.create(DATABASE_NAME, "t_actions"); + restCatalogServer.setRowFilterAuth( + identifier, + Collections.singletonList( + LeafPredicate.of( + new FieldTransform(new FieldRef(0, "id", DataTypes.STRING())), + Equal.INSTANCE, + Collections.singletonList(BinaryString.fromString("visible"))))); + restCatalogServer.setColumnMaskingAuth( + identifier, + Collections.singletonMap( + "id", + new ConcatTransform( + Collections.singletonList(BinaryString.fromString("hidden"))))); + assertThat(batchSql("SELECT * FROM " + tableName)) + .containsExactly(Row.of("hidden", "original")); + + String sourceSql = + "CREATE TEMPORARY VIEW " + + DATABASE_NAME + + ".S AS SELECT 'hidden' AS id, 'merged' AS note"; + ActionBase merge = + dataEvolution + ? new DataEvolutionMergeIntoAction( + DATABASE_NAME, "t_actions", catalogOptions()) + .withTargetAlias("T") + .withSourceSqls(sourceSql) + .withSourceTable(DATABASE_NAME + ".S") + .withMergeCondition("T.id = S.id") + .withMatchedUpdateSet("note = S.note") + .withSinkParallelism(1) + : new MergeIntoAction(DATABASE_NAME, "t_actions", catalogOptions()) + .withTargetAlias("T") + .withSourceSqls(sourceSql) + .withSourceTable(DATABASE_NAME + ".S") + .withMergeCondition("T.id = S.id") + .withMatchedUpsert(null, "note = S.note"); + merge.withStreamExecutionEnvironment( + StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1)); + Table table = flinkCatalog().catalog().getTable(identifier); + long snapshotIdBeforeMerge = table.latestSnapshot().get().id(); + assertThatThrownBy(merge::run) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("MERGE INTO requires full-table access"); + assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotIdBeforeMerge); + long snapshotIdBeforeDelete = table.latestSnapshot().get().id(); + assertThatThrownBy( + () -> + new DeleteAction( + DATABASE_NAME, + "t_actions", + "TRUE", + catalogOptions()) + .run()) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("DELETE requires full-table access"); + assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotIdBeforeDelete); + + restCatalogServer.setRowFilterAuth(identifier, null); + restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); + assertThat(batchSql("SELECT * FROM " + tableName)) + .containsExactlyInAnyOrder( + Row.of("visible", "original"), Row.of("hidden", "original")); + merge.run(); + assertThat(batchSql("SELECT note FROM " + tableName + " ORDER BY id")) + .extracting(row -> row.getField(0)) + .containsExactly("merged", "original"); + new DeleteAction(DATABASE_NAME, "t_actions", "TRUE", catalogOptions()) + .withStreamExecutionEnvironment( + StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1)) + .run(); + assertThat(batchSql("SELECT * FROM " + tableName)).isEmpty(); + } + + @ParameterizedTest + @CsvSource({ + "false,false,false", + "false,true,false", + "true,false,false", + "true,true,false", + "false,false,true", + "false,true,true", + "true,false,true", + "true,true,true" + }) + public void testMaintenanceRewritesRequireFullTableAccess( + boolean sort, boolean dedicatedSplits, boolean filterAll) throws Exception { + String tableName = DATABASE_NAME + ".t_compact"; + batchSql( + "CREATE TABLE " + + tableName + + " (id INT, ssn STRING) WITH ('query-auth.enabled'='true', " + + "'scan.dedicated-split-generation'='" + + dedicatedSplits + + "', " + + (sort ? "'bucket'='-1'" : "'primary-key'='id', 'bucket'='1'") + + ")"); + batchSql("INSERT INTO " + tableName + " VALUES (1, 's1'), (2, 's2')"); + Identifier identifier = Identifier.create(DATABASE_NAME, "t_compact"); + Predicate rowFilter = + LeafPredicate.of( + new FieldTransform(new FieldRef(0, "id", DataTypes.INT())), + Equal.INSTANCE, + Collections.singletonList(filterAll ? 3 : 1)); + restCatalogServer.setRowFilterAuth(identifier, Collections.singletonList(rowFilter)); + restCatalogServer.setColumnMaskingAuth( + identifier, + Collections.singletonMap( + "ssn", + new ConcatTransform( + Collections.singletonList(BinaryString.fromString("****"))))); + ActionBase action = + sort + ? new SortCompactAction( + DATABASE_NAME, + "t_compact", + catalogOptions(), + Collections.emptyMap()) + .withOrderStrategy("order") + .withOrderColumns("id") + : new RescaleAction(DATABASE_NAME, "t_compact", catalogOptions()) + .withBucketNum(2); + StreamExecutionEnvironment env = + StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1); + action.withStreamExecutionEnvironment(env); + assertThatThrownBy(action::build) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining( + (sort ? "Sort compaction" : "Rescale") + " requires full-table access"); + + restCatalogServer.setRowFilterAuth(identifier, null); + restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); + Table table = flinkCatalog().catalog().getTable(identifier); + long snapshotId = table.latestSnapshot().get().id(); + action.build(); + restCatalogServer.setRowFilterAuth(identifier, Collections.singletonList(rowFilter)); + assertThatThrownBy(env::execute) + .hasStackTraceContaining( + (sort ? "Sort compaction" : "Rescale") + " requires full-table access"); + assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); + restCatalogServer.setRowFilterAuth(identifier, null); + assertThat(batchSql("SELECT * FROM " + tableName)) + .containsExactlyInAnyOrder(Row.of(1, "s1"), Row.of(2, "s2")); + action.run(); + assertThat(batchSql("SELECT * FROM " + tableName)) + .containsExactlyInAnyOrder(Row.of(1, "s1"), Row.of(2, "s2")); + } + + @Test + public void testChainCompactionRequiresFullTableAccess() throws Exception { + batchSql( + "CREATE TABLE " + + DATABASE_NAME + + ".t_chain (id INT, note STRING, dt STRING)" + + " PARTITIONED BY (dt) WITH ('primary-key'='dt,id', 'bucket-key'='id'," + + " 'bucket'='1', 'sequence.field'='id', 'chain-table.enabled'='true', 'query-auth.enabled'='true'," + + " 'partition.timestamp-pattern'='$dt', 'partition.timestamp-formatter'='yyyyMMdd')"); + for (String branch : Arrays.asList("snapshot", "delta")) { + batchSql("CALL sys.create_branch('" + DATABASE_NAME + ".t_chain', '" + branch + "')"); + } + for (String suffix : Arrays.asList("", "$branch_snapshot", "$branch_delta")) { + batchSql( + "ALTER TABLE " + + DATABASE_NAME + + ".`t_chain" + + suffix + + "` SET (" + + "'scan.fallback-snapshot-branch'='snapshot', 'scan.fallback-delta-branch'='delta')"); + } + String snapshotTable = DATABASE_NAME + ".`t_chain$branch_snapshot`"; + FileStoreTable mainTable = + (FileStoreTable) + flinkCatalog() + .catalog() + .getTable(Identifier.create(DATABASE_NAME, "t_chain")); + // Branch paths share the main table's token in the test file IO. + assertThat(mainTable.fileIO().exists(mainTable.location())).isTrue(); + batchSql( + "INSERT INTO " + + snapshotTable + + " VALUES (1, 'one', '20261001'), (2, 'two', '20261001')"); + batchSql( + "INSERT INTO " + + DATABASE_NAME + + ".`t_chain$branch_delta` VALUES (3, 'three', '20261002')"); + Table table = + flinkCatalog() + .catalog() + .getTable(new Identifier(DATABASE_NAME, "t_chain", "snapshot")); + long snapshotId = table.latestSnapshot().get().id(); + StreamExecutionEnvironment env = + StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1); + env.setRuntimeMode(RuntimeExecutionMode.BATCH); + CompactChainTableAction action = + new CompactChainTableAction( + DATABASE_NAME, "t_chain", catalogOptions(), "dt=20261002", false); + action.withStreamExecutionEnvironment(env); + Map masking = + Collections.singletonMap( + "note", + new ConcatTransform( + Collections.singletonList(BinaryString.fromString("****")))); + Identifier identifier = Identifier.create(DATABASE_NAME, "t_chain"); + List chainIdentifiers = + Arrays.asList( + identifier, + new Identifier(DATABASE_NAME, "t_chain", "snapshot"), + new Identifier(DATABASE_NAME, "t_chain", "delta")); + chainIdentifiers.forEach(id -> restCatalogServer.setColumnMaskingAuth(id, masking)); + assertThatThrownBy(action::build) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("Chain table compaction requires full-table access"); + assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); + chainIdentifiers.forEach( + id -> restCatalogServer.setColumnMaskingAuth(id, Collections.emptyMap())); + assertThatCode(action::run).doesNotThrowAnyException(); + } + @Test public void testColumnMasking() { String maskingTable = "column_masking_table"; diff --git a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala index fa9c436bf266..b8abdc8ed90a 100644 --- a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala +++ b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala @@ -21,6 +21,7 @@ package org.apache.paimon.spark.commands import org.apache.paimon.CoreOptions import org.apache.paimon.CoreOptions.GlobalIndexColumnUpdateAction import org.apache.paimon.Snapshot +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth import org.apache.paimon.data.BinaryRow import org.apache.paimon.deletionvectors.DeletionVector import org.apache.paimon.format.blob.BlobFileFormat.isBlobFile @@ -307,6 +308,7 @@ case class MergeIntoPaimonDataEvolutionTable( lazy val tableSchema: StructType = targetSparkTable.schema override def run(sparkSession: SparkSession): Seq[Row] = { + rejectRewriteUnderQueryAuth(table, "MERGE INTO") // Persist the schema that the analyzer evolved in memory (commit deferred to execution). SchemaEvolutionHelper.commitEvolvedSchemaAtExecution(table, targetRelation, sparkSession) invokeMergeInto(sparkSession) diff --git a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala index d51504059df9..d7d650e7de88 100644 --- a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala +++ b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala @@ -19,6 +19,7 @@ package org.apache.paimon.spark.commands import org.apache.paimon.Snapshot +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth import org.apache.paimon.spark.SparkTable import org.apache.paimon.spark.catalyst.analysis.{PaimonRelation, PaimonUpdateAction} import org.apache.paimon.spark.schema.{PaimonMetadataColumn, SparkSystemColumns} @@ -84,6 +85,7 @@ case class MergeIntoPaimonTable( } override def run(sparkSession: SparkSession): Seq[Row] = { + rejectRewriteUnderQueryAuth(table, "MERGE INTO") // Avoid that more than one source rows match the same target row. checkMatchRationality(sparkSession) // Persist the schema that the analyzer evolved in memory (commit deferred to execution). diff --git a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/CompactChainTableProcedure.java b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/CompactChainTableProcedure.java index 36ab181aec4b..465a0f8f7913 100644 --- a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/CompactChainTableProcedure.java +++ b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/CompactChainTableProcedure.java @@ -48,6 +48,7 @@ import java.util.List; import java.util.Map; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; import static org.apache.paimon.utils.Preconditions.checkArgument; import static org.apache.spark.sql.types.DataTypes.BooleanType; import static org.apache.spark.sql.types.DataTypes.StringType; @@ -133,6 +134,7 @@ private boolean execute( DataSourceV2Relation relation, String partitionStr, boolean overwrite) { + rejectRewriteUnderQueryAuth(table, "Chain table compaction"); FileStoreTable snapshotTable = table.wrapped(); ChainGroupReadTable.ChainTableBatchScan scan = diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonPartitionManagement.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonPartitionManagement.scala index 2232b6dd3407..3a08d9027fe4 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonPartitionManagement.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonPartitionManagement.scala @@ -19,6 +19,7 @@ package org.apache.paimon.spark import org.apache.paimon.CoreOptions +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth import org.apache.paimon.data.{GenericRow, InternalRow => PaimonInternalRow, Timestamp} import org.apache.paimon.data.serializer.InternalRowSerializer import org.apache.paimon.options.Options @@ -279,6 +280,7 @@ trait PaimonPartitionManagement extends SupportsAtomicPartitionManagement with L } override def truncatePartitions(idents: Array[InternalRow]): Boolean = { + rejectRewriteUnderQueryAuth(table, "TRUNCATE") table match { case fileStoreTable: FileStoreTable => truncatePartitionsByValue(fileStoreTable, idents) diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonSparkTableBase.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonSparkTableBase.scala index aa537f22b363..fb052db3b7a0 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonSparkTableBase.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonSparkTableBase.scala @@ -20,6 +20,7 @@ package org.apache.paimon.spark import org.apache.paimon.CoreOptions import org.apache.paimon.CoreOptions.BucketFunctionType +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth import org.apache.paimon.options.CatalogOptions.TABLE_TYPE import org.apache.paimon.options.Options import org.apache.paimon.spark.catalog.functions.BucketFunction @@ -212,6 +213,7 @@ abstract class PaimonSparkTableBase(val table: Table) } def truncateTable: Boolean = { + rejectRewriteUnderQueryAuth(table, "TRUNCATE") val commit = table.newBatchWriteBuilder().newCommit() try { commit.truncateTable() diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkTable.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkTable.scala index 2dd70920cd83..3d7794c080fa 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkTable.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkTable.scala @@ -18,6 +18,7 @@ package org.apache.paimon.spark +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth import org.apache.paimon.spark.read.ObjectTableScanBuilder import org.apache.paimon.spark.rowops.{PaimonSparkCopyOnWriteOperation, PaimonSparkDeltaOperation} import org.apache.paimon.table.`object`.ObjectTable @@ -64,6 +65,7 @@ class SparkTableWithRowLevelOps(tableArg: Table) override def newRowLevelOperationBuilder( info: RowLevelOperationInfo): RowLevelOperationBuilder = { + rejectRewriteUnderQueryAuth(table, info.command().toString) table match { case t: FileStoreTable => if (SparkTable.supportsV2DeltaOps(this)) { () => new PaimonSparkDeltaOperation(t, info) } diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DeleteFromPaimonTableCommand.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DeleteFromPaimonTableCommand.scala index e8cae8ea523a..e002abaa66c6 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DeleteFromPaimonTableCommand.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DeleteFromPaimonTableCommand.scala @@ -19,6 +19,7 @@ package org.apache.paimon.spark.commands import org.apache.paimon.{CoreOptions, Snapshot} +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth import org.apache.paimon.spark.catalyst.analysis.expressions.ExpressionHelper import org.apache.paimon.spark.schema.SparkSystemColumns.ROW_KIND_COL import org.apache.paimon.table.FileStoreTable @@ -42,6 +43,7 @@ case class DeleteFromPaimonTableCommand( with SupportsSubquery { override def run(sparkSession: SparkSession): Seq[Row] = { + rejectRewriteUnderQueryAuth(table, "DELETE") val commitMessages = if (usePKUpsertDelete()) { performPrimaryKeyDelete(sparkSession) } else { diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala index fa9c436bf266..b8abdc8ed90a 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala @@ -21,6 +21,7 @@ package org.apache.paimon.spark.commands import org.apache.paimon.CoreOptions import org.apache.paimon.CoreOptions.GlobalIndexColumnUpdateAction import org.apache.paimon.Snapshot +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth import org.apache.paimon.data.BinaryRow import org.apache.paimon.deletionvectors.DeletionVector import org.apache.paimon.format.blob.BlobFileFormat.isBlobFile @@ -307,6 +308,7 @@ case class MergeIntoPaimonDataEvolutionTable( lazy val tableSchema: StructType = targetSparkTable.schema override def run(sparkSession: SparkSession): Seq[Row] = { + rejectRewriteUnderQueryAuth(table, "MERGE INTO") // Persist the schema that the analyzer evolved in memory (commit deferred to execution). SchemaEvolutionHelper.commitEvolvedSchemaAtExecution(table, targetRelation, sparkSession) invokeMergeInto(sparkSession) diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala index d51504059df9..d7d650e7de88 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala @@ -19,6 +19,7 @@ package org.apache.paimon.spark.commands import org.apache.paimon.Snapshot +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth import org.apache.paimon.spark.SparkTable import org.apache.paimon.spark.catalyst.analysis.{PaimonRelation, PaimonUpdateAction} import org.apache.paimon.spark.schema.{PaimonMetadataColumn, SparkSystemColumns} @@ -84,6 +85,7 @@ case class MergeIntoPaimonTable( } override def run(sparkSession: SparkSession): Seq[Row] = { + rejectRewriteUnderQueryAuth(table, "MERGE INTO") // Avoid that more than one source rows match the same target row. checkMatchRationality(sparkSession) // Persist the schema that the analyzer evolved in memory (commit deferred to execution). diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/UpdatePaimonDataEvolutionTableCommand.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/UpdatePaimonDataEvolutionTableCommand.scala index 9eac851acf0f..8da5f74f8bc7 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/UpdatePaimonDataEvolutionTableCommand.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/UpdatePaimonDataEvolutionTableCommand.scala @@ -18,6 +18,7 @@ package org.apache.paimon.spark.commands +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth import org.apache.paimon.errors.ErrorMessages import org.apache.paimon.spark.SparkTable import org.apache.paimon.spark.leafnode.PaimonLeafRunnableCommand @@ -43,6 +44,7 @@ case class UpdatePaimonDataEvolutionTableCommand( with Logging { override def run(sparkSession: SparkSession): Seq[Row] = { + rejectRewriteUnderQueryAuth(v2Table.getTable, "UPDATE") val maxAttempts = math.max(1, OptionUtils.dataEvolutionUpdateConflictRetryMaxAttempts()) val retryWaitMs = math.max(0L, OptionUtils.dataEvolutionUpdateConflictRetryWaitMs()) val canRetry = deterministicUpdate diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/UpdatePaimonTableCommand.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/UpdatePaimonTableCommand.scala index 1f1622fe2b77..4e36a0d01abb 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/UpdatePaimonTableCommand.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/UpdatePaimonTableCommand.scala @@ -19,6 +19,7 @@ package org.apache.paimon.spark.commands import org.apache.paimon.Snapshot +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth import org.apache.paimon.spark.schema.PaimonMetadataColumn.{ROW_ID_COLUMN, SEQUENCE_NUMBER_COLUMN} import org.apache.paimon.spark.schema.SparkSystemColumns.ROW_KIND_COL import org.apache.paimon.table.FileStoreTable @@ -47,6 +48,7 @@ case class UpdatePaimonTableCommand( } override def run(sparkSession: SparkSession): Seq[Row] = { + rejectRewriteUnderQueryAuth(table, "UPDATE") val commitMessages = if (withPrimaryKeys) { performUpdateForPkTable(sparkSession) diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/TruncatePaimonTableWithFilterExec.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/TruncatePaimonTableWithFilterExec.scala index 1e122f698457..c1086062c578 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/TruncatePaimonTableWithFilterExec.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/TruncatePaimonTableWithFilterExec.scala @@ -19,6 +19,7 @@ package org.apache.paimon.spark.execution import org.apache.paimon.CoreOptions +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth import org.apache.paimon.options.Options import org.apache.paimon.partition.PartitionPredicate import org.apache.paimon.spark.leafnode.PaimonLeafV2CommandExec @@ -36,6 +37,7 @@ case class TruncatePaimonTableWithFilterExec( extends PaimonLeafV2CommandExec { override def run(): Seq[InternalRow] = { + rejectRewriteUnderQueryAuth(table, "DELETE") partitionPredicate match { case Some(p) => table match { diff --git a/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java b/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java index c9ff2b5fd34a..aa11d609eca9 100644 --- a/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java +++ b/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java @@ -47,6 +47,7 @@ import org.apache.paimon.rest.auth.BearTokenAuthProvider; import org.apache.paimon.rest.responses.ConfigResponse; import org.apache.paimon.spark.catalog.WithPaimonCatalog; +import org.apache.paimon.table.Table; import org.apache.paimon.types.DataField; import org.apache.paimon.types.DataTypes; @@ -60,6 +61,9 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.io.File; import java.io.IOException; @@ -70,8 +74,10 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Test for spark read from Rest catalog. */ @@ -258,6 +264,146 @@ public void testMapFunction() throws Exception { cleanFunction(functionName); } + @ParameterizedTest + @MethodSource("rowLevelTableOptions") + public void testRowLevelOperationsRequireFullTableAccess(boolean useV2Write, String options) { + spark.conf().set("spark.paimon.write.use-v2-write", useV2Write); + spark.sql( + "CREATE TABLE t_rewrite (id INT, ssn STRING, note STRING, p INT) PARTITIONED BY (p)" + + " TBLPROPERTIES ('query-auth.enabled'='true', " + + options + + ")"); + spark.sql("INSERT INTO t_rewrite VALUES (1, 's1', 'n1', 1), (2, 's2', 'n2', 1)"); + Identifier identifier = Identifier.create("db2", "t_rewrite"); + Predicate rowFilter = + LeafPredicate.of( + new FieldTransform(new FieldRef(0, "id", DataTypes.INT())), + Equal.INSTANCE, + Collections.singletonList(1)); + Transform mask = + new ConcatTransform(Collections.singletonList(BinaryString.fromString("****"))); + String merge = + "MERGE INTO t_rewrite t USING (SELECT 2 AS id) s ON t.id = s.id" + + " WHEN MATCHED THEN UPDATE SET note = t.ssn"; + String[][] statements = { + {"UPDATE", "UPDATE t_rewrite SET note = ssn"}, + {"DELETE", "DELETE FROM t_rewrite WHERE id = 2"}, + {"DELETE", "DELETE FROM t_rewrite WHERE p = 1"}, + {"DELETE", "DELETE FROM t_rewrite"}, + {"MERGE", merge} + }; + for (boolean masking : new boolean[] {false, true}) { + restCatalogServer.setRowFilterAuth( + identifier, masking ? null : Collections.singletonList(rowFilter)); + restCatalogServer.setColumnMaskingAuth( + identifier, + masking ? Collections.singletonMap("ssn", mask) : Collections.emptyMap()); + for (String[] statement : statements) { + assertThatThrownBy(() -> spark.sql(statement[1]).collectAsList()) + .hasStackTraceContaining("UnsupportedOperationException") + .hasStackTraceContaining(statement[0]) + .hasStackTraceContaining("requires full-table access"); + } + } + + restCatalogServer.setRowFilterAuth(identifier, null); + restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); + assertThat(spark.sql("SELECT * FROM t_rewrite ORDER BY id").collectAsList().toString()) + .isEqualTo("[[1,s1,n1,1], [2,s2,n2,1]]"); + spark.sql("UPDATE t_rewrite SET note = ssn WHERE id = 1"); + spark.sql(merge); + assertThat(spark.sql("SELECT * FROM t_rewrite ORDER BY id").collectAsList().toString()) + .isEqualTo("[[1,s1,s1,1], [2,s2,s2,1]]"); + spark.sql("DELETE FROM t_rewrite WHERE id = 2"); + assertThat(spark.sql("SELECT id FROM t_rewrite").collectAsList().toString()) + .isEqualTo("[[1]]"); + spark.sql("DELETE FROM t_rewrite"); + assertThat(spark.sql("SELECT * FROM t_rewrite").collectAsList()).isEmpty(); + } + + @Test + public void testTruncateRequiresFullTableAccess() { + spark.sql( + "CREATE TABLE t_truncate (id INT, value STRING, p INT) PARTITIONED BY (p)" + + " TBLPROPERTIES ('query-auth.enabled'='true')"); + spark.sql("INSERT INTO t_truncate VALUES (1, 'one', 1), (2, 'two', 1), (3, 'three', 2)"); + Identifier identifier = Identifier.create("db2", "t_truncate"); + restCatalogServer.setRowFilterAuth( + identifier, + Collections.singletonList( + LeafPredicate.of( + new FieldTransform(new FieldRef(0, "id", DataTypes.INT())), + Equal.INSTANCE, + Collections.singletonList(1)))); + assertThatThrownBy(() -> spark.sql("TRUNCATE TABLE t_truncate").collectAsList()) + .hasStackTraceContaining("TRUNCATE requires full-table access"); + assertThatThrownBy( + () -> + spark.sql("TRUNCATE TABLE t_truncate PARTITION (p = 1)") + .collectAsList()) + .hasStackTraceContaining("TRUNCATE requires full-table access"); + assertThat(spark.sql("SELECT * FROM t_truncate").collectAsList().toString()) + .isEqualTo("[[1,one,1]]"); + + restCatalogServer.setRowFilterAuth(identifier, null); + spark.sql("TRUNCATE TABLE t_truncate PARTITION (p = 1)"); + assertThat(spark.sql("SELECT * FROM t_truncate").collectAsList().toString()) + .isEqualTo("[[3,three,2]]"); + spark.sql("TRUNCATE TABLE t_truncate"); + assertThat(spark.sql("SELECT * FROM t_truncate").collectAsList()).isEmpty(); + } + + private static Stream rowLevelTableOptions() { + return Stream.of( + Arguments.of(false, "'bucket'='-1'"), + Arguments.of(true, "'bucket'='-1'"), + Arguments.of(false, "'primary-key'='id,p', 'bucket'='1'"), + Arguments.of( + false, + "'bucket'='-1', 'data-evolution.enabled'='true'," + + " 'row-tracking.enabled'='true', 'deletion-vectors.enabled'='true'"), + Arguments.of(true, "'bucket'='-1', 'deletion-vectors.enabled'='true'")); + } + + @Test + public void testChainCompactionRequiresFullTableAccess() throws Exception { + spark.sql( + "CREATE TABLE t_chain (id INT, note STRING, dt STRING) PARTITIONED BY (dt)" + + " TBLPROPERTIES ('primary-key'='dt,id', 'bucket-key'='id', 'bucket'='1'," + + " 'sequence.field'='id', 'chain-table.enabled'='true', 'query-auth.enabled'='true'," + + " 'partition.timestamp-pattern'='$dt', 'partition.timestamp-formatter'='yyyyMMdd')"); + for (String branch : Arrays.asList("snapshot", "delta")) { + spark.sql("CALL sys.create_branch('db2.t_chain', '" + branch + "')"); + } + for (String suffix : Arrays.asList("", "$branch_snapshot", "$branch_delta")) { + spark.sql( + "ALTER TABLE `t_chain" + + suffix + + "` SET TBLPROPERTIES (" + + "'scan.fallback-snapshot-branch'='snapshot', 'scan.fallback-delta-branch'='delta')"); + } + spark.sql( + "INSERT INTO `t_chain$branch_snapshot` VALUES (1, 'one', '20261001'), (2, 'two', '20261001')"); + spark.sql("INSERT INTO `t_chain$branch_delta` VALUES (3, 'three', '20261002')"); + Table table = getPaimonCatalog().getTable(new Identifier("db2", "t_chain", "snapshot")); + long snapshotId = table.latestSnapshot().get().id(); + String compact = + "CALL sys.compact_chain_table(table => 'db2.t_chain', partition => 'dt=\"20261002\"')"; + Identifier identifier = Identifier.create("db2", "t_chain"); + restCatalogServer.setColumnMaskingAuth( + identifier, + Collections.singletonMap( + "note", + new ConcatTransform( + Collections.singletonList(BinaryString.fromString("****"))))); + assertThatThrownBy(() -> spark.sql(compact).collectAsList()) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("Chain table compaction requires full-table access"); + assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); + restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); + assertThatCode(() -> spark.sql(compact).collectAsList()).doesNotThrowAnyException(); + } + @Test public void testColumnMasking() { spark.sql( From 17e141c6dbf8c5383acd1cd0b76afb534ee73d13 Mon Sep 17 00:00:00 2001 From: Li Jiajia Date: Mon, 2 Nov 2026 00:56:16 -0800 Subject: [PATCH 02/10] [core][spark][flink] Check query auth for more rewrite paths The Flink merge-into actions checked query auth only when the merge was built. MergeIntoProcedure and callers of buildDataStream() submit the job afterwards, so a row filter or column mask added in between was applied to the target scan, and the filtered, masked rows were written back. The Flink delete action had the same gap between its check and its scans of the target. The merge-into and delete actions now read the target with an internal scan.rewrite-operation table option, and the Flink table sources pass it to the execution-time check that sort compaction and rescale use. Through the row tracking table of a Data Evolution table, the check authorizes the data table behind it, so a filter that leaves no split is not missed. The Data Evolution merge also authorizes again before it commits, which covers a source with _ROW_ID that does not read the target. A table without query auth only reads the table option. Spark plans a merge with only WHEN NOT MATCHED clauses on a V2 table as an append over an anti join, without the row-level operation that checks query auth, so rows whose keys the row filter hid were inserted again. PaimonMergeInto and the Spark 4.1 rewrite now read the target with the same option, so the Paimon scan checks when it plans the splits. The option is removed from the relation Spark appends to, so the cache refresh after the write still matches cached reads. The branches of a chain table read with the main table's identifier, so chain table compaction missed rules set only on a branch. The rewrite check now also authorizes a table with its own branch. --- .../java/org/apache/paimon/CoreOptions.java | 9 + .../paimon/catalog/TableQueryAuthResult.java | 32 +- .../paimon/table/system/RowTrackingTable.java | 4 + .../flink/action/DataEvolutionDelete.java | 6 +- .../action/DataEvolutionMergeIntoAction.java | 4 +- .../paimon/flink/action/DeleteAction.java | 4 +- .../paimon/flink/action/MergeIntoAction.java | 31 +- .../dataevolution/MergeIntoUpdateChecker.java | 4 + .../flink/source/BaseDataTableSource.java | 2 + .../flink/source/FlinkSourceBuilder.java | 4 - .../flink/source/StaticFileStoreSource.java | 9 +- .../flink/source/SystemTableSource.java | 6 +- .../flink/source/operator/MonitorSource.java | 34 +- .../paimon/flink/RESTCatalogITCase.java | 361 ++++++++++++------ .../spark/sql/paimon/shims/Spark4Shim.scala | 6 + .../apache/paimon/spark/PaimonBaseScan.scala | 7 + .../catalyst/analysis/PaimonMergeInto.scala | 20 +- .../catalyst/analysis/PaimonRelation.scala | 20 + .../optimizer/UnmarkRewriteWriteTarget.scala | 46 +++ .../PaimonSparkSessionExtensions.scala | 3 +- .../spark/sql/paimon/shims/SparkShim.scala | 4 + .../spark/SparkCatalogWithRestTest.java | 143 ++++--- .../spark/sql/paimon/shims/Spark3Shim.scala | 6 + .../analysis/Spark41MergeIntoRewrite.scala | 9 +- .../spark/sql/paimon/shims/Spark4Shim.scala | 6 + 25 files changed, 539 insertions(+), 241 deletions(-) create mode 100644 paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/optimizer/UnmarkRewriteWriteTarget.scala diff --git a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java index aa511a20e1b9..4d2616a68b1e 100644 --- a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java +++ b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java @@ -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 SCAN_REWRITE_OPERATION = + key("scan.rewrite-operation") + .stringType() + .noDefaultValue() + .withDescription( + "The rewrite reading this table, which fails when the read is under " + + "row filters or column masks."); + @ExcludeFromDocumentation("Only used internally to support materialized table") public static final ConfigOption MATERIALIZED_TABLE_DEFINITION_QUERY = key("materialized-table.definition-query") diff --git a/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java b/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java index 47f30d0a4c16..65aa433332a5 100644 --- a/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java +++ b/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java @@ -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; @@ -28,6 +29,7 @@ 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; @@ -38,6 +40,7 @@ import org.apache.paimon.table.source.Split; import org.apache.paimon.table.source.Splits; 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; @@ -146,15 +149,30 @@ public static void rejectSearchUnderQueryAuth(@Nullable Table 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; - if (fileStoreTable.coreOptions().queryAuthEnabled()) { - TableQueryAuthResult authResult = - fileStoreTable - .catalogEnvironment() - .tableQueryAuth(fileStoreTable.coreOptions()) - .auth(null); - rejectRewriteUnderQueryAuthRules(authResult, operation); + 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( diff --git a/paimon-core/src/main/java/org/apache/paimon/table/system/RowTrackingTable.java b/paimon-core/src/main/java/org/apache/paimon/table/system/RowTrackingTable.java index 519bf62d183c..ce87cd6d8ad1 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/system/RowTrackingTable.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/system/RowTrackingTable.java @@ -69,6 +69,10 @@ public RowTrackingTable(FileStoreTable wrapped) { } } + public FileStoreTable wrapped() { + return wrapped; + } + @Override public Optional latestSnapshot() { return wrapped.latestSnapshot(); diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java index 0f0433733309..f4cce057d7fe 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java @@ -39,6 +39,8 @@ import java.io.Serializable; import java.util.Collections; +import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; + /** Internal implementation which logically deletes rows from a Data Evolution append table. */ class DataEvolutionDelete implements Serializable { @@ -91,12 +93,14 @@ TableResult runInternal() { String query = String.format( "SELECT `_ROW_ID` FROM `%s`.`%s`.`%s$row_tracking` " - + "/*+ OPTIONS('scan.snapshot-id'='%d', '%s'='full') */ WHERE %s", + + "/*+ OPTIONS('scan.snapshot-id'='%d', '%s'='full', '%s'='DELETE') */" + + " WHERE %s", action.catalogName, action.identifier.getDatabaseName(), action.identifier.getObjectName(), baseSnapshotId, CoreOptions.SCALAR_INDEX_SEARCH_MODE.key(), + SCAN_REWRITE_OPERATION.key(), filter); LOG.info("Data-evolution delete source query: {}", query); diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java index 1c6eb9242eca..8a484e97ee0a 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java @@ -87,6 +87,7 @@ import java.util.function.Function; import java.util.stream.Collectors; +import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; import static org.apache.paimon.format.blob.BlobFileFormat.isBlobFile; import static org.apache.paimon.utils.ParameterUtils.parseCommaSeparatedKeyValues; @@ -307,12 +308,13 @@ public Tuple2, RowType> buildSource() { query = String.format( "SELECT %s, %s FROM %s INNER JOIN %s " - + "/*+ OPTIONS('%s'='full') */ AS RT ON %s", + + "/*+ OPTIONS('%s'='full', '%s'='MERGE INTO') */ AS RT ON %s", "`RT`.`_ROW_ID` as `_ROW_ID`", String.join(",", project), escapedSourceName(), escapedRowTrackingTargetName(), CoreOptions.SCALAR_INDEX_SEARCH_MODE.key(), + SCAN_REWRITE_OPERATION.key(), rewriteMergeCondition(mergeCondition)); } diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java index 895ff53eb4d1..5327928f6f5a 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java @@ -39,6 +39,7 @@ import java.util.stream.Collectors; import static org.apache.paimon.CoreOptions.MergeEngine.DEDUPLICATE; +import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; /** Delete from table action for Flink, dispatching by table type. */ @@ -118,10 +119,11 @@ private void runPrimaryKeyDelete() throws Exception { Table queriedTable = batchTEnv.sqlQuery( String.format( - "SELECT * FROM `%s`.`%s`.`%s` WHERE %s", + "SELECT * FROM `%s`.`%s`.`%s` /*+ OPTIONS('%s'='DELETE') */ WHERE %s", catalogName, identifier.getDatabaseName(), identifier.getObjectName(), + SCAN_REWRITE_OPERATION.key(), filter)); List> converters = diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java index 4fa7d61a0e8c..d56923c73784 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java @@ -48,6 +48,7 @@ import static org.apache.paimon.CoreOptions.MergeEngine.DEDUPLICATE; import static org.apache.paimon.CoreOptions.MergeEngine.PARTIAL_UPDATE; +import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; import static org.apache.paimon.utils.ParameterUtils.parseCommaSeparatedKeyValues; @@ -81,6 +82,10 @@ public class MergeIntoAction extends TableActionBase { public static final String IDENTIFIER_QUOTE = "`"; + // checks query auth again when the job reads the target + private static final String TARGET_SCAN_HINT = + String.format("/*+ OPTIONS('%s'='MERGE INTO') */", SCAN_REWRITE_OPERATION.key()); + // primary keys of target table private final List primaryKeys; @@ -282,7 +287,14 @@ private void handleTargetAlias() { // create a view 'targetAlias' in the path of target table, then we can find it with the // qualified name batchTEnv.createTemporaryView( - escapedTargetName(), batchTEnv.from(identifier.getFullName())); + escapedTargetName(), + batchTEnv.sqlQuery( + String.format( + "SELECT * FROM `%s`.`%s`.`%s` %s", + catalogName, + identifier.getDatabaseName(), + identifier.getObjectName(), + TARGET_SCAN_HINT))); } } @@ -339,7 +351,7 @@ private Optional> getMatchedUpsertDataStream() { String.format( "SELECT %s FROM %s INNER JOIN %s ON %s %s", String.join(",", normalizeFieldName(project)), - escapedTargetName(), + targetScan(), escapedSourceName(), mergeCondition, matchedUpsertCondition == null ? "" : "WHERE " + matchedUpsertCondition); @@ -383,7 +395,7 @@ private Optional> getNotMatchedUpsertDataStream() { String.format( "SELECT %s FROM %s WHERE NOT EXISTS (SELECT * FROM %s WHERE %s) %s", String.join(",", normalizeFieldName(project)), - escapedTargetName(), + targetScan(), escapedSourceName(), mergeCondition, notMatchedBySourceUpsertCondition == null @@ -414,7 +426,7 @@ private Optional> getMatchedDeleteDataStream() { String.format( "SELECT %s FROM %s INNER JOIN %s ON %s %s", String.join(",", normalizeFieldName(project)), - escapedTargetName(), + targetScan(), escapedSourceName(), mergeCondition, matchedDeleteCondition == null ? "" : "WHERE " + matchedDeleteCondition); @@ -436,7 +448,7 @@ private Optional> getNotMatchedDeleteDataStream() { String.format( "SELECT %s FROM %s WHERE NOT EXISTS (SELECT * FROM %s WHERE %s) %s", String.join(",", normalizeFieldName(targetFieldNames)), - escapedTargetName(), + targetScan(), escapedSourceName(), mergeCondition, notMatchedBySourceDeleteCondition == null @@ -461,7 +473,7 @@ private Optional> getInsertDataStream() { "SELECT %s FROM %s WHERE NOT EXISTS (SELECT * FROM %s WHERE %s) %s", notMatchedInsertValues, escapedSourceName(), - escapedTargetName(), + targetScan(), mergeCondition, notMatchedInsertCondition == null ? "" @@ -519,6 +531,13 @@ private String escapedTargetName() { "`%s`.`%s`.`%s`", catalogName, identifier.getDatabaseName(), targetTableName()); } + // the alias view reads the target with the hint already + private String targetScan() { + return targetAlias == null + ? escapedTargetName() + " " + TARGET_SCAN_HINT + : escapedTargetName(); + } + private String escapedSourceName() { return Arrays.stream(sourceTable.split("\\.")) .map(s -> String.format("`%s`", s)) diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/dataevolution/MergeIntoUpdateChecker.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/dataevolution/MergeIntoUpdateChecker.java index 39518e6147f8..e9f9c06433aa 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/dataevolution/MergeIntoUpdateChecker.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/dataevolution/MergeIntoUpdateChecker.java @@ -46,6 +46,8 @@ import java.util.Set; import java.util.stream.Collectors; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; + /** * The checker for merge into update result. It will check each committable to see if some * global-indexed columns are updated. It will take some actions according to {@link @@ -86,6 +88,8 @@ public void processElement(StreamRecord element) throws Exception { @Override public void endInput() throws Exception { + // Authorize again before the commit, as a source with _ROW_ID does not read the target. + rejectRewriteUnderQueryAuth(table, "MERGE INTO"); checkUpdatedColumns(); } diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/BaseDataTableSource.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/BaseDataTableSource.java index 9bdbf0e7dc72..1eb6faa08355 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/BaseDataTableSource.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/BaseDataTableSource.java @@ -74,6 +74,7 @@ import static org.apache.flink.util.Preconditions.checkArgument; import static org.apache.paimon.CoreOptions.CHANGELOG_PRODUCER; import static org.apache.paimon.CoreOptions.MergeEngine.FIRST_ROW; +import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.flink.FlinkConnectorOptions.LOOKUP_ASYNC; import static org.apache.paimon.flink.FlinkConnectorOptions.LOOKUP_ASYNC_THREAD_NUMBER; import static org.apache.paimon.flink.FlinkConnectorOptions.SCAN_PARALLELISM; @@ -208,6 +209,7 @@ public ScanRuntimeProvider getScanRuntimeProvider(ScanContext scanContext) { .limit(limit) .watermarkStrategy(watermarkStrategy) .dynamicPartitionFilteringFields(dynamicPartitionFilteringFields()); + options.getOptional(SCAN_REWRITE_OPERATION).ifPresent(sourceBuilder::withRewriteOperation); return new PaimonDataStreamScanProvider( !unbounded, env -> diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/FlinkSourceBuilder.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/FlinkSourceBuilder.java index 232550d0c07b..e75ca9ed5288 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/FlinkSourceBuilder.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/FlinkSourceBuilder.java @@ -67,7 +67,6 @@ import java.util.Optional; import static org.apache.flink.table.types.utils.TypeConversions.fromLogicalToDataType; -import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; import static org.apache.paimon.flink.FlinkConnectorOptions.SOURCE_OPERATOR_UID_SUFFIX; import static org.apache.paimon.flink.FlinkConnectorOptions.generateCustomUid; import static org.apache.paimon.flink.LogicalTypeConversion.toLogicalType; @@ -291,9 +290,6 @@ private void checkConsumerId() { private @Nullable DataStream buildPostponeMergeSource() { FileStoreTable fileStoreTable = (FileStoreTable) table; - if (rewriteOperation != null) { - rejectRewriteUnderQueryAuth(table, rewriteOperation); - } if (fileStoreTable.coreOptions().startupMode() == CoreOptions.StartupMode.COMPACTED_FULL) { return null; } diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/StaticFileStoreSource.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/StaticFileStoreSource.java index b32f3d7f9379..a7a21057f210 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/StaticFileStoreSource.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/StaticFileStoreSource.java @@ -150,14 +150,10 @@ public Boundedness getBoundedness() { return Boundedness.BOUNDED; } - public StaticFileStoreSource withRewriteOperation(@Nullable String operation) { + public StaticFileStoreSource withRewriteOperation(@Nullable String operation, Table table) { this.rewriteOperation = operation; - return this; - } - - public StaticFileStoreSource withRewriteOperation(String operation, Table table) { this.rewriteTable = table; - return withRewriteOperation(operation); + return this; } @Override @@ -194,7 +190,6 @@ private List getSplits(SplitEnumeratorContext context) { } TableScan.Plan plan = scan.plan(); if (rewriteOperation != null) { - rejectRewriteUnderQueryAuth(rewriteTable, rewriteOperation); rejectRewriteUnderQueryAuthRules(plan.splits(), rewriteOperation); } return splitGenerator.createSplits(plan); diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/SystemTableSource.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/SystemTableSource.java index d4fbd333a2b1..323c5e0fbfdc 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/SystemTableSource.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/SystemTableSource.java @@ -40,6 +40,7 @@ import javax.annotation.Nullable; +import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.flink.FlinkConnectorOptions.SCAN_PARALLELISM; /** A {@link FlinkTableSource} for system table. */ @@ -137,7 +138,7 @@ public ScanRuntimeProvider getScanRuntimeProvider(ScanContext scanContext) { new ContinuousFileStoreSource( readBuilder, table.options(), limit, isUnordered(table), rowData); } else { - source = + StaticFileStoreSource staticSource = new StaticFileStoreSource( readBuilder, limit, @@ -152,6 +153,9 @@ public ScanRuntimeProvider getScanRuntimeProvider(ScanContext scanContext) { .getOrDefault( CoreOptions.BLOB_AS_DESCRIPTOR.key(), "false")), false); + source = + staticSource.withRewriteOperation( + table.options().get(SCAN_REWRITE_OPERATION.key()), table); } return new PaimonDataStreamScanProvider( source.getBoundedness() == Boundedness.BOUNDED, diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java index c7d8b8a6d16a..28d8a85fb0a9 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java @@ -348,39 +348,7 @@ public static DataStream buildSource( limit, table, readBuilder.readType(), - false); - } - - public static DataStream buildSource( - StreamExecutionEnvironment env, - String name, - TypeInformation typeInfo, - ReadBuilder readBuilder, - long monitorInterval, - boolean emitSnapshotWatermark, - boolean shuffleBucketWithPartition, - boolean unordered, - NestedProjectedRowData nestedProjectedRowData, - boolean isBounded, - @Nullable Long limit, - @Nullable Table table, - RowType readType, - boolean blobAsDescriptor) { - return buildSource( - env, - name, - typeInfo, - readBuilder, - monitorInterval, - emitSnapshotWatermark, - shuffleBucketWithPartition, - unordered, - nestedProjectedRowData, - isBounded, - limit, - table, - readType, - blobAsDescriptor, + false, null); } diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java index b6e107b24f3e..afa1853d4606 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java @@ -46,6 +46,7 @@ import org.apache.paimon.schema.TableSchema; import org.apache.paimon.table.FileStoreTable; import org.apache.paimon.table.Table; +import org.apache.paimon.types.DataType; import org.apache.paimon.types.DataTypes; import org.apache.paimon.utils.BlockingIterator; @@ -53,19 +54,25 @@ import org.apache.paimon.shade.guava30.com.google.common.collect.ImmutableMap; import org.apache.flink.api.common.RuntimeExecutionMode; +import org.apache.flink.api.dag.Transformation; +import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; +import org.apache.flink.streaming.api.functions.sink.v2.DiscardingSink; +import org.apache.flink.table.api.TableResult; import org.apache.flink.table.catalog.Catalog; import org.apache.flink.table.catalog.CatalogFunction; import org.apache.flink.table.catalog.CatalogFunctionImpl; import org.apache.flink.table.catalog.FunctionLanguage; import org.apache.flink.table.catalog.ObjectPath; +import org.apache.flink.table.data.RowData; import org.apache.flink.table.resource.ResourceType; import org.apache.flink.table.resource.ResourceUri; import org.apache.flink.types.Row; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; -import org.junit.jupiter.params.provider.ValueSource; + +import javax.annotation.Nullable; import java.util.Arrays; import java.util.Collections; @@ -279,33 +286,17 @@ private void validateTotalBuckets( public void testRowLevelOperationsRequireFullTableAccess( boolean dataEvolution, boolean masking) { String tableName = DATABASE_NAME + ".t_rewrite"; - batchSql( - "CREATE TABLE " - + tableName - + " (id INT, ssn STRING, note STRING, p INT) PARTITIONED BY (p)" - + " WITH ('query-auth.enabled'='true', " - + (dataEvolution - ? "'bucket'='-1', 'data-evolution.enabled'='true'," - + " 'row-tracking.enabled'='true', 'deletion-vectors.enabled'='true'" - : "'primary-key'='id,p', 'bucket'='1'") - + ")"); + createAuthTable( + "t_rewrite", + "(id INT, ssn STRING, note STRING, p INT) PARTITIONED BY (p)", + dataEvolution, + "id,p"); batchSql("INSERT INTO " + tableName + " VALUES (1, 's1', 'n1', 1), (2, 's2', 'n2', 1)"); Identifier identifier = Identifier.create(DATABASE_NAME, "t_rewrite"); if (masking) { - restCatalogServer.setColumnMaskingAuth( - identifier, - Collections.singletonMap( - "ssn", - new ConcatTransform( - Collections.singletonList(BinaryString.fromString("****"))))); + restCatalogServer.setColumnMaskingAuth(identifier, mask("ssn", "****")); } else { - restCatalogServer.setRowFilterAuth( - identifier, - Collections.singletonList( - LeafPredicate.of( - new FieldTransform(new FieldRef(0, "id", DataTypes.INT())), - Equal.INSTANCE, - Collections.singletonList(1)))); + restCatalogServer.setRowFilterAuth(identifier, equalTo(0, "id", DataTypes.INT(), 1)); } assertThatThrownBy(() -> batchSql("UPDATE " + tableName + " SET note = ssn")) .hasStackTraceContaining("UPDATE requires full-table access"); @@ -333,96 +324,231 @@ public void testRowLevelOperationsRequireFullTableAccess( } @ParameterizedTest - @ValueSource(booleans = {false, true}) - public void testRowLevelActionsRequireFullTableAccess(boolean dataEvolution) throws Exception { - String tableName = DATABASE_NAME + ".t_actions"; + @CsvSource({"false,false", "false,true", "true,false", "true,true"}) + public void testMergeIntoChecksQueryAuthWhenTheJobReads(boolean dataEvolution, boolean alias) + throws Exception { + String tableName = DATABASE_NAME + ".t_merge"; + createAuthTable("t_merge", "(id STRING, note STRING)", dataEvolution, "id"); batchSql( - "CREATE TABLE " + "INSERT INTO " + tableName - + " (id STRING, note STRING) WITH ('query-auth.enabled'='true', " - + (dataEvolution - ? "'bucket'='-1', 'data-evolution.enabled'='true'," - + " 'row-tracking.enabled'='true', 'deletion-vectors.enabled'='true'" - : "'primary-key'='id', 'bucket'='1'") - + ")"); + + " VALUES ('visible', 'original'), ('hidden', 'original')"); + Identifier identifier = Identifier.create(DATABASE_NAME, "t_merge"); + Table table = flinkCatalog().catalog().getTable(identifier); + long snapshotId = table.latestSnapshot().get().id(); + List rowFilter = equalTo(0, "id", DataTypes.STRING(), "visible"); + restCatalogServer.setRowFilterAuth(identifier, rowFilter); + assertThatThrownBy(mergeAction(dataEvolution, alias, singleParallelismEnv())::run) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("MERGE INTO requires full-table access"); + restCatalogServer.setRowFilterAuth(identifier, null); + + // The merge is built with full access, and a row filter is added before the job reads. + StreamExecutionEnvironment env = singleParallelismEnv(); + env.setRuntimeMode(RuntimeExecutionMode.BATCH); + ActionBase merge = mergeAction(dataEvolution, alias, env); + DataStream stream = + dataEvolution + ? ((DataEvolutionMergeIntoAction) merge).buildSource().f0 + : ((MergeIntoAction) merge).buildDataStream(); + restCatalogServer.setRowFilterAuth(identifier, rowFilter); + stream.sinkTo(new DiscardingSink<>()); + assertThatThrownBy(env::execute) + .hasStackTraceContaining("MERGE INTO requires full-table access"); + assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); + + restCatalogServer.setRowFilterAuth(identifier, null); + mergeAction(dataEvolution, alias, singleParallelismEnv()).run(); + assertThat(batchSql("SELECT note FROM " + tableName + " ORDER BY id")) + .extracting(row -> row.getField(0)) + .containsExactly("merged", "original"); + } + + @Test + public void testDataEvolutionMergeWithRowIdsChecksQueryAuthBeforeCommit() throws Exception { + String tableName = DATABASE_NAME + ".t_row_ids"; + createAuthTable("t_row_ids", "(id STRING, note STRING)", true, null); batchSql( "INSERT INTO " + tableName + " VALUES ('visible', 'original'), ('hidden', 'original')"); - Identifier identifier = Identifier.create(DATABASE_NAME, "t_actions"); - restCatalogServer.setRowFilterAuth( - identifier, - Collections.singletonList( - LeafPredicate.of( - new FieldTransform(new FieldRef(0, "id", DataTypes.STRING())), - Equal.INSTANCE, - Collections.singletonList(BinaryString.fromString("visible"))))); - restCatalogServer.setColumnMaskingAuth( - identifier, - Collections.singletonMap( - "id", - new ConcatTransform( - Collections.singletonList(BinaryString.fromString("hidden"))))); - assertThat(batchSql("SELECT * FROM " + tableName)) - .containsExactly(Row.of("hidden", "original")); + long rowId = + (Long) + batchSql( + "SELECT _ROW_ID FROM " + + DATABASE_NAME + + ".`t_row_ids$row_tracking` WHERE id = 'hidden'") + .get(0) + .getField(0); + Identifier identifier = Identifier.create(DATABASE_NAME, "t_row_ids"); + Table table = flinkCatalog().catalog().getTable(identifier); + long snapshotId = table.latestSnapshot().get().id(); - String sourceSql = - "CREATE TEMPORARY VIEW " - + DATABASE_NAME - + ".S AS SELECT 'hidden' AS id, 'merged' AS note"; - ActionBase merge = - dataEvolution - ? new DataEvolutionMergeIntoAction( - DATABASE_NAME, "t_actions", catalogOptions()) - .withTargetAlias("T") - .withSourceSqls(sourceSql) - .withSourceTable(DATABASE_NAME + ".S") - .withMergeCondition("T.id = S.id") - .withMatchedUpdateSet("note = S.note") - .withSinkParallelism(1) - : new MergeIntoAction(DATABASE_NAME, "t_actions", catalogOptions()) - .withTargetAlias("T") - .withSourceSqls(sourceSql) - .withSourceTable(DATABASE_NAME + ".S") - .withMergeCondition("T.id = S.id") - .withMatchedUpsert(null, "note = S.note"); - merge.withStreamExecutionEnvironment( - StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1)); + // The source gives the row IDs, so the merge does not read the target; the row filter is + // added after the merge checked, when it submits the job. + List rowFilter = equalTo(0, "id", DataTypes.STRING(), "visible"); + assertThatThrownBy(rowIdMergeAction(rowId, rowFilter)::run) + .hasStackTraceContaining("MERGE INTO requires full-table access"); + assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); + + restCatalogServer.setRowFilterAuth(identifier, null); + rowIdMergeAction(rowId, null).run(); + assertThat(batchSql("SELECT note FROM " + tableName + " ORDER BY id")) + .extracting(row -> row.getField(0)) + .containsExactly("merged", "original"); + } + + @ParameterizedTest + @CsvSource({"false,false", "false,true", "true,false", "true,true"}) + public void testDeleteActionChecksQueryAuthWhenTheJobReads( + boolean dataEvolution, boolean filterAll) throws Exception { + String tableName = DATABASE_NAME + ".t_delete"; + createAuthTable( + "t_delete", + "(id STRING, note STRING, p INT) PARTITIONED BY (p)", + dataEvolution, + "id,p"); + batchSql( + "INSERT INTO " + + tableName + + " VALUES ('visible', 'original', 1), ('hidden', 'original', 1)"); + Identifier identifier = Identifier.create(DATABASE_NAME, "t_delete"); Table table = flinkCatalog().catalog().getTable(identifier); - long snapshotIdBeforeMerge = table.latestSnapshot().get().id(); - assertThatThrownBy(merge::run) - .isInstanceOf(UnsupportedOperationException.class) - .hasMessageContaining("MERGE INTO requires full-table access"); - assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotIdBeforeMerge); - long snapshotIdBeforeDelete = table.latestSnapshot().get().id(); + long snapshotId = table.latestSnapshot().get().id(); + // A filter on another partition leaves no split to read. + List rowFilter = + filterAll + ? equalTo(2, "p", DataTypes.INT(), 2) + : equalTo(0, "id", DataTypes.STRING(), "visible"); + + restCatalogServer.setRowFilterAuth(identifier, rowFilter); assertThatThrownBy( - () -> - new DeleteAction( - DATABASE_NAME, - "t_actions", - "TRUE", - catalogOptions()) - .run()) + new DeleteAction(DATABASE_NAME, "t_delete", "TRUE", catalogOptions())::run) .isInstanceOf(UnsupportedOperationException.class) .hasMessageContaining("DELETE requires full-table access"); - assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotIdBeforeDelete); + restCatalogServer.setRowFilterAuth(identifier, null); + + // The row filter is added after the action checked, when it submits the job. + DeleteAction delete = + new DeleteAction(DATABASE_NAME, "t_delete", "TRUE", catalogOptions()) { + @Override + protected TableResult executeInternal( + List> transformations, + List sinkIdentifierNames) { + restCatalogServer.setRowFilterAuth(identifier, rowFilter); + return super.executeInternal(transformations, sinkIdentifierNames); + } + }; + delete.withStreamExecutionEnvironment(singleParallelismEnv()); + assertThatThrownBy(delete::run) + .hasStackTraceContaining("DELETE requires full-table access"); + assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); restCatalogServer.setRowFilterAuth(identifier, null); - restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); assertThat(batchSql("SELECT * FROM " + tableName)) .containsExactlyInAnyOrder( - Row.of("visible", "original"), Row.of("hidden", "original")); - merge.run(); - assertThat(batchSql("SELECT note FROM " + tableName + " ORDER BY id")) - .extracting(row -> row.getField(0)) - .containsExactly("merged", "original"); - new DeleteAction(DATABASE_NAME, "t_actions", "TRUE", catalogOptions()) - .withStreamExecutionEnvironment( - StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1)) + Row.of("visible", "original", 1), Row.of("hidden", "original", 1)); + new DeleteAction(DATABASE_NAME, "t_delete", "TRUE", catalogOptions()) + .withStreamExecutionEnvironment(singleParallelismEnv()) .run(); assertThat(batchSql("SELECT * FROM " + tableName)).isEmpty(); } + /** Creates a table with query auth, a Data Evolution table or one with the primary key. */ + private void createAuthTable( + String name, String schema, boolean dataEvolution, @Nullable String primaryKey) { + batchSql( + String.format( + "CREATE TABLE %s.%s %s WITH ('query-auth.enabled'='true', %s)", + DATABASE_NAME, + name, + schema, + dataEvolution + ? "'bucket'='-1', 'data-evolution.enabled'='true'," + + " 'row-tracking.enabled'='true', 'deletion-vectors.enabled'='true'" + : "'primary-key'='" + primaryKey + "', 'bucket'='1'")); + } + + private static List equalTo(int index, String field, DataType type, Object value) { + return Collections.singletonList( + LeafPredicate.of( + new FieldTransform(new FieldRef(index, field, type)), + Equal.INSTANCE, + Collections.singletonList( + value instanceof String + ? BinaryString.fromString((String) value) + : value))); + } + + private static Map mask(String column, String value) { + return Collections.singletonMap( + column, + new ConcatTransform(Collections.singletonList(BinaryString.fromString(value)))); + } + + private static StreamExecutionEnvironment singleParallelismEnv() { + return StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1); + } + + private DataEvolutionMergeIntoAction rowIdMergeAction( + long rowId, @Nullable List lateRowFilter) { + DataEvolutionMergeIntoAction merge = + new DataEvolutionMergeIntoAction(DATABASE_NAME, "t_row_ids", catalogOptions()) { + @Override + protected TableResult executeInternal( + List> transformations, + List sinkIdentifierNames) { + if (lateRowFilter != null) { + restCatalogServer.setRowFilterAuth( + Identifier.create(DATABASE_NAME, "t_row_ids"), lateRowFilter); + } + return super.executeInternal(transformations, sinkIdentifierNames); + } + }.withTargetAlias("T") + .withSourceSqls( + "CREATE TEMPORARY VIEW " + + DATABASE_NAME + + ".S AS SELECT CAST(" + + rowId + + " AS BIGINT) AS rid, 'merged' AS note") + .withSourceTable(DATABASE_NAME + ".S") + .withMergeCondition("T._ROW_ID = S.rid") + .withMatchedUpdateSet("note = S.note") + .withSinkParallelism(1); + merge.withStreamExecutionEnvironment(singleParallelismEnv()); + return merge; + } + + private ActionBase mergeAction( + boolean dataEvolution, boolean alias, StreamExecutionEnvironment env) { + String sourceSql = + "CREATE TEMPORARY VIEW " + + DATABASE_NAME + + ".S AS SELECT 'hidden' AS id, 'merged' AS note"; + String condition = (alias ? "T" : "t_merge") + ".id = S.id"; + ActionBase merge; + if (dataEvolution) { + DataEvolutionMergeIntoAction action = + new DataEvolutionMergeIntoAction(DATABASE_NAME, "t_merge", catalogOptions()) + .withSourceSqls(sourceSql) + .withSourceTable(DATABASE_NAME + ".S") + .withMergeCondition(condition) + .withMatchedUpdateSet("note = S.note") + .withSinkParallelism(1); + merge = alias ? action.withTargetAlias("T") : action; + } else { + MergeIntoAction action = + new MergeIntoAction(DATABASE_NAME, "t_merge", catalogOptions()) + .withSourceSqls(sourceSql) + .withSourceTable(DATABASE_NAME + ".S") + .withMergeCondition(condition) + .withMatchedUpsert(null, "note = S.note"); + merge = alias ? action.withTargetAlias("T") : action; + } + merge.withStreamExecutionEnvironment(env); + return merge; + } + @ParameterizedTest @CsvSource({ "false,false,false", @@ -448,18 +574,9 @@ public void testMaintenanceRewritesRequireFullTableAccess( + ")"); batchSql("INSERT INTO " + tableName + " VALUES (1, 's1'), (2, 's2')"); Identifier identifier = Identifier.create(DATABASE_NAME, "t_compact"); - Predicate rowFilter = - LeafPredicate.of( - new FieldTransform(new FieldRef(0, "id", DataTypes.INT())), - Equal.INSTANCE, - Collections.singletonList(filterAll ? 3 : 1)); - restCatalogServer.setRowFilterAuth(identifier, Collections.singletonList(rowFilter)); - restCatalogServer.setColumnMaskingAuth( - identifier, - Collections.singletonMap( - "ssn", - new ConcatTransform( - Collections.singletonList(BinaryString.fromString("****"))))); + List rowFilter = equalTo(0, "id", DataTypes.INT(), filterAll ? 3 : 1); + restCatalogServer.setRowFilterAuth(identifier, rowFilter); + restCatalogServer.setColumnMaskingAuth(identifier, mask("ssn", "****")); ActionBase action = sort ? new SortCompactAction( @@ -471,8 +588,7 @@ public void testMaintenanceRewritesRequireFullTableAccess( .withOrderColumns("id") : new RescaleAction(DATABASE_NAME, "t_compact", catalogOptions()) .withBucketNum(2); - StreamExecutionEnvironment env = - StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1); + StreamExecutionEnvironment env = singleParallelismEnv(); action.withStreamExecutionEnvironment(env); assertThatThrownBy(action::build) .isInstanceOf(UnsupportedOperationException.class) @@ -484,7 +600,7 @@ public void testMaintenanceRewritesRequireFullTableAccess( Table table = flinkCatalog().catalog().getTable(identifier); long snapshotId = table.latestSnapshot().get().id(); action.build(); - restCatalogServer.setRowFilterAuth(identifier, Collections.singletonList(rowFilter)); + restCatalogServer.setRowFilterAuth(identifier, rowFilter); assertThatThrownBy(env::execute) .hasStackTraceContaining( (sort ? "Sort compaction" : "Rescale") + " requires full-table access"); @@ -539,31 +655,28 @@ public void testChainCompactionRequiresFullTableAccess() throws Exception { .catalog() .getTable(new Identifier(DATABASE_NAME, "t_chain", "snapshot")); long snapshotId = table.latestSnapshot().get().id(); - StreamExecutionEnvironment env = - StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1); + StreamExecutionEnvironment env = singleParallelismEnv(); env.setRuntimeMode(RuntimeExecutionMode.BATCH); CompactChainTableAction action = new CompactChainTableAction( DATABASE_NAME, "t_chain", catalogOptions(), "dt=20261002", false); action.withStreamExecutionEnvironment(env); - Map masking = - Collections.singletonMap( - "note", - new ConcatTransform( - Collections.singletonList(BinaryString.fromString("****")))); + Map masking = mask("note", "****"); Identifier identifier = Identifier.create(DATABASE_NAME, "t_chain"); List chainIdentifiers = Arrays.asList( identifier, new Identifier(DATABASE_NAME, "t_chain", "snapshot"), new Identifier(DATABASE_NAME, "t_chain", "delta")); - chainIdentifiers.forEach(id -> restCatalogServer.setColumnMaskingAuth(id, masking)); - assertThatThrownBy(action::build) - .isInstanceOf(UnsupportedOperationException.class) - .hasMessageContaining("Chain table compaction requires full-table access"); - assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); - chainIdentifiers.forEach( - id -> restCatalogServer.setColumnMaskingAuth(id, Collections.emptyMap())); + // A rule on the table or on either branch alone is enough. + for (Identifier chainIdentifier : chainIdentifiers) { + restCatalogServer.setColumnMaskingAuth(chainIdentifier, masking); + assertThatThrownBy(action::build) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("Chain table compaction requires full-table access"); + assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); + restCatalogServer.setColumnMaskingAuth(chainIdentifier, Collections.emptyMap()); + } assertThatCode(action::run).doesNotThrowAnyException(); } diff --git a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala index 3dc06231a32b..b9fd3ceec7de 100644 --- a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala +++ b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala @@ -319,6 +319,12 @@ class Spark4Shim extends SparkShim { relation.copy(catalog = Some(catalog), identifier = Some(identifier)) } + override def copyDataSourceV2Relation( + relation: DataSourceV2Relation, + options: CaseInsensitiveStringMap): DataSourceV2Relation = { + relation.copy(options = options) + } + override def createDataSourceV2Relation( table: Table, catalog: Option[CatalogPlugin], diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala index 2358e02c6f19..40477f4742a0 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala @@ -19,6 +19,7 @@ package org.apache.paimon.spark import org.apache.paimon.{CoreOptions, Snapshot} +import org.apache.paimon.catalog.TableQueryAuthResult.{rejectRewriteUnderQueryAuth, rejectRewriteUnderQueryAuthRules} import org.apache.paimon.globalindex.{DataEvolutionBatchScan, GlobalIndexResult} import org.apache.paimon.partition.PartitionPredicate import org.apache.paimon.predicate.{Predicate, PredicateBuilder, VectorSearch} @@ -60,6 +61,12 @@ abstract class PaimonBaseScan(table: InnerTable) val plan = scan.plan() registerReadProtectionTagCleanup(scan.readProtectionTagName) + // A rewrite reading this scan, such as an insert-only merge, needs full access. + Option(table.options().get(CoreOptions.SCAN_REWRITE_OPERATION.key())).foreach { + operation => + rejectRewriteUnderQueryAuth(table, operation) + rejectRewriteUnderQueryAuthRules(plan.splits(), operation) + } plan.splits().asScala.toArray } diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonMergeInto.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonMergeInto.scala index cd159dce8dee..c6d1ebf407cd 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonMergeInto.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonMergeInto.scala @@ -28,6 +28,7 @@ import org.apache.spark.sql.SparkSession import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, Expression, SubqueryExpression} import org.apache.spark.sql.catalyst.plans.logical._ import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation import org.apache.spark.sql.paimon.shims.SparkShimLoader import scala.collection.JavaConverters._ @@ -79,9 +80,26 @@ case class PaimonMergeInto(spark: SparkSession) val aligned = alignAllMergeActions(resolvedMerge, targetOutput) if (!shouldFallbackToV1MergeInto(aligned)) { + // Spark appends an insert-only merge without a row-level operation, which checks query + // auth, so the scan of the target checks instead. + val marked = + if ( + aligned.matchedActions.isEmpty && + SparkShimLoader.shim.notMatchedBySourceActions(aligned).isEmpty + ) { + val target = aligned.targetTable.transform { + case r: DataSourceV2Relation if r.table.isInstanceOf[SparkTable] => + PaimonRelation.withRewriteOperation(r, "MERGE") + } + aligned + .withNewChildren(Seq(target, aligned.sourceTable)) + .asInstanceOf[MergeIntoTable] + } else { + aligned + } // Tag so the analyzer's idempotence re-run skips this node (V1 fallback is a different // node type and doesn't need the tag). - PaimonMergeActionTags.markAligned(aligned) + PaimonMergeActionTags.markAligned(marked) } else { buildV1Command(v2Table, resolvedMerge, aligned) } diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonRelation.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonRelation.scala index 0f3bae2638f4..e5c8343c1572 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonRelation.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonRelation.scala @@ -18,12 +18,17 @@ package org.apache.paimon.spark.catalyst.analysis +import org.apache.paimon.CoreOptions import org.apache.paimon.spark.SparkTable import org.apache.spark.internal.Logging import org.apache.spark.sql.catalyst.analysis.{EliminateSubqueryAliases, ResolvedTable} import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, Project} import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation +import org.apache.spark.sql.paimon.shims.SparkShimLoader +import org.apache.spark.sql.util.CaseInsensitiveStringMap + +import java.util.{HashMap => JHashMap} import scala.util.control.NonFatal @@ -55,4 +60,19 @@ object PaimonRelation extends Logging { case _ => throw new RuntimeException(s"It's not a paimon table, $plan") } } + + /** Reads the relation for a rewrite, so the scan checks query auth when it plans splits. */ + def withRewriteOperation( + relation: DataSourceV2Relation, + operation: String): DataSourceV2Relation = { + val options = new JHashMap[String, String](relation.options.asCaseSensitiveMap()) + options.put(CoreOptions.SCAN_REWRITE_OPERATION.key(), operation) + SparkShimLoader.shim.copyDataSourceV2Relation(relation, new CaseInsensitiveStringMap(options)) + } + + def withoutRewriteOperation(relation: DataSourceV2Relation): DataSourceV2Relation = { + val options = new JHashMap[String, String](relation.options.asCaseSensitiveMap()) + options.remove(CoreOptions.SCAN_REWRITE_OPERATION.key()) + SparkShimLoader.shim.copyDataSourceV2Relation(relation, new CaseInsensitiveStringMap(options)) + } } diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/optimizer/UnmarkRewriteWriteTarget.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/optimizer/UnmarkRewriteWriteTarget.scala new file mode 100644 index 000000000000..7aab05e9e85d --- /dev/null +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/optimizer/UnmarkRewriteWriteTarget.scala @@ -0,0 +1,46 @@ +/* + * 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.paimon.spark.catalyst.optimizer + +import org.apache.paimon.CoreOptions +import org.apache.paimon.spark.catalyst.analysis.PaimonRelation + +import org.apache.spark.sql.catalyst.plans.logical.{AppendData, LogicalPlan} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation + +/** + * Spark appends an insert-only merge to the relation it also reads, which `PaimonMergeInto` marks + * for the query auth check of the scan. Only the read needs it, and the write target keeps its own + * options, so the cache refresh after the write still matches cached reads of the table. + */ +object UnmarkRewriteWriteTarget extends Rule[LogicalPlan] { + + override def apply(plan: LogicalPlan): LogicalPlan = { + plan.transformDown { + case a: AppendData => + a.table match { + case r: DataSourceV2Relation + if r.options.containsKey(CoreOptions.SCAN_REWRITE_OPERATION.key()) => + a.withNewTable(PaimonRelation.withoutRewriteOperation(r)) + case _ => a + } + } + } +} diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala index fe9715cde223..e55f56645314 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala @@ -19,7 +19,7 @@ package org.apache.paimon.spark.extensions import org.apache.paimon.spark.catalyst.analysis.{PaimonAnalysis, PaimonDeleteTable, PaimonFunctionResolver, PaimonIncompatibleResolutionRules, PaimonMergeInto, PaimonPostHocResolutionRules, PaimonProcedureResolver, PaimonUpdateTable, PaimonViewResolver, ReplacePaimonFunctions} -import org.apache.paimon.spark.catalyst.optimizer.{MergePaimonScalarSubqueries, OptimizeMetadataOnlyDeleteFromPaimonTable, PushDownArrayPredicates, PushDownLateralVectorSearchFilter, RepartitionLargeBlobScan, RepartitionLateralVectorSearchInput} +import org.apache.paimon.spark.catalyst.optimizer.{MergePaimonScalarSubqueries, OptimizeMetadataOnlyDeleteFromPaimonTable, PushDownArrayPredicates, PushDownLateralVectorSearchFilter, RepartitionLargeBlobScan, RepartitionLateralVectorSearchInput, UnmarkRewriteWriteTarget} import org.apache.paimon.spark.catalyst.plans.logical.PaimonTableValuedFunctions import org.apache.paimon.spark.commands.BucketExpression import org.apache.paimon.spark.execution.{OldCompatibleStrategy, PaimonStrategy} @@ -113,6 +113,7 @@ class PaimonSparkSessionExtensions extends (SparkSessionExtensions => Unit) { extensions.injectOptimizerRule(spark => ReplacePaimonFunctions(spark)) extensions.injectOptimizerRule(spark => OptimizeMetadataOnlyDeleteFromPaimonTable(spark)) extensions.injectOptimizerRule(_ => MergePaimonScalarSubqueries) + extensions.injectOptimizerRule(_ => UnmarkRewriteWriteTarget) // Spark 3.2 uses the V1 filter translation path, which cannot translate the // comparison-shaped array predicate bridge used by this rule. if (org.apache.spark.SPARK_VERSION >= "3.3") { diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/SparkShim.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/SparkShim.scala index e40706affa9c..5c56a158434a 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/SparkShim.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/SparkShim.scala @@ -219,6 +219,10 @@ trait SparkShim { catalog: CatalogPlugin, identifier: Identifier): DataSourceV2Relation + def copyDataSourceV2Relation( + relation: DataSourceV2Relation, + options: CaseInsensitiveStringMap): DataSourceV2Relation + // Per-version shim: Spark 4.1 added a 5th `timeTravelSpec` parameter with a default. A 4-arg call // site compiled against 4.1 emits a `create$default$5()` lookup absent on 4.0. def createDataSourceV2Relation( diff --git a/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java b/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java index aa11d609eca9..bebc13282f32 100644 --- a/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java +++ b/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java @@ -57,6 +57,8 @@ import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.connector.catalog.CatalogManager; +import org.apache.spark.sql.execution.CommandExecutionMode; +import org.apache.spark.sql.execution.QueryExecution; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -64,6 +66,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.io.File; import java.io.IOException; @@ -275,29 +278,32 @@ public void testRowLevelOperationsRequireFullTableAccess(boolean useV2Write, Str + ")"); spark.sql("INSERT INTO t_rewrite VALUES (1, 's1', 'n1', 1), (2, 's2', 'n2', 1)"); Identifier identifier = Identifier.create("db2", "t_rewrite"); - Predicate rowFilter = - LeafPredicate.of( - new FieldTransform(new FieldRef(0, "id", DataTypes.INT())), - Equal.INSTANCE, - Collections.singletonList(1)); - Transform mask = - new ConcatTransform(Collections.singletonList(BinaryString.fromString("****"))); String merge = "MERGE INTO t_rewrite t USING (SELECT 2 AS id) s ON t.id = s.id" + " WHEN MATCHED THEN UPDATE SET note = t.ssn"; + // Spark plans insert-only merges as appends over an anti join. + String insertMerge = + "MERGE INTO t_rewrite t USING (SELECT 2 AS id, 'x' AS ssn, 'y' AS note, 1 AS p) s" + + " ON t.id = s.id WHEN NOT MATCHED THEN INSERT *"; + String insertsMerge = + "MERGE INTO t_rewrite t USING (SELECT 2 AS id, 'x' AS ssn, 'y' AS note, 1 AS p) s" + + " ON t.id = s.id WHEN NOT MATCHED AND s.id = 1 THEN INSERT *" + + " WHEN NOT MATCHED THEN INSERT *"; String[][] statements = { {"UPDATE", "UPDATE t_rewrite SET note = ssn"}, {"DELETE", "DELETE FROM t_rewrite WHERE id = 2"}, {"DELETE", "DELETE FROM t_rewrite WHERE p = 1"}, {"DELETE", "DELETE FROM t_rewrite"}, - {"MERGE", merge} + {"MERGE", merge}, + {"MERGE", insertMerge}, + {"MERGE", insertsMerge}, + {"TRUNCATE", "TRUNCATE TABLE t_rewrite"}, + {"TRUNCATE", "TRUNCATE TABLE t_rewrite PARTITION (p = 1)"} }; for (boolean masking : new boolean[] {false, true}) { - restCatalogServer.setRowFilterAuth( - identifier, masking ? null : Collections.singletonList(rowFilter)); + restCatalogServer.setRowFilterAuth(identifier, masking ? null : idEquals(1)); restCatalogServer.setColumnMaskingAuth( - identifier, - masking ? Collections.singletonMap("ssn", mask) : Collections.emptyMap()); + identifier, masking ? mask("ssn") : Collections.emptyMap()); for (String[] statement : statements) { assertThatThrownBy(() -> spark.sql(statement[1]).collectAsList()) .hasStackTraceContaining("UnsupportedOperationException") @@ -319,38 +325,70 @@ public void testRowLevelOperationsRequireFullTableAccess(boolean useV2Write, Str .isEqualTo("[[1]]"); spark.sql("DELETE FROM t_rewrite"); assertThat(spark.sql("SELECT * FROM t_rewrite").collectAsList()).isEmpty(); + spark.sql(insertMerge); + spark.sql(insertsMerge); + assertThat(spark.sql("SELECT * FROM t_rewrite").collectAsList().toString()) + .isEqualTo("[[2,x,y,1]]"); + spark.sql("TRUNCATE TABLE t_rewrite PARTITION (p = 1)"); + spark.sql("TRUNCATE TABLE t_rewrite"); + assertThat(spark.sql("SELECT * FROM t_rewrite").collectAsList()).isEmpty(); } - @Test - public void testTruncateRequiresFullTableAccess() { + @ParameterizedTest + @ValueSource(strings = {"'bucket'='-1'", "'bucket'='-1', 'deletion-vectors.enabled'='true'"}) + public void testInsertOnlyMergeChecksQueryAuthWhenItReads(String options) throws Exception { + spark.conf().set("spark.paimon.write.use-v2-write", true); spark.sql( - "CREATE TABLE t_truncate (id INT, value STRING, p INT) PARTITIONED BY (p)" - + " TBLPROPERTIES ('query-auth.enabled'='true')"); - spark.sql("INSERT INTO t_truncate VALUES (1, 'one', 1), (2, 'two', 1), (3, 'three', 2)"); - Identifier identifier = Identifier.create("db2", "t_truncate"); - restCatalogServer.setRowFilterAuth( - identifier, - Collections.singletonList( - LeafPredicate.of( - new FieldTransform(new FieldRef(0, "id", DataTypes.INT())), - Equal.INSTANCE, - Collections.singletonList(1)))); - assertThatThrownBy(() -> spark.sql("TRUNCATE TABLE t_truncate").collectAsList()) - .hasStackTraceContaining("TRUNCATE requires full-table access"); - assertThatThrownBy( - () -> - spark.sql("TRUNCATE TABLE t_truncate PARTITION (p = 1)") - .collectAsList()) - .hasStackTraceContaining("TRUNCATE requires full-table access"); - assertThat(spark.sql("SELECT * FROM t_truncate").collectAsList().toString()) - .isEqualTo("[[1,one,1]]"); + "CREATE TABLE t_insert_merge (id INT, note STRING)" + + " TBLPROPERTIES ('query-auth.enabled'='true', " + + options + + ")"); + spark.sql("INSERT INTO t_insert_merge VALUES (1, 'n1'), (2, 'n2')"); + Identifier identifier = Identifier.create("db2", "t_insert_merge"); + String merge = + "MERGE INTO t_insert_merge t USING (SELECT %d AS id, 'x' AS note) s ON t.id = s.id"; + for (String actions : + new String[] { + " WHEN NOT MATCHED THEN INSERT *", + " WHEN NOT MATCHED AND s.id = 0 THEN INSERT * WHEN NOT MATCHED THEN INSERT *" + }) { + // The merge is analyzed with full access, and a row filter is added before it reads. + QueryExecution execution = + spark.sessionState() + .executePlan( + spark.sessionState() + .sqlParser() + .parsePlan(String.format(merge, 2) + actions), + CommandExecutionMode.SKIP()); + execution.assertAnalyzed(); + restCatalogServer.setRowFilterAuth(identifier, idEquals(1)); + assertThatThrownBy(() -> execution.executedPlan().executeCollect()) + .hasStackTraceContaining("MERGE requires full-table access"); + restCatalogServer.setRowFilterAuth(identifier, null); + } + assertThat(spark.sql("SELECT * FROM t_insert_merge ORDER BY id").collectAsList().toString()) + .isEqualTo("[[1,n1], [2,n2]]"); + + // The merge refreshes a cached read of the table. + spark.sql("CACHE TABLE t_insert_merge"); + spark.sql(String.format(merge, 3) + " WHEN NOT MATCHED THEN INSERT *"); + assertThat(spark.sql("SELECT * FROM t_insert_merge ORDER BY id").collectAsList().toString()) + .isEqualTo("[[1,n1], [2,n2], [3,x]]"); + spark.sql("UNCACHE TABLE t_insert_merge"); + } - restCatalogServer.setRowFilterAuth(identifier, null); - spark.sql("TRUNCATE TABLE t_truncate PARTITION (p = 1)"); - assertThat(spark.sql("SELECT * FROM t_truncate").collectAsList().toString()) - .isEqualTo("[[3,three,2]]"); - spark.sql("TRUNCATE TABLE t_truncate"); - assertThat(spark.sql("SELECT * FROM t_truncate").collectAsList()).isEmpty(); + private static List idEquals(int id) { + return Collections.singletonList( + LeafPredicate.of( + new FieldTransform(new FieldRef(0, "id", DataTypes.INT())), + Equal.INSTANCE, + Collections.singletonList(id))); + } + + private static Map mask(String column) { + return Collections.singletonMap( + column, + new ConcatTransform(Collections.singletonList(BinaryString.fromString("****")))); } private static Stream rowLevelTableOptions() { @@ -389,18 +427,19 @@ public void testChainCompactionRequiresFullTableAccess() throws Exception { long snapshotId = table.latestSnapshot().get().id(); String compact = "CALL sys.compact_chain_table(table => 'db2.t_chain', partition => 'dt=\"20261002\"')"; - Identifier identifier = Identifier.create("db2", "t_chain"); - restCatalogServer.setColumnMaskingAuth( - identifier, - Collections.singletonMap( - "note", - new ConcatTransform( - Collections.singletonList(BinaryString.fromString("****"))))); - assertThatThrownBy(() -> spark.sql(compact).collectAsList()) - .isInstanceOf(UnsupportedOperationException.class) - .hasMessageContaining("Chain table compaction requires full-table access"); - assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); - restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); + // A rule on the table or on either branch alone is enough. + for (Identifier identifier : + Arrays.asList( + Identifier.create("db2", "t_chain"), + new Identifier("db2", "t_chain", "snapshot"), + new Identifier("db2", "t_chain", "delta"))) { + restCatalogServer.setColumnMaskingAuth(identifier, mask("note")); + assertThatThrownBy(() -> spark.sql(compact).collectAsList()) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("Chain table compaction requires full-table access"); + assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); + restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); + } assertThatCode(() -> spark.sql(compact).collectAsList()).doesNotThrowAnyException(); } diff --git a/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark3Shim.scala b/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark3Shim.scala index 2910babef0e9..95c8cdb24f27 100644 --- a/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark3Shim.scala +++ b/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark3Shim.scala @@ -289,6 +289,12 @@ class Spark3Shim extends SparkShim { relation.copy(catalog = Some(catalog), identifier = Some(identifier)) } + override def copyDataSourceV2Relation( + relation: DataSourceV2Relation, + options: CaseInsensitiveStringMap): DataSourceV2Relation = { + relation.copy(options = options) + } + override def createDataSourceV2Relation( table: Table, catalog: Option[CatalogPlugin], diff --git a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/catalyst/analysis/Spark41MergeIntoRewrite.scala b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/catalyst/analysis/Spark41MergeIntoRewrite.scala index 0d012e18f249..8a9c20651c70 100644 --- a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/catalyst/analysis/Spark41MergeIntoRewrite.scala +++ b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/catalyst/analysis/Spark41MergeIntoRewrite.scala @@ -140,6 +140,11 @@ object Spark41MergeIntoRewrite } } + // The insert-only plans append without a row-level operation, so their scan of the target + // checks query auth. + private def rewriteRead(r: DataSourceV2Relation): DataSourceV2Relation = + PaimonRelation.withRewriteOperation(r, "MERGE") + // Fast-path #1: single NOT MATCHED InsertAction. Append over a left-anti join. private def buildSingleInsertAppendPlan( r: DataSourceV2Relation, @@ -151,7 +156,7 @@ object Spark41MergeIntoRewrite case Some(insertCond) => Filter(insertCond, source) case None => source } - val joinPlan = Join(filteredSource, r, LeftAnti, Some(cond), JoinHint.NONE) + val joinPlan = Join(filteredSource, rewriteRead(r), LeftAnti, Some(cond), JoinHint.NONE) val output = insertAction.assignments.map(_.value) val outputColNames = r.output.map(_.name) val projectList = output.zip(outputColNames).map { case (expr, name) => Alias(expr, name)() } @@ -165,7 +170,7 @@ object Spark41MergeIntoRewrite source: LogicalPlan, cond: Expression, notMatchedActions: Seq[MergeAction]): LogicalPlan = { - val joinPlan = Join(source, r, LeftAnti, Some(cond), JoinHint.NONE) + val joinPlan = Join(source, rewriteRead(r), LeftAnti, Some(cond), JoinHint.NONE) val notMatchedInstructions = notMatchedActions.map { case InsertAction(cond, assignments) => Keep(Insert, cond.getOrElse(TrueLiteral), assignments.map(_.value)) diff --git a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala index dd5336c36b6a..c245ba67b81a 100644 --- a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala +++ b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala @@ -341,6 +341,12 @@ class Spark4Shim extends SparkShim { relation.copy(catalog = Some(catalog), identifier = Some(identifier)) } + override def copyDataSourceV2Relation( + relation: DataSourceV2Relation, + options: CaseInsensitiveStringMap): DataSourceV2Relation = { + relation.copy(options = options) + } + override def createDataSourceV2Relation( table: Table, catalog: Option[CatalogPlugin], From ba1fc177fd546663371b8cded84dbce3c03097e1 Mon Sep 17 00:00:00 2001 From: Li Jiajia Date: Mon, 23 Nov 2026 02:45:28 -0800 Subject: [PATCH 03/10] [core][spark][flink] Check query auth only when a rewrite is planned Drop the second check when the job reads the target. It only covered a rule added between planning and reading, which the Spark V2 row-level operations and the Flink row-level sink never covered either, and it needed an internal scan.rewrite-operation option carried through the Spark relation, the Flink SQL hints and every Flink source, plus an optimizer rule and a new shim method to keep the option off the relation Spark writes to. Spark insert-only merges are now refused in PaimonMergeInto and Spark41MergeIntoRewrite, like the other row-level operations, and the Flink actions keep their check when they are built. Co-Authored-By: Claude Opus 5.5 --- .../java/org/apache/paimon/CoreOptions.java | 9 - .../paimon/catalog/TableQueryAuthResult.java | 7 - .../flink/action/CompactChainTableAction.java | 1 - .../flink/action/DataEvolutionDelete.java | 6 +- .../action/DataEvolutionMergeIntoAction.java | 4 +- .../paimon/flink/action/DeleteAction.java | 4 +- .../paimon/flink/action/MergeIntoAction.java | 31 +-- .../paimon/flink/action/RescaleAction.java | 1 - .../flink/action/SortCompactAction.java | 1 - .../dataevolution/MergeIntoUpdateChecker.java | 4 - .../flink/source/BaseDataTableSource.java | 2 - .../flink/source/FlinkSourceBuilder.java | 33 ++- .../source/PostponeMergeInputSource.java | 15 +- .../flink/source/PostponeMergeOnRead.java | 11 +- .../flink/source/StaticFileStoreSource.java | 21 +- .../flink/source/SystemTableSource.java | 6 +- .../flink/source/operator/MonitorSource.java | 17 +- .../paimon/flink/RESTCatalogITCase.java | 197 +++--------------- .../spark/sql/paimon/shims/Spark4Shim.scala | 6 - .../apache/paimon/spark/PaimonBaseScan.scala | 7 - .../catalyst/analysis/PaimonMergeInto.scala | 27 +-- .../catalyst/analysis/PaimonRelation.scala | 20 -- .../optimizer/UnmarkRewriteWriteTarget.scala | 46 ---- .../PaimonSparkSessionExtensions.scala | 3 +- .../spark/sql/paimon/shims/SparkShim.scala | 4 - .../spark/SparkCatalogWithRestTest.java | 46 ---- .../spark/sql/paimon/shims/Spark3Shim.scala | 6 - .../analysis/Spark41MergeIntoRewrite.scala | 17 +- .../spark/sql/paimon/shims/Spark4Shim.scala | 6 - 29 files changed, 78 insertions(+), 480 deletions(-) delete mode 100644 paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/optimizer/UnmarkRewriteWriteTarget.scala diff --git a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java index 4d2616a68b1e..aa511a20e1b9 100644 --- a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java +++ b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java @@ -2481,15 +2481,6 @@ 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 SCAN_REWRITE_OPERATION = - key("scan.rewrite-operation") - .stringType() - .noDefaultValue() - .withDescription( - "The rewrite reading this table, which fails when the read is under " - + "row filters or column masks."); - @ExcludeFromDocumentation("Only used internally to support materialized table") public static final ConfigOption MATERIALIZED_TABLE_DEFINITION_QUERY = key("materialized-table.definition-query") diff --git a/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java b/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java index 65aa433332a5..b5ff20ec74b4 100644 --- a/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java +++ b/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java @@ -38,7 +38,6 @@ import org.apache.paimon.table.source.QueryAuthSplit; import org.apache.paimon.table.source.SnapshotNotExistPlan; import org.apache.paimon.table.source.Split; -import org.apache.paimon.table.source.Splits; import org.apache.paimon.table.source.TableScan; import org.apache.paimon.table.system.RowTrackingTable; import org.apache.paimon.types.DataField; @@ -181,12 +180,6 @@ public static void rejectRewriteUnderQueryAuth(@Nullable Table table, String ope } } - public static void rejectRewriteUnderQueryAuthRules(List splits, String operation) { - for (Split split : splits) { - rejectRewriteUnderQueryAuthRules(Splits.authResult(split), operation); - } - } - private static void rejectRewriteUnderQueryAuthRules( @Nullable TableQueryAuthResult authResult, String operation) { if (authResult != null && authResult.hasRules()) { diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/CompactChainTableAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/CompactChainTableAction.java index 4e084d33d9cc..402737327d49 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/CompactChainTableAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/CompactChainTableAction.java @@ -135,7 +135,6 @@ public void build() throws Exception { } DataStream source = new FlinkSourceBuilder(chainTable) - .withRewriteOperation("Chain table compaction") .env(env) .sourceBounded(true) .partitionPredicate(predicate) diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java index f4cce057d7fe..0f0433733309 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java @@ -39,8 +39,6 @@ import java.io.Serializable; import java.util.Collections; -import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; - /** Internal implementation which logically deletes rows from a Data Evolution append table. */ class DataEvolutionDelete implements Serializable { @@ -93,14 +91,12 @@ TableResult runInternal() { String query = String.format( "SELECT `_ROW_ID` FROM `%s`.`%s`.`%s$row_tracking` " - + "/*+ OPTIONS('scan.snapshot-id'='%d', '%s'='full', '%s'='DELETE') */" - + " WHERE %s", + + "/*+ OPTIONS('scan.snapshot-id'='%d', '%s'='full') */ WHERE %s", action.catalogName, action.identifier.getDatabaseName(), action.identifier.getObjectName(), baseSnapshotId, CoreOptions.SCALAR_INDEX_SEARCH_MODE.key(), - SCAN_REWRITE_OPERATION.key(), filter); LOG.info("Data-evolution delete source query: {}", query); diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java index 8a484e97ee0a..1c6eb9242eca 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java @@ -87,7 +87,6 @@ import java.util.function.Function; import java.util.stream.Collectors; -import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; import static org.apache.paimon.format.blob.BlobFileFormat.isBlobFile; import static org.apache.paimon.utils.ParameterUtils.parseCommaSeparatedKeyValues; @@ -308,13 +307,12 @@ public Tuple2, RowType> buildSource() { query = String.format( "SELECT %s, %s FROM %s INNER JOIN %s " - + "/*+ OPTIONS('%s'='full', '%s'='MERGE INTO') */ AS RT ON %s", + + "/*+ OPTIONS('%s'='full') */ AS RT ON %s", "`RT`.`_ROW_ID` as `_ROW_ID`", String.join(",", project), escapedSourceName(), escapedRowTrackingTargetName(), CoreOptions.SCALAR_INDEX_SEARCH_MODE.key(), - SCAN_REWRITE_OPERATION.key(), rewriteMergeCondition(mergeCondition)); } diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java index 5327928f6f5a..895ff53eb4d1 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java @@ -39,7 +39,6 @@ import java.util.stream.Collectors; import static org.apache.paimon.CoreOptions.MergeEngine.DEDUPLICATE; -import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; /** Delete from table action for Flink, dispatching by table type. */ @@ -119,11 +118,10 @@ private void runPrimaryKeyDelete() throws Exception { Table queriedTable = batchTEnv.sqlQuery( String.format( - "SELECT * FROM `%s`.`%s`.`%s` /*+ OPTIONS('%s'='DELETE') */ WHERE %s", + "SELECT * FROM `%s`.`%s`.`%s` WHERE %s", catalogName, identifier.getDatabaseName(), identifier.getObjectName(), - SCAN_REWRITE_OPERATION.key(), filter)); List> converters = diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java index d56923c73784..4fa7d61a0e8c 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java @@ -48,7 +48,6 @@ import static org.apache.paimon.CoreOptions.MergeEngine.DEDUPLICATE; import static org.apache.paimon.CoreOptions.MergeEngine.PARTIAL_UPDATE; -import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; import static org.apache.paimon.utils.ParameterUtils.parseCommaSeparatedKeyValues; @@ -82,10 +81,6 @@ public class MergeIntoAction extends TableActionBase { public static final String IDENTIFIER_QUOTE = "`"; - // checks query auth again when the job reads the target - private static final String TARGET_SCAN_HINT = - String.format("/*+ OPTIONS('%s'='MERGE INTO') */", SCAN_REWRITE_OPERATION.key()); - // primary keys of target table private final List primaryKeys; @@ -287,14 +282,7 @@ private void handleTargetAlias() { // create a view 'targetAlias' in the path of target table, then we can find it with the // qualified name batchTEnv.createTemporaryView( - escapedTargetName(), - batchTEnv.sqlQuery( - String.format( - "SELECT * FROM `%s`.`%s`.`%s` %s", - catalogName, - identifier.getDatabaseName(), - identifier.getObjectName(), - TARGET_SCAN_HINT))); + escapedTargetName(), batchTEnv.from(identifier.getFullName())); } } @@ -351,7 +339,7 @@ private Optional> getMatchedUpsertDataStream() { String.format( "SELECT %s FROM %s INNER JOIN %s ON %s %s", String.join(",", normalizeFieldName(project)), - targetScan(), + escapedTargetName(), escapedSourceName(), mergeCondition, matchedUpsertCondition == null ? "" : "WHERE " + matchedUpsertCondition); @@ -395,7 +383,7 @@ private Optional> getNotMatchedUpsertDataStream() { String.format( "SELECT %s FROM %s WHERE NOT EXISTS (SELECT * FROM %s WHERE %s) %s", String.join(",", normalizeFieldName(project)), - targetScan(), + escapedTargetName(), escapedSourceName(), mergeCondition, notMatchedBySourceUpsertCondition == null @@ -426,7 +414,7 @@ private Optional> getMatchedDeleteDataStream() { String.format( "SELECT %s FROM %s INNER JOIN %s ON %s %s", String.join(",", normalizeFieldName(project)), - targetScan(), + escapedTargetName(), escapedSourceName(), mergeCondition, matchedDeleteCondition == null ? "" : "WHERE " + matchedDeleteCondition); @@ -448,7 +436,7 @@ private Optional> getNotMatchedDeleteDataStream() { String.format( "SELECT %s FROM %s WHERE NOT EXISTS (SELECT * FROM %s WHERE %s) %s", String.join(",", normalizeFieldName(targetFieldNames)), - targetScan(), + escapedTargetName(), escapedSourceName(), mergeCondition, notMatchedBySourceDeleteCondition == null @@ -473,7 +461,7 @@ private Optional> getInsertDataStream() { "SELECT %s FROM %s WHERE NOT EXISTS (SELECT * FROM %s WHERE %s) %s", notMatchedInsertValues, escapedSourceName(), - targetScan(), + escapedTargetName(), mergeCondition, notMatchedInsertCondition == null ? "" @@ -531,13 +519,6 @@ private String escapedTargetName() { "`%s`.`%s`.`%s`", catalogName, identifier.getDatabaseName(), targetTableName()); } - // the alias view reads the target with the hint already - private String targetScan() { - return targetAlias == null - ? escapedTargetName() + " " + TARGET_SCAN_HINT - : escapedTargetName(); - } - private String escapedSourceName() { return Arrays.stream(sourceTable.split("\\.")) .map(s -> String.format("`%s`", s)) diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java index 6509e56d1b54..b1c5f567554b 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java @@ -105,7 +105,6 @@ public void build() throws Exception { DataStream source = new FlinkSourceBuilder(fileStoreTable) - .withRewriteOperation("Rescale") .env(env) .sourceBounded(true) .sourceParallelism( diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java index 457f4e10ca18..c9e71fe24b1f 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java @@ -94,7 +94,6 @@ public void build() throws Exception { Map tableConfig = fileStoreTable.options(); FlinkSourceBuilder sourceBuilder = new FlinkSourceBuilder(fileStoreTable) - .withRewriteOperation("Sort compaction") .sourceName( ObjectIdentifier.of( catalogName, diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/dataevolution/MergeIntoUpdateChecker.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/dataevolution/MergeIntoUpdateChecker.java index e9f9c06433aa..39518e6147f8 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/dataevolution/MergeIntoUpdateChecker.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/dataevolution/MergeIntoUpdateChecker.java @@ -46,8 +46,6 @@ import java.util.Set; import java.util.stream.Collectors; -import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; - /** * The checker for merge into update result. It will check each committable to see if some * global-indexed columns are updated. It will take some actions according to {@link @@ -88,8 +86,6 @@ public void processElement(StreamRecord element) throws Exception { @Override public void endInput() throws Exception { - // Authorize again before the commit, as a source with _ROW_ID does not read the target. - rejectRewriteUnderQueryAuth(table, "MERGE INTO"); checkUpdatedColumns(); } diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/BaseDataTableSource.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/BaseDataTableSource.java index 1eb6faa08355..9bdbf0e7dc72 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/BaseDataTableSource.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/BaseDataTableSource.java @@ -74,7 +74,6 @@ import static org.apache.flink.util.Preconditions.checkArgument; import static org.apache.paimon.CoreOptions.CHANGELOG_PRODUCER; import static org.apache.paimon.CoreOptions.MergeEngine.FIRST_ROW; -import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.flink.FlinkConnectorOptions.LOOKUP_ASYNC; import static org.apache.paimon.flink.FlinkConnectorOptions.LOOKUP_ASYNC_THREAD_NUMBER; import static org.apache.paimon.flink.FlinkConnectorOptions.SCAN_PARALLELISM; @@ -209,7 +208,6 @@ public ScanRuntimeProvider getScanRuntimeProvider(ScanContext scanContext) { .limit(limit) .watermarkStrategy(watermarkStrategy) .dynamicPartitionFilteringFields(dynamicPartitionFilteringFields()); - options.getOptional(SCAN_REWRITE_OPERATION).ifPresent(sourceBuilder::withRewriteOperation); return new PaimonDataStreamScanProvider( !unbounded, env -> diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/FlinkSourceBuilder.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/FlinkSourceBuilder.java index e75ca9ed5288..4857d40c13a0 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/FlinkSourceBuilder.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/FlinkSourceBuilder.java @@ -98,7 +98,6 @@ public class FlinkSourceBuilder { @Nullable private WatermarkStrategy watermarkStrategy; @Nullable private DynamicPartitionFilteringInfo dynamicPartitionFilteringInfo; private boolean skipPreloadTargetSnapshot; - @Nullable private String rewriteOperation; public FlinkSourceBuilder(Table table) { this.table = table; @@ -201,11 +200,6 @@ public FlinkSourceBuilder withSkipPreloadTargetSnapshot(boolean skip) { return this; } - public FlinkSourceBuilder withRewriteOperation(String operation) { - this.rewriteOperation = operation; - return this; - } - private ReadBuilder createReadBuilder(@Nullable org.apache.paimon.types.RowType readType) { ReadBuilder readBuilder = table.newReadBuilder(); if (readType != null) { @@ -244,17 +238,16 @@ private ReadBuilder createReadBuilder(@Nullable org.apache.paimon.types.RowType } Options options = Options.fromMap(table.options()); return new StaticFileStoreSource( - createReadBuilder(projectedRowType()), - limit, - options.get(FlinkConnectorOptions.SCAN_SPLIT_ENUMERATOR_BATCH_SIZE), - options.get(FlinkConnectorOptions.SCAN_SPLIT_ENUMERATOR_ASSIGN_MODE), - dynamicPartitionFilteringInfo, - outerProject(), - SplitWeightUtils.splitWeightFunc(options), - null, - options.get(CoreOptions.BLOB_AS_DESCRIPTOR), - skipPreloadTargetSnapshot) - .withRewriteOperation(rewriteOperation, table); + createReadBuilder(projectedRowType()), + limit, + options.get(FlinkConnectorOptions.SCAN_SPLIT_ENUMERATOR_BATCH_SIZE), + options.get(FlinkConnectorOptions.SCAN_SPLIT_ENUMERATOR_ASSIGN_MODE), + dynamicPartitionFilteringInfo, + outerProject(), + SplitWeightUtils.splitWeightFunc(options), + null, + options.get(CoreOptions.BLOB_AS_DESCRIPTOR), + skipPreloadTargetSnapshot); } TableScanUtils.streamingReadingValidate(table); @@ -323,8 +316,7 @@ private void checkConsumerId() { produceTypeInfo(), outerProject(), limit, - conf.get(CoreOptions.BLOB_AS_DESCRIPTOR), - rewriteOperation); + conf.get(CoreOptions.BLOB_AS_DESCRIPTOR)); } private int basePostponeMergeParallelism() { @@ -588,8 +580,7 @@ private DataStream buildDedicatedSplitGenSource(boolean isBounded) { limit, table, readBuilder.readType(), - conf.get(CoreOptions.BLOB_AS_DESCRIPTOR), - rewriteOperation); + conf.get(CoreOptions.BLOB_AS_DESCRIPTOR)); if (parallelism != null) { dataStream.getTransformation().setParallelism(parallelism); } diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeInputSource.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeInputSource.java index 70fa63fa52dd..092af1677827 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeInputSource.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeInputSource.java @@ -20,7 +20,6 @@ import org.apache.paimon.data.BinaryRow; import org.apache.paimon.io.DataFileMeta; -import org.apache.paimon.table.Table; import org.apache.paimon.table.source.DataSplit; import org.apache.paimon.table.source.DeletionFile; import org.apache.paimon.table.source.PostponeMergePlan; @@ -33,29 +32,20 @@ import org.apache.flink.api.connector.source.SourceReaderContext; import org.apache.flink.core.io.InputStatus; -import javax.annotation.Nullable; - import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; - /** Emits real-bucket markers and writer-grouped postpone splits for merge-on-read. */ final class PostponeMergeInputSource extends AbstractNonCoordinatedSource { private static final long serialVersionUID = 1L; private final List inputs; - private final Table table; - @Nullable private final String rewriteOperation; - PostponeMergeInputSource( - PostponeMergePlan plan, Table table, @Nullable String rewriteOperation) { - this.table = table; - this.rewriteOperation = rewriteOperation; + PostponeMergeInputSource(PostponeMergePlan plan) { this.inputs = new ArrayList<>(); Map, List> realBuckets = new LinkedHashMap<>(); @@ -79,9 +69,6 @@ public Boundedness getBoundedness() { @Override public SourceReader createReader(SourceReaderContext readerContext) { - if (rewriteOperation != null) { - rejectRewriteUnderQueryAuth(table, rewriteOperation); - } return new Reader(); } diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeOnRead.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeOnRead.java index f3545495c3c9..b0054e066db5 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeOnRead.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/PostponeMergeOnRead.java @@ -45,8 +45,6 @@ import javax.annotation.Nullable; -import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; - /** Builds the Flink batch topology for postpone merge-on-read. */ final class PostponeMergeOnRead { @@ -101,13 +99,8 @@ static DataStream build( TypeInformation outputType, @Nullable NestedProjectedRowData outerProject, @Nullable Long limit, - boolean blobAsDescriptor, - @Nullable String rewriteOperation) { - if (rewriteOperation != null) { - rejectRewriteUnderQueryAuth(table, rewriteOperation); - } - PostponeMergeInputSource inputSource = - new PostponeMergeInputSource(plan, table, rewriteOperation); + boolean blobAsDescriptor) { + PostponeMergeInputSource inputSource = new PostponeMergeInputSource(plan); DataStream inputs = env.fromSource( new PaimonDataStreamSource<>(inputSource, table), diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/StaticFileStoreSource.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/StaticFileStoreSource.java index a7a21057f210..04facbd49e29 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/StaticFileStoreSource.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/StaticFileStoreSource.java @@ -24,7 +24,6 @@ import org.apache.paimon.flink.source.assigners.PreAssignSplitAssigner; import org.apache.paimon.flink.source.assigners.SplitAssigner; import org.apache.paimon.table.ChainGroupReadTable; -import org.apache.paimon.table.Table; import org.apache.paimon.table.source.InnerTableScan; import org.apache.paimon.table.source.ReadBuilder; import org.apache.paimon.table.source.TableScan; @@ -39,8 +38,6 @@ import java.util.Collection; import java.util.List; -import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; -import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuthRules; import static org.apache.paimon.flink.FlinkConnectorOptions.SplitAssignMode; /** Bounded {@link FlinkSource} for reading records. It does not monitor new snapshots. */ @@ -60,9 +57,6 @@ public class StaticFileStoreSource extends FlinkSource { private final boolean skipPreloadTargetSnapshot; - @Nullable private String rewriteOperation; - @Nullable private Table rewriteTable; - public StaticFileStoreSource( ReadBuilder readBuilder, @Nullable Long limit, @@ -150,19 +144,10 @@ public Boundedness getBoundedness() { return Boundedness.BOUNDED; } - public StaticFileStoreSource withRewriteOperation(@Nullable String operation, Table table) { - this.rewriteOperation = operation; - this.rewriteTable = table; - return this; - } - @Override public SplitEnumerator restoreEnumerator( SplitEnumeratorContext context, PendingSplitsCheckpoint checkpoint) { - if (rewriteOperation != null) { - rejectRewriteUnderQueryAuth(rewriteTable, rewriteOperation); - } Collection splits = checkpoint == null ? getSplits(context) : checkpoint.splits(); SplitAssigner splitAssigner = @@ -188,11 +173,7 @@ private List getSplits(SplitEnumeratorContext context) { ((InnerTableScan) scan) .withMetricRegistry(new FlinkMetricRegistry(context.metricGroup())); } - TableScan.Plan plan = scan.plan(); - if (rewriteOperation != null) { - rejectRewriteUnderQueryAuthRules(plan.splits(), rewriteOperation); - } - return splitGenerator.createSplits(plan); + return splitGenerator.createSplits(scan.plan()); } public static SplitAssigner createSplitAssigner( diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/SystemTableSource.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/SystemTableSource.java index 323c5e0fbfdc..d4fbd333a2b1 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/SystemTableSource.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/SystemTableSource.java @@ -40,7 +40,6 @@ import javax.annotation.Nullable; -import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.flink.FlinkConnectorOptions.SCAN_PARALLELISM; /** A {@link FlinkTableSource} for system table. */ @@ -138,7 +137,7 @@ public ScanRuntimeProvider getScanRuntimeProvider(ScanContext scanContext) { new ContinuousFileStoreSource( readBuilder, table.options(), limit, isUnordered(table), rowData); } else { - StaticFileStoreSource staticSource = + source = new StaticFileStoreSource( readBuilder, limit, @@ -153,9 +152,6 @@ public ScanRuntimeProvider getScanRuntimeProvider(ScanContext scanContext) { .getOrDefault( CoreOptions.BLOB_AS_DESCRIPTOR.key(), "false")), false); - source = - staticSource.withRewriteOperation( - table.options().get(SCAN_REWRITE_OPERATION.key()), table); } return new PaimonDataStreamScanProvider( source.getBoundedness() == Boundedness.BOUNDED, diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java index 28d8a85fb0a9..1b1ad2392fe1 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/source/operator/MonitorSource.java @@ -69,9 +69,6 @@ import java.util.TreeMap; import java.util.concurrent.CompletableFuture; -import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; -import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuthRules; - /** * This is the single (non-parallel) monitoring task, it is responsible for: * @@ -106,8 +103,6 @@ public class MonitorSource extends AbstractNonCoordinatedSource { private final boolean emitSnapshotWatermark; private final boolean isBounded; private final int maxSnapshotCount; - @Nullable private String rewriteOperation; - @Nullable private Table rewriteTable; public MonitorSource( ReadBuilder readBuilder, @@ -242,10 +237,6 @@ public InputStatus pollNext(ReaderOutput readerOutput) throws Exception { boolean isEmpty; try { List splits = isBounded ? batchScan.plan().splits() : scan.plan().splits(); - if (rewriteOperation != null) { - rejectRewriteUnderQueryAuth(rewriteTable, rewriteOperation); - rejectRewriteUnderQueryAuthRules(splits, rewriteOperation); - } isEmpty = splits.isEmpty(); splits.forEach(readerOutput::collect); if (!isBounded && maxSnapshotCount > 0 && !isEmpty) { @@ -348,8 +339,7 @@ public static DataStream buildSource( limit, table, readBuilder.readType(), - false, - null); + false); } public static DataStream buildSource( @@ -366,8 +356,7 @@ public static DataStream buildSource( @Nullable Long limit, @Nullable Table table, RowType readType, - boolean blobAsDescriptor, - @Nullable String rewriteOperation) { + boolean blobAsDescriptor) { int maxSnapshotCount = table == null ? -1 @@ -386,8 +375,6 @@ public static DataStream buildSource( emitSnapshotWatermark, isBounded, maxSnapshotCount); - monitorSource.rewriteOperation = rewriteOperation; - monitorSource.rewriteTable = table; Source source = monitorSource; if (table != null) { source = new PaimonDataStreamSource<>(monitorSource, table); diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java index afa1853d4606..9b7f1868c629 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java @@ -54,23 +54,19 @@ import org.apache.paimon.shade.guava30.com.google.common.collect.ImmutableMap; import org.apache.flink.api.common.RuntimeExecutionMode; -import org.apache.flink.api.dag.Transformation; -import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; -import org.apache.flink.streaming.api.functions.sink.v2.DiscardingSink; -import org.apache.flink.table.api.TableResult; import org.apache.flink.table.catalog.Catalog; import org.apache.flink.table.catalog.CatalogFunction; import org.apache.flink.table.catalog.CatalogFunctionImpl; import org.apache.flink.table.catalog.FunctionLanguage; import org.apache.flink.table.catalog.ObjectPath; -import org.apache.flink.table.data.RowData; import org.apache.flink.table.resource.ResourceType; import org.apache.flink.table.resource.ResourceUri; import org.apache.flink.types.Row; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; import javax.annotation.Nullable; @@ -324,9 +320,8 @@ public void testRowLevelOperationsRequireFullTableAccess( } @ParameterizedTest - @CsvSource({"false,false", "false,true", "true,false", "true,true"}) - public void testMergeIntoChecksQueryAuthWhenTheJobReads(boolean dataEvolution, boolean alias) - throws Exception { + @ValueSource(booleans = {false, true}) + public void testMergeIntoActionRequiresFullTableAccess(boolean dataEvolution) throws Exception { String tableName = DATABASE_NAME + ".t_merge"; createAuthTable("t_merge", "(id STRING, note STRING)", dataEvolution, "id"); batchSql( @@ -334,65 +329,14 @@ public void testMergeIntoChecksQueryAuthWhenTheJobReads(boolean dataEvolution, b + tableName + " VALUES ('visible', 'original'), ('hidden', 'original')"); Identifier identifier = Identifier.create(DATABASE_NAME, "t_merge"); - Table table = flinkCatalog().catalog().getTable(identifier); - long snapshotId = table.latestSnapshot().get().id(); - List rowFilter = equalTo(0, "id", DataTypes.STRING(), "visible"); - restCatalogServer.setRowFilterAuth(identifier, rowFilter); - assertThatThrownBy(mergeAction(dataEvolution, alias, singleParallelismEnv())::run) + restCatalogServer.setRowFilterAuth( + identifier, equalTo(0, "id", DataTypes.STRING(), "visible")); + assertThatThrownBy(mergeAction(dataEvolution)::run) .isInstanceOf(UnsupportedOperationException.class) .hasMessageContaining("MERGE INTO requires full-table access"); - restCatalogServer.setRowFilterAuth(identifier, null); - - // The merge is built with full access, and a row filter is added before the job reads. - StreamExecutionEnvironment env = singleParallelismEnv(); - env.setRuntimeMode(RuntimeExecutionMode.BATCH); - ActionBase merge = mergeAction(dataEvolution, alias, env); - DataStream stream = - dataEvolution - ? ((DataEvolutionMergeIntoAction) merge).buildSource().f0 - : ((MergeIntoAction) merge).buildDataStream(); - restCatalogServer.setRowFilterAuth(identifier, rowFilter); - stream.sinkTo(new DiscardingSink<>()); - assertThatThrownBy(env::execute) - .hasStackTraceContaining("MERGE INTO requires full-table access"); - assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); - - restCatalogServer.setRowFilterAuth(identifier, null); - mergeAction(dataEvolution, alias, singleParallelismEnv()).run(); - assertThat(batchSql("SELECT note FROM " + tableName + " ORDER BY id")) - .extracting(row -> row.getField(0)) - .containsExactly("merged", "original"); - } - - @Test - public void testDataEvolutionMergeWithRowIdsChecksQueryAuthBeforeCommit() throws Exception { - String tableName = DATABASE_NAME + ".t_row_ids"; - createAuthTable("t_row_ids", "(id STRING, note STRING)", true, null); - batchSql( - "INSERT INTO " - + tableName - + " VALUES ('visible', 'original'), ('hidden', 'original')"); - long rowId = - (Long) - batchSql( - "SELECT _ROW_ID FROM " - + DATABASE_NAME - + ".`t_row_ids$row_tracking` WHERE id = 'hidden'") - .get(0) - .getField(0); - Identifier identifier = Identifier.create(DATABASE_NAME, "t_row_ids"); - Table table = flinkCatalog().catalog().getTable(identifier); - long snapshotId = table.latestSnapshot().get().id(); - - // The source gives the row IDs, so the merge does not read the target; the row filter is - // added after the merge checked, when it submits the job. - List rowFilter = equalTo(0, "id", DataTypes.STRING(), "visible"); - assertThatThrownBy(rowIdMergeAction(rowId, rowFilter)::run) - .hasStackTraceContaining("MERGE INTO requires full-table access"); - assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); restCatalogServer.setRowFilterAuth(identifier, null); - rowIdMergeAction(rowId, null).run(); + mergeAction(dataEvolution).run(); assertThat(batchSql("SELECT note FROM " + tableName + " ORDER BY id")) .extracting(row -> row.getField(0)) .containsExactly("merged", "original"); @@ -400,8 +344,8 @@ public void testDataEvolutionMergeWithRowIdsChecksQueryAuthBeforeCommit() throws @ParameterizedTest @CsvSource({"false,false", "false,true", "true,false", "true,true"}) - public void testDeleteActionChecksQueryAuthWhenTheJobReads( - boolean dataEvolution, boolean filterAll) throws Exception { + public void testDeleteActionRequiresFullTableAccess(boolean dataEvolution, boolean filterAll) + throws Exception { String tableName = DATABASE_NAME + ".t_delete"; createAuthTable( "t_delete", @@ -413,8 +357,6 @@ public void testDeleteActionChecksQueryAuthWhenTheJobReads( + tableName + " VALUES ('visible', 'original', 1), ('hidden', 'original', 1)"); Identifier identifier = Identifier.create(DATABASE_NAME, "t_delete"); - Table table = flinkCatalog().catalog().getTable(identifier); - long snapshotId = table.latestSnapshot().get().id(); // A filter on another partition leaves no split to read. List rowFilter = filterAll @@ -427,24 +369,6 @@ public void testDeleteActionChecksQueryAuthWhenTheJobReads( .isInstanceOf(UnsupportedOperationException.class) .hasMessageContaining("DELETE requires full-table access"); restCatalogServer.setRowFilterAuth(identifier, null); - - // The row filter is added after the action checked, when it submits the job. - DeleteAction delete = - new DeleteAction(DATABASE_NAME, "t_delete", "TRUE", catalogOptions()) { - @Override - protected TableResult executeInternal( - List> transformations, - List sinkIdentifierNames) { - restCatalogServer.setRowFilterAuth(identifier, rowFilter); - return super.executeInternal(transformations, sinkIdentifierNames); - } - }; - delete.withStreamExecutionEnvironment(singleParallelismEnv()); - assertThatThrownBy(delete::run) - .hasStackTraceContaining("DELETE requires full-table access"); - assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); - - restCatalogServer.setRowFilterAuth(identifier, null); assertThat(batchSql("SELECT * FROM " + tableName)) .containsExactlyInAnyOrder( Row.of("visible", "original", 1), Row.of("hidden", "original", 1)); @@ -490,92 +414,43 @@ private static StreamExecutionEnvironment singleParallelismEnv() { return StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1); } - private DataEvolutionMergeIntoAction rowIdMergeAction( - long rowId, @Nullable List lateRowFilter) { - DataEvolutionMergeIntoAction merge = - new DataEvolutionMergeIntoAction(DATABASE_NAME, "t_row_ids", catalogOptions()) { - @Override - protected TableResult executeInternal( - List> transformations, - List sinkIdentifierNames) { - if (lateRowFilter != null) { - restCatalogServer.setRowFilterAuth( - Identifier.create(DATABASE_NAME, "t_row_ids"), lateRowFilter); - } - return super.executeInternal(transformations, sinkIdentifierNames); - } - }.withTargetAlias("T") - .withSourceSqls( - "CREATE TEMPORARY VIEW " - + DATABASE_NAME - + ".S AS SELECT CAST(" - + rowId - + " AS BIGINT) AS rid, 'merged' AS note") - .withSourceTable(DATABASE_NAME + ".S") - .withMergeCondition("T._ROW_ID = S.rid") - .withMatchedUpdateSet("note = S.note") - .withSinkParallelism(1); - merge.withStreamExecutionEnvironment(singleParallelismEnv()); - return merge; - } - - private ActionBase mergeAction( - boolean dataEvolution, boolean alias, StreamExecutionEnvironment env) { + private ActionBase mergeAction(boolean dataEvolution) { String sourceSql = "CREATE TEMPORARY VIEW " + DATABASE_NAME + ".S AS SELECT 'hidden' AS id, 'merged' AS note"; - String condition = (alias ? "T" : "t_merge") + ".id = S.id"; - ActionBase merge; - if (dataEvolution) { - DataEvolutionMergeIntoAction action = - new DataEvolutionMergeIntoAction(DATABASE_NAME, "t_merge", catalogOptions()) - .withSourceSqls(sourceSql) - .withSourceTable(DATABASE_NAME + ".S") - .withMergeCondition(condition) - .withMatchedUpdateSet("note = S.note") - .withSinkParallelism(1); - merge = alias ? action.withTargetAlias("T") : action; - } else { - MergeIntoAction action = - new MergeIntoAction(DATABASE_NAME, "t_merge", catalogOptions()) - .withSourceSqls(sourceSql) - .withSourceTable(DATABASE_NAME + ".S") - .withMergeCondition(condition) - .withMatchedUpsert(null, "note = S.note"); - merge = alias ? action.withTargetAlias("T") : action; - } - merge.withStreamExecutionEnvironment(env); + String condition = "t_merge.id = S.id"; + ActionBase merge = + dataEvolution + ? new DataEvolutionMergeIntoAction( + DATABASE_NAME, "t_merge", catalogOptions()) + .withSourceSqls(sourceSql) + .withSourceTable(DATABASE_NAME + ".S") + .withMergeCondition(condition) + .withMatchedUpdateSet("note = S.note") + .withSinkParallelism(1) + : new MergeIntoAction(DATABASE_NAME, "t_merge", catalogOptions()) + .withSourceSqls(sourceSql) + .withSourceTable(DATABASE_NAME + ".S") + .withMergeCondition(condition) + .withMatchedUpsert(null, "note = S.note"); + merge.withStreamExecutionEnvironment(singleParallelismEnv()); return merge; } @ParameterizedTest - @CsvSource({ - "false,false,false", - "false,true,false", - "true,false,false", - "true,true,false", - "false,false,true", - "false,true,true", - "true,false,true", - "true,true,true" - }) - public void testMaintenanceRewritesRequireFullTableAccess( - boolean sort, boolean dedicatedSplits, boolean filterAll) throws Exception { + @ValueSource(booleans = {false, true}) + public void testMaintenanceRewritesRequireFullTableAccess(boolean sort) throws Exception { String tableName = DATABASE_NAME + ".t_compact"; batchSql( "CREATE TABLE " + tableName + " (id INT, ssn STRING) WITH ('query-auth.enabled'='true', " - + "'scan.dedicated-split-generation'='" - + dedicatedSplits - + "', " + (sort ? "'bucket'='-1'" : "'primary-key'='id', 'bucket'='1'") + ")"); batchSql("INSERT INTO " + tableName + " VALUES (1, 's1'), (2, 's2')"); Identifier identifier = Identifier.create(DATABASE_NAME, "t_compact"); - List rowFilter = equalTo(0, "id", DataTypes.INT(), filterAll ? 3 : 1); - restCatalogServer.setRowFilterAuth(identifier, rowFilter); + restCatalogServer.setRowFilterAuth(identifier, equalTo(0, "id", DataTypes.INT(), 1)); restCatalogServer.setColumnMaskingAuth(identifier, mask("ssn", "****")); ActionBase action = sort @@ -588,8 +463,7 @@ public void testMaintenanceRewritesRequireFullTableAccess( .withOrderColumns("id") : new RescaleAction(DATABASE_NAME, "t_compact", catalogOptions()) .withBucketNum(2); - StreamExecutionEnvironment env = singleParallelismEnv(); - action.withStreamExecutionEnvironment(env); + action.withStreamExecutionEnvironment(singleParallelismEnv()); assertThatThrownBy(action::build) .isInstanceOf(UnsupportedOperationException.class) .hasMessageContaining( @@ -597,17 +471,6 @@ public void testMaintenanceRewritesRequireFullTableAccess( restCatalogServer.setRowFilterAuth(identifier, null); restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); - Table table = flinkCatalog().catalog().getTable(identifier); - long snapshotId = table.latestSnapshot().get().id(); - action.build(); - restCatalogServer.setRowFilterAuth(identifier, rowFilter); - assertThatThrownBy(env::execute) - .hasStackTraceContaining( - (sort ? "Sort compaction" : "Rescale") + " requires full-table access"); - assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); - restCatalogServer.setRowFilterAuth(identifier, null); - assertThat(batchSql("SELECT * FROM " + tableName)) - .containsExactlyInAnyOrder(Row.of(1, "s1"), Row.of(2, "s2")); action.run(); assertThat(batchSql("SELECT * FROM " + tableName)) .containsExactlyInAnyOrder(Row.of(1, "s1"), Row.of(2, "s2")); diff --git a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala index b9fd3ceec7de..3dc06231a32b 100644 --- a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala +++ b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala @@ -319,12 +319,6 @@ class Spark4Shim extends SparkShim { relation.copy(catalog = Some(catalog), identifier = Some(identifier)) } - override def copyDataSourceV2Relation( - relation: DataSourceV2Relation, - options: CaseInsensitiveStringMap): DataSourceV2Relation = { - relation.copy(options = options) - } - override def createDataSourceV2Relation( table: Table, catalog: Option[CatalogPlugin], diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala index 40477f4742a0..2358e02c6f19 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonBaseScan.scala @@ -19,7 +19,6 @@ package org.apache.paimon.spark import org.apache.paimon.{CoreOptions, Snapshot} -import org.apache.paimon.catalog.TableQueryAuthResult.{rejectRewriteUnderQueryAuth, rejectRewriteUnderQueryAuthRules} import org.apache.paimon.globalindex.{DataEvolutionBatchScan, GlobalIndexResult} import org.apache.paimon.partition.PartitionPredicate import org.apache.paimon.predicate.{Predicate, PredicateBuilder, VectorSearch} @@ -61,12 +60,6 @@ abstract class PaimonBaseScan(table: InnerTable) val plan = scan.plan() registerReadProtectionTagCleanup(scan.readProtectionTagName) - // A rewrite reading this scan, such as an insert-only merge, needs full access. - Option(table.options().get(CoreOptions.SCAN_REWRITE_OPERATION.key())).foreach { - operation => - rejectRewriteUnderQueryAuth(table, operation) - rejectRewriteUnderQueryAuthRules(plan.splits(), operation) - } plan.splits().asScala.toArray } diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonMergeInto.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonMergeInto.scala index c6d1ebf407cd..e1138cfdcf44 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonMergeInto.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonMergeInto.scala @@ -18,6 +18,7 @@ package org.apache.paimon.spark.catalyst.analysis +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth import org.apache.paimon.spark.SparkTable import org.apache.paimon.spark.catalyst.analysis.expressions.ExpressionHelper import org.apache.paimon.spark.commands.{MergeIntoPaimonDataEvolutionTable, MergeIntoPaimonTable} @@ -28,7 +29,6 @@ import org.apache.spark.sql.SparkSession import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, Expression, SubqueryExpression} import org.apache.spark.sql.catalyst.plans.logical._ import org.apache.spark.sql.catalyst.rules.Rule -import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation import org.apache.spark.sql.paimon.shims.SparkShimLoader import scala.collection.JavaConverters._ @@ -81,25 +81,16 @@ case class PaimonMergeInto(spark: SparkSession) if (!shouldFallbackToV1MergeInto(aligned)) { // Spark appends an insert-only merge without a row-level operation, which checks query - // auth, so the scan of the target checks instead. - val marked = - if ( - aligned.matchedActions.isEmpty && - SparkShimLoader.shim.notMatchedBySourceActions(aligned).isEmpty - ) { - val target = aligned.targetTable.transform { - case r: DataSourceV2Relation if r.table.isInstanceOf[SparkTable] => - PaimonRelation.withRewriteOperation(r, "MERGE") - } - aligned - .withNewChildren(Seq(target, aligned.sourceTable)) - .asInstanceOf[MergeIntoTable] - } else { - aligned - } + // auth, so check it here. + if ( + aligned.matchedActions.isEmpty && + SparkShimLoader.shim.notMatchedBySourceActions(aligned).isEmpty + ) { + rejectRewriteUnderQueryAuth(v2Table.getTable, "MERGE") + } // Tag so the analyzer's idempotence re-run skips this node (V1 fallback is a different // node type and doesn't need the tag). - PaimonMergeActionTags.markAligned(marked) + PaimonMergeActionTags.markAligned(aligned) } else { buildV1Command(v2Table, resolvedMerge, aligned) } diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonRelation.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonRelation.scala index e5c8343c1572..0f3bae2638f4 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonRelation.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonRelation.scala @@ -18,17 +18,12 @@ package org.apache.paimon.spark.catalyst.analysis -import org.apache.paimon.CoreOptions import org.apache.paimon.spark.SparkTable import org.apache.spark.internal.Logging import org.apache.spark.sql.catalyst.analysis.{EliminateSubqueryAliases, ResolvedTable} import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, Project} import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation -import org.apache.spark.sql.paimon.shims.SparkShimLoader -import org.apache.spark.sql.util.CaseInsensitiveStringMap - -import java.util.{HashMap => JHashMap} import scala.util.control.NonFatal @@ -60,19 +55,4 @@ object PaimonRelation extends Logging { case _ => throw new RuntimeException(s"It's not a paimon table, $plan") } } - - /** Reads the relation for a rewrite, so the scan checks query auth when it plans splits. */ - def withRewriteOperation( - relation: DataSourceV2Relation, - operation: String): DataSourceV2Relation = { - val options = new JHashMap[String, String](relation.options.asCaseSensitiveMap()) - options.put(CoreOptions.SCAN_REWRITE_OPERATION.key(), operation) - SparkShimLoader.shim.copyDataSourceV2Relation(relation, new CaseInsensitiveStringMap(options)) - } - - def withoutRewriteOperation(relation: DataSourceV2Relation): DataSourceV2Relation = { - val options = new JHashMap[String, String](relation.options.asCaseSensitiveMap()) - options.remove(CoreOptions.SCAN_REWRITE_OPERATION.key()) - SparkShimLoader.shim.copyDataSourceV2Relation(relation, new CaseInsensitiveStringMap(options)) - } } diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/optimizer/UnmarkRewriteWriteTarget.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/optimizer/UnmarkRewriteWriteTarget.scala deleted file mode 100644 index 7aab05e9e85d..000000000000 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/optimizer/UnmarkRewriteWriteTarget.scala +++ /dev/null @@ -1,46 +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.paimon.spark.catalyst.optimizer - -import org.apache.paimon.CoreOptions -import org.apache.paimon.spark.catalyst.analysis.PaimonRelation - -import org.apache.spark.sql.catalyst.plans.logical.{AppendData, LogicalPlan} -import org.apache.spark.sql.catalyst.rules.Rule -import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation - -/** - * Spark appends an insert-only merge to the relation it also reads, which `PaimonMergeInto` marks - * for the query auth check of the scan. Only the read needs it, and the write target keeps its own - * options, so the cache refresh after the write still matches cached reads of the table. - */ -object UnmarkRewriteWriteTarget extends Rule[LogicalPlan] { - - override def apply(plan: LogicalPlan): LogicalPlan = { - plan.transformDown { - case a: AppendData => - a.table match { - case r: DataSourceV2Relation - if r.options.containsKey(CoreOptions.SCAN_REWRITE_OPERATION.key()) => - a.withNewTable(PaimonRelation.withoutRewriteOperation(r)) - case _ => a - } - } - } -} diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala index e55f56645314..fe9715cde223 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala @@ -19,7 +19,7 @@ package org.apache.paimon.spark.extensions import org.apache.paimon.spark.catalyst.analysis.{PaimonAnalysis, PaimonDeleteTable, PaimonFunctionResolver, PaimonIncompatibleResolutionRules, PaimonMergeInto, PaimonPostHocResolutionRules, PaimonProcedureResolver, PaimonUpdateTable, PaimonViewResolver, ReplacePaimonFunctions} -import org.apache.paimon.spark.catalyst.optimizer.{MergePaimonScalarSubqueries, OptimizeMetadataOnlyDeleteFromPaimonTable, PushDownArrayPredicates, PushDownLateralVectorSearchFilter, RepartitionLargeBlobScan, RepartitionLateralVectorSearchInput, UnmarkRewriteWriteTarget} +import org.apache.paimon.spark.catalyst.optimizer.{MergePaimonScalarSubqueries, OptimizeMetadataOnlyDeleteFromPaimonTable, PushDownArrayPredicates, PushDownLateralVectorSearchFilter, RepartitionLargeBlobScan, RepartitionLateralVectorSearchInput} import org.apache.paimon.spark.catalyst.plans.logical.PaimonTableValuedFunctions import org.apache.paimon.spark.commands.BucketExpression import org.apache.paimon.spark.execution.{OldCompatibleStrategy, PaimonStrategy} @@ -113,7 +113,6 @@ class PaimonSparkSessionExtensions extends (SparkSessionExtensions => Unit) { extensions.injectOptimizerRule(spark => ReplacePaimonFunctions(spark)) extensions.injectOptimizerRule(spark => OptimizeMetadataOnlyDeleteFromPaimonTable(spark)) extensions.injectOptimizerRule(_ => MergePaimonScalarSubqueries) - extensions.injectOptimizerRule(_ => UnmarkRewriteWriteTarget) // Spark 3.2 uses the V1 filter translation path, which cannot translate the // comparison-shaped array predicate bridge used by this rule. if (org.apache.spark.SPARK_VERSION >= "3.3") { diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/SparkShim.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/SparkShim.scala index 5c56a158434a..e40706affa9c 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/SparkShim.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/SparkShim.scala @@ -219,10 +219,6 @@ trait SparkShim { catalog: CatalogPlugin, identifier: Identifier): DataSourceV2Relation - def copyDataSourceV2Relation( - relation: DataSourceV2Relation, - options: CaseInsensitiveStringMap): DataSourceV2Relation - // Per-version shim: Spark 4.1 added a 5th `timeTravelSpec` parameter with a default. A 4-arg call // site compiled against 4.1 emits a `create$default$5()` lookup absent on 4.0. def createDataSourceV2Relation( diff --git a/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java b/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java index bebc13282f32..e3b57930a6f3 100644 --- a/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java +++ b/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java @@ -57,8 +57,6 @@ import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.connector.catalog.CatalogManager; -import org.apache.spark.sql.execution.CommandExecutionMode; -import org.apache.spark.sql.execution.QueryExecution; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -66,7 +64,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import org.junit.jupiter.params.provider.ValueSource; import java.io.File; import java.io.IOException; @@ -334,49 +331,6 @@ public void testRowLevelOperationsRequireFullTableAccess(boolean useV2Write, Str assertThat(spark.sql("SELECT * FROM t_rewrite").collectAsList()).isEmpty(); } - @ParameterizedTest - @ValueSource(strings = {"'bucket'='-1'", "'bucket'='-1', 'deletion-vectors.enabled'='true'"}) - public void testInsertOnlyMergeChecksQueryAuthWhenItReads(String options) throws Exception { - spark.conf().set("spark.paimon.write.use-v2-write", true); - spark.sql( - "CREATE TABLE t_insert_merge (id INT, note STRING)" - + " TBLPROPERTIES ('query-auth.enabled'='true', " - + options - + ")"); - spark.sql("INSERT INTO t_insert_merge VALUES (1, 'n1'), (2, 'n2')"); - Identifier identifier = Identifier.create("db2", "t_insert_merge"); - String merge = - "MERGE INTO t_insert_merge t USING (SELECT %d AS id, 'x' AS note) s ON t.id = s.id"; - for (String actions : - new String[] { - " WHEN NOT MATCHED THEN INSERT *", - " WHEN NOT MATCHED AND s.id = 0 THEN INSERT * WHEN NOT MATCHED THEN INSERT *" - }) { - // The merge is analyzed with full access, and a row filter is added before it reads. - QueryExecution execution = - spark.sessionState() - .executePlan( - spark.sessionState() - .sqlParser() - .parsePlan(String.format(merge, 2) + actions), - CommandExecutionMode.SKIP()); - execution.assertAnalyzed(); - restCatalogServer.setRowFilterAuth(identifier, idEquals(1)); - assertThatThrownBy(() -> execution.executedPlan().executeCollect()) - .hasStackTraceContaining("MERGE requires full-table access"); - restCatalogServer.setRowFilterAuth(identifier, null); - } - assertThat(spark.sql("SELECT * FROM t_insert_merge ORDER BY id").collectAsList().toString()) - .isEqualTo("[[1,n1], [2,n2]]"); - - // The merge refreshes a cached read of the table. - spark.sql("CACHE TABLE t_insert_merge"); - spark.sql(String.format(merge, 3) + " WHEN NOT MATCHED THEN INSERT *"); - assertThat(spark.sql("SELECT * FROM t_insert_merge ORDER BY id").collectAsList().toString()) - .isEqualTo("[[1,n1], [2,n2], [3,x]]"); - spark.sql("UNCACHE TABLE t_insert_merge"); - } - private static List idEquals(int id) { return Collections.singletonList( LeafPredicate.of( diff --git a/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark3Shim.scala b/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark3Shim.scala index 95c8cdb24f27..2910babef0e9 100644 --- a/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark3Shim.scala +++ b/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark3Shim.scala @@ -289,12 +289,6 @@ class Spark3Shim extends SparkShim { relation.copy(catalog = Some(catalog), identifier = Some(identifier)) } - override def copyDataSourceV2Relation( - relation: DataSourceV2Relation, - options: CaseInsensitiveStringMap): DataSourceV2Relation = { - relation.copy(options = options) - } - override def createDataSourceV2Relation( table: Table, catalog: Option[CatalogPlugin], diff --git a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/catalyst/analysis/Spark41MergeIntoRewrite.scala b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/catalyst/analysis/Spark41MergeIntoRewrite.scala index 8a9c20651c70..6e5efdecb0eb 100644 --- a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/catalyst/analysis/Spark41MergeIntoRewrite.scala +++ b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/catalyst/analysis/Spark41MergeIntoRewrite.scala @@ -18,6 +18,7 @@ package org.apache.spark.sql.catalyst.analysis +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth import org.apache.paimon.spark.SparkTable import org.apache.paimon.spark.catalyst.analysis.{MergeSchemaEvolutionHelper, PaimonRelation} @@ -105,6 +106,13 @@ object Spark41MergeIntoRewrite case r @ ExtractV2Table(tbl: SupportsRowLevelOperations) => validateMergeIntoConditions(m) val relation = r.asInstanceOf[DataSourceV2Relation] + if (matchedActions.isEmpty && notMatchedBySourceActions.isEmpty) { + // The insert-only plans append without a row-level operation, which checks query auth. + tbl match { + case t: SparkTable => rejectRewriteUnderQueryAuth(t.getTable, "MERGE") + case _ => + } + } if ( matchedActions.isEmpty && notMatchedBySourceActions.isEmpty && notMatchedActions.size == 1 @@ -140,11 +148,6 @@ object Spark41MergeIntoRewrite } } - // The insert-only plans append without a row-level operation, so their scan of the target - // checks query auth. - private def rewriteRead(r: DataSourceV2Relation): DataSourceV2Relation = - PaimonRelation.withRewriteOperation(r, "MERGE") - // Fast-path #1: single NOT MATCHED InsertAction. Append over a left-anti join. private def buildSingleInsertAppendPlan( r: DataSourceV2Relation, @@ -156,7 +159,7 @@ object Spark41MergeIntoRewrite case Some(insertCond) => Filter(insertCond, source) case None => source } - val joinPlan = Join(filteredSource, rewriteRead(r), LeftAnti, Some(cond), JoinHint.NONE) + val joinPlan = Join(filteredSource, r, LeftAnti, Some(cond), JoinHint.NONE) val output = insertAction.assignments.map(_.value) val outputColNames = r.output.map(_.name) val projectList = output.zip(outputColNames).map { case (expr, name) => Alias(expr, name)() } @@ -170,7 +173,7 @@ object Spark41MergeIntoRewrite source: LogicalPlan, cond: Expression, notMatchedActions: Seq[MergeAction]): LogicalPlan = { - val joinPlan = Join(source, rewriteRead(r), LeftAnti, Some(cond), JoinHint.NONE) + val joinPlan = Join(source, r, LeftAnti, Some(cond), JoinHint.NONE) val notMatchedInstructions = notMatchedActions.map { case InsertAction(cond, assignments) => Keep(Insert, cond.getOrElse(TrueLiteral), assignments.map(_.value)) diff --git a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala index c245ba67b81a..dd5336c36b6a 100644 --- a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala +++ b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala @@ -341,12 +341,6 @@ class Spark4Shim extends SparkShim { relation.copy(catalog = Some(catalog), identifier = Some(identifier)) } - override def copyDataSourceV2Relation( - relation: DataSourceV2Relation, - options: CaseInsensitiveStringMap): DataSourceV2Relation = { - relation.copy(options = options) - } - override def createDataSourceV2Relation( table: Table, catalog: Option[CatalogPlugin], From c1bd085cd78f0c0fdcb747b67aa9724d14425323 Mon Sep 17 00:00:00 2001 From: Li Jiajia Date: Mon, 23 Nov 2026 04:15:16 -0800 Subject: [PATCH 04/10] [core][flink] Check the scan's own auth result in sort compaction and rescale Sort compaction and rescale checked query auth only when the action was built. The job authorizes again when it plans the scan, so a rule added in between was applied to the read. A partition filter that prunes every partition gives an empty plan, and the overwrite then removed the data, for example with dynamic-partition-overwrite=false. Both actions now read the table with an internal scan.rewrite-operation option. The table scan checks the auth result it plans with before it lists any file, so a rule that leaves no split fails the job as well. Co-Authored-By: Claude Opus 5.5 --- .../java/org/apache/paimon/CoreOptions.java | 14 +++++++++ .../paimon/catalog/TableQueryAuthResult.java | 2 +- .../table/source/AbstractDataTableScan.java | 5 ++++ .../paimon/flink/action/RescaleAction.java | 7 ++++- .../flink/action/SortCompactAction.java | 6 +++- .../paimon/flink/RESTCatalogITCase.java | 29 ++++++++++++++----- 6 files changed, 52 insertions(+), 11 deletions(-) diff --git a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java index aa511a20e1b9..c07f53494b42 100644 --- a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java +++ b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java @@ -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 SCAN_REWRITE_OPERATION = + key("scan.rewrite-operation") + .stringType() + .noDefaultValue() + .withDescription( + "The rewrite that reads the table with this scan. The scan fails " + + "when query auth returns row filters or column masks."); + @ExcludeFromDocumentation("Only used internally to support materialized table") public static final ConfigOption MATERIALIZED_TABLE_DEFINITION_QUERY = key("materialized-table.definition-query") @@ -3862,6 +3871,11 @@ public boolean queryAuthEnabled() { return options.get(QUERY_AUTH_ENABLED); } + @Nullable + public String scanRewriteOperation() { + return options.get(SCAN_REWRITE_OPERATION); + } + public boolean ignoreDelete() { return options.get(IGNORE_DELETE); } diff --git a/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java b/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java index b5ff20ec74b4..7f1312ccd545 100644 --- a/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java +++ b/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java @@ -180,7 +180,7 @@ public static void rejectRewriteUnderQueryAuth(@Nullable Table table, String ope } } - private static void rejectRewriteUnderQueryAuthRules( + public static void rejectRewriteUnderQueryAuthRules( @Nullable TableQueryAuthResult authResult, String operation) { if (authResult != null && authResult.hasRules()) { throw new UnsupportedOperationException( diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java index e126cd4a4094..e7d9fb424368 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java @@ -316,6 +316,11 @@ protected TableQueryAuthResult authQuery() { select = new ArrayList<>(fields); } TableQueryAuthResult result = queryAuth.auth(select); + String rewriteOperation = options.scanRewriteOperation(); + if (rewriteOperation != null) { + // Checked before planning, so a rule that leaves no split still fails the rewrite. + TableQueryAuthResult.rejectRewriteUnderQueryAuthRules(result, rewriteOperation); + } if (result != null && result.hasRules()) { // re-validated every plan, so a schema change under a live scan fails closed RowType latestSchema = diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java index b1c5f567554b..993c978d37e0 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java @@ -36,6 +36,7 @@ import javax.annotation.Nullable; +import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @@ -104,7 +105,11 @@ public void build() throws Exception { fileStoreTable.coreOptions().partitionDefaultName()); DataStream source = - new FlinkSourceBuilder(fileStoreTable) + new FlinkSourceBuilder( + fileStoreTable.copy( + Collections.singletonMap( + CoreOptions.SCAN_REWRITE_OPERATION.key(), + "Rescale"))) .env(env) .sourceBounded(true) .sourceParallelism( diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java index c9e71fe24b1f..3c6ab3035b27 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java @@ -93,7 +93,11 @@ public void build() throws Exception { } Map tableConfig = fileStoreTable.options(); FlinkSourceBuilder sourceBuilder = - new FlinkSourceBuilder(fileStoreTable) + new FlinkSourceBuilder( + fileStoreTable.copy( + Collections.singletonMap( + CoreOptions.SCAN_REWRITE_OPERATION.key(), + "Sort compaction"))) .sourceName( ObjectIdentifier.of( catalogName, diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java index 9b7f1868c629..0fc36180f9b7 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java @@ -445,13 +445,15 @@ public void testMaintenanceRewritesRequireFullTableAccess(boolean sort) throws E batchSql( "CREATE TABLE " + tableName - + " (id INT, ssn STRING) WITH ('query-auth.enabled'='true', " - + (sort ? "'bucket'='-1'" : "'primary-key'='id', 'bucket'='1'") + + " (id INT, ssn STRING, pt INT) PARTITIONED BY (pt) WITH (" + + "'query-auth.enabled'='true', 'dynamic-partition-overwrite'='false', " + + (sort ? "'bucket'='-1'" : "'primary-key'='pt,id', 'bucket'='1'") + ")"); - batchSql("INSERT INTO " + tableName + " VALUES (1, 's1'), (2, 's2')"); + batchSql("INSERT INTO " + tableName + " VALUES (1, 's1', 1), (2, 's2', 1)"); Identifier identifier = Identifier.create(DATABASE_NAME, "t_compact"); restCatalogServer.setRowFilterAuth(identifier, equalTo(0, "id", DataTypes.INT(), 1)); restCatalogServer.setColumnMaskingAuth(identifier, mask("ssn", "****")); + StreamExecutionEnvironment env = singleParallelismEnv(); ActionBase action = sort ? new SortCompactAction( @@ -462,18 +464,29 @@ public void testMaintenanceRewritesRequireFullTableAccess(boolean sort) throws E .withOrderStrategy("order") .withOrderColumns("id") : new RescaleAction(DATABASE_NAME, "t_compact", catalogOptions()) - .withBucketNum(2); - action.withStreamExecutionEnvironment(singleParallelismEnv()); + .withBucketNum(2) + .withPartition(Collections.singletonMap("pt", "1")); + action.withStreamExecutionEnvironment(env); + String message = (sort ? "Sort compaction" : "Rescale") + " requires full-table access"; assertThatThrownBy(action::build) .isInstanceOf(UnsupportedOperationException.class) - .hasMessageContaining( - (sort ? "Sort compaction" : "Rescale") + " requires full-table access"); + .hasMessageContaining(message); + // A rule added after the build that prunes every partition leaves the job no split to + // read. The scan checks the rules it plans with, so nothing is overwritten. restCatalogServer.setRowFilterAuth(identifier, null); restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); + Table table = flinkCatalog().catalog().getTable(identifier); + long snapshotId = table.latestSnapshot().get().id(); + action.build(); + restCatalogServer.setRowFilterAuth(identifier, equalTo(2, "pt", DataTypes.INT(), 2)); + assertThatThrownBy(env::execute).hasStackTraceContaining(message); + assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); + + restCatalogServer.setRowFilterAuth(identifier, null); action.run(); assertThat(batchSql("SELECT * FROM " + tableName)) - .containsExactlyInAnyOrder(Row.of(1, "s1"), Row.of(2, "s2")); + .containsExactlyInAnyOrder(Row.of(1, "s1", 1), Row.of(2, "s2", 1)); } @Test From 1f4867447d9f1adb21e4d3f7b362bb1dfa86819a Mon Sep 17 00:00:00 2001 From: Li Jiajia Date: Mon, 23 Nov 2026 04:48:32 -0800 Subject: [PATCH 05/10] [flink] Check the target scan's auth result in merge-into and delete actions The merge-into and delete actions checked query auth when they were built. MergeIntoProcedure and callers of buildDataStream() submit the job afterwards, and the job authorizes again when it plans the target scan, so a rule added in between was applied to the target rows, and the filtered, masked rows were written back. The actions now read the target with the scan.rewrite-operation option as an OPTIONS hint, so the target scan fails when the auth result it plans with has rules. This covers the alias view of MergeIntoAction and the row tracking table that the Data Evolution merge and delete read. Co-Authored-By: Claude Opus 5.5 --- .../flink/action/DataEvolutionDelete.java | 6 +++- .../action/DataEvolutionMergeIntoAction.java | 4 ++- .../paimon/flink/action/DeleteAction.java | 4 ++- .../paimon/flink/action/MergeIntoAction.java | 31 +++++++++++++++---- .../paimon/flink/RESTCatalogITCase.java | 15 +++++++++ 5 files changed, 51 insertions(+), 9 deletions(-) diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java index 0f0433733309..f4cce057d7fe 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java @@ -39,6 +39,8 @@ import java.io.Serializable; import java.util.Collections; +import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; + /** Internal implementation which logically deletes rows from a Data Evolution append table. */ class DataEvolutionDelete implements Serializable { @@ -91,12 +93,14 @@ TableResult runInternal() { String query = String.format( "SELECT `_ROW_ID` FROM `%s`.`%s`.`%s$row_tracking` " - + "/*+ OPTIONS('scan.snapshot-id'='%d', '%s'='full') */ WHERE %s", + + "/*+ OPTIONS('scan.snapshot-id'='%d', '%s'='full', '%s'='DELETE') */" + + " WHERE %s", action.catalogName, action.identifier.getDatabaseName(), action.identifier.getObjectName(), baseSnapshotId, CoreOptions.SCALAR_INDEX_SEARCH_MODE.key(), + SCAN_REWRITE_OPERATION.key(), filter); LOG.info("Data-evolution delete source query: {}", query); diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java index 1c6eb9242eca..8a484e97ee0a 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java @@ -87,6 +87,7 @@ import java.util.function.Function; import java.util.stream.Collectors; +import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; import static org.apache.paimon.format.blob.BlobFileFormat.isBlobFile; import static org.apache.paimon.utils.ParameterUtils.parseCommaSeparatedKeyValues; @@ -307,12 +308,13 @@ public Tuple2, RowType> buildSource() { query = String.format( "SELECT %s, %s FROM %s INNER JOIN %s " - + "/*+ OPTIONS('%s'='full') */ AS RT ON %s", + + "/*+ OPTIONS('%s'='full', '%s'='MERGE INTO') */ AS RT ON %s", "`RT`.`_ROW_ID` as `_ROW_ID`", String.join(",", project), escapedSourceName(), escapedRowTrackingTargetName(), CoreOptions.SCALAR_INDEX_SEARCH_MODE.key(), + SCAN_REWRITE_OPERATION.key(), rewriteMergeCondition(mergeCondition)); } diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java index 895ff53eb4d1..5327928f6f5a 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java @@ -39,6 +39,7 @@ import java.util.stream.Collectors; import static org.apache.paimon.CoreOptions.MergeEngine.DEDUPLICATE; +import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; /** Delete from table action for Flink, dispatching by table type. */ @@ -118,10 +119,11 @@ private void runPrimaryKeyDelete() throws Exception { Table queriedTable = batchTEnv.sqlQuery( String.format( - "SELECT * FROM `%s`.`%s`.`%s` WHERE %s", + "SELECT * FROM `%s`.`%s`.`%s` /*+ OPTIONS('%s'='DELETE') */ WHERE %s", catalogName, identifier.getDatabaseName(), identifier.getObjectName(), + SCAN_REWRITE_OPERATION.key(), filter)); List> converters = diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java index 4fa7d61a0e8c..d56923c73784 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java @@ -48,6 +48,7 @@ import static org.apache.paimon.CoreOptions.MergeEngine.DEDUPLICATE; import static org.apache.paimon.CoreOptions.MergeEngine.PARTIAL_UPDATE; +import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; import static org.apache.paimon.utils.ParameterUtils.parseCommaSeparatedKeyValues; @@ -81,6 +82,10 @@ public class MergeIntoAction extends TableActionBase { public static final String IDENTIFIER_QUOTE = "`"; + // checks query auth again when the job reads the target + private static final String TARGET_SCAN_HINT = + String.format("/*+ OPTIONS('%s'='MERGE INTO') */", SCAN_REWRITE_OPERATION.key()); + // primary keys of target table private final List primaryKeys; @@ -282,7 +287,14 @@ private void handleTargetAlias() { // create a view 'targetAlias' in the path of target table, then we can find it with the // qualified name batchTEnv.createTemporaryView( - escapedTargetName(), batchTEnv.from(identifier.getFullName())); + escapedTargetName(), + batchTEnv.sqlQuery( + String.format( + "SELECT * FROM `%s`.`%s`.`%s` %s", + catalogName, + identifier.getDatabaseName(), + identifier.getObjectName(), + TARGET_SCAN_HINT))); } } @@ -339,7 +351,7 @@ private Optional> getMatchedUpsertDataStream() { String.format( "SELECT %s FROM %s INNER JOIN %s ON %s %s", String.join(",", normalizeFieldName(project)), - escapedTargetName(), + targetScan(), escapedSourceName(), mergeCondition, matchedUpsertCondition == null ? "" : "WHERE " + matchedUpsertCondition); @@ -383,7 +395,7 @@ private Optional> getNotMatchedUpsertDataStream() { String.format( "SELECT %s FROM %s WHERE NOT EXISTS (SELECT * FROM %s WHERE %s) %s", String.join(",", normalizeFieldName(project)), - escapedTargetName(), + targetScan(), escapedSourceName(), mergeCondition, notMatchedBySourceUpsertCondition == null @@ -414,7 +426,7 @@ private Optional> getMatchedDeleteDataStream() { String.format( "SELECT %s FROM %s INNER JOIN %s ON %s %s", String.join(",", normalizeFieldName(project)), - escapedTargetName(), + targetScan(), escapedSourceName(), mergeCondition, matchedDeleteCondition == null ? "" : "WHERE " + matchedDeleteCondition); @@ -436,7 +448,7 @@ private Optional> getNotMatchedDeleteDataStream() { String.format( "SELECT %s FROM %s WHERE NOT EXISTS (SELECT * FROM %s WHERE %s) %s", String.join(",", normalizeFieldName(targetFieldNames)), - escapedTargetName(), + targetScan(), escapedSourceName(), mergeCondition, notMatchedBySourceDeleteCondition == null @@ -461,7 +473,7 @@ private Optional> getInsertDataStream() { "SELECT %s FROM %s WHERE NOT EXISTS (SELECT * FROM %s WHERE %s) %s", notMatchedInsertValues, escapedSourceName(), - escapedTargetName(), + targetScan(), mergeCondition, notMatchedInsertCondition == null ? "" @@ -519,6 +531,13 @@ private String escapedTargetName() { "`%s`.`%s`.`%s`", catalogName, identifier.getDatabaseName(), targetTableName()); } + // the alias view reads the target with the hint already + private String targetScan() { + return targetAlias == null + ? escapedTargetName() + " " + TARGET_SCAN_HINT + : escapedTargetName(); + } + private String escapedSourceName() { return Arrays.stream(sourceTable.split("\\.")) .map(s -> String.format("`%s`", s)) diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java index 0fc36180f9b7..836dfd4985a3 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java @@ -54,12 +54,14 @@ import org.apache.paimon.shade.guava30.com.google.common.collect.ImmutableMap; import org.apache.flink.api.common.RuntimeExecutionMode; +import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.catalog.Catalog; import org.apache.flink.table.catalog.CatalogFunction; import org.apache.flink.table.catalog.CatalogFunctionImpl; import org.apache.flink.table.catalog.FunctionLanguage; import org.apache.flink.table.catalog.ObjectPath; +import org.apache.flink.table.data.RowData; import org.apache.flink.table.resource.ResourceType; import org.apache.flink.table.resource.ResourceUri; import org.apache.flink.types.Row; @@ -336,6 +338,19 @@ public void testMergeIntoActionRequiresFullTableAccess(boolean dataEvolution) th .hasMessageContaining("MERGE INTO requires full-table access"); restCatalogServer.setRowFilterAuth(identifier, null); + if (!dataEvolution) { + // A rule added after the merge is built is checked when the job plans the target scan. + MergeIntoAction merge = (MergeIntoAction) mergeAction(false); + DataStream dataStream = merge.buildDataStream(); + Table table = flinkCatalog().catalog().getTable(identifier); + long snapshotId = table.latestSnapshot().get().id(); + restCatalogServer.setRowFilterAuth( + identifier, equalTo(0, "id", DataTypes.STRING(), "visible")); + assertThatThrownBy(() -> merge.batchSink(dataStream).await()) + .hasStackTraceContaining("MERGE INTO requires full-table access"); + assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); + restCatalogServer.setRowFilterAuth(identifier, null); + } mergeAction(dataEvolution).run(); assertThat(batchSql("SELECT note FROM " + tableName + " ORDER BY id")) .extracting(row -> row.getField(0)) From 730e4a960dd4c4c72fc17287119de0f0c4e14448 Mon Sep 17 00:00:00 2001 From: Li Jiajia Date: Mon, 23 Nov 2026 05:17:09 -0800 Subject: [PATCH 06/10] [flink] Pass the rewrite scan option through the action's table config The merge-into and delete actions passed scan.rewrite-operation to the target scan as an OPTIONS hint. With table.dynamic-table-options.enabled set to false, Flink rejects the hint, so the primary-key merge and delete failed in planning even for a user with full access. The actions now set the option as a paimon.... table option in the table config of their own table environment, which the Paimon table factory reads without dynamic table options. It also reaches the row tracking table that the Data Evolution merge and delete read, so their existing hints are left as they were on master. Co-Authored-By: Claude Opus 5.5 --- .../flink/action/DataEvolutionDelete.java | 6 +--- .../action/DataEvolutionMergeIntoAction.java | 5 ++- .../paimon/flink/action/DeleteAction.java | 5 ++- .../paimon/flink/action/MergeIntoAction.java | 32 ++++--------------- .../paimon/flink/action/TableActionBase.java | 21 ++++++++++++ .../paimon/flink/RESTCatalogITCase.java | 23 +++++++++++-- 6 files changed, 54 insertions(+), 38 deletions(-) diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java index f4cce057d7fe..0f0433733309 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionDelete.java @@ -39,8 +39,6 @@ import java.io.Serializable; import java.util.Collections; -import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; - /** Internal implementation which logically deletes rows from a Data Evolution append table. */ class DataEvolutionDelete implements Serializable { @@ -93,14 +91,12 @@ TableResult runInternal() { String query = String.format( "SELECT `_ROW_ID` FROM `%s`.`%s`.`%s$row_tracking` " - + "/*+ OPTIONS('scan.snapshot-id'='%d', '%s'='full', '%s'='DELETE') */" - + " WHERE %s", + + "/*+ OPTIONS('scan.snapshot-id'='%d', '%s'='full') */ WHERE %s", action.catalogName, action.identifier.getDatabaseName(), action.identifier.getObjectName(), baseSnapshotId, CoreOptions.SCALAR_INDEX_SEARCH_MODE.key(), - SCAN_REWRITE_OPERATION.key(), filter); LOG.info("Data-evolution delete source query: {}", query); diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java index 8a484e97ee0a..9ef7006760ff 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java @@ -87,7 +87,6 @@ import java.util.function.Function; import java.util.stream.Collectors; -import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; import static org.apache.paimon.format.blob.BlobFileFormat.isBlobFile; import static org.apache.paimon.utils.ParameterUtils.parseCommaSeparatedKeyValues; @@ -259,6 +258,7 @@ public TableResult runInternal() { public Tuple2, RowType> buildSource() { rejectRewriteUnderQueryAuth(table, "MERGE INTO"); + checkQueryAuthWhenScanningTarget("MERGE INTO"); if (targetTableName().equals(sourceTableName())) { throw new RuntimeException( String.format( @@ -308,13 +308,12 @@ public Tuple2, RowType> buildSource() { query = String.format( "SELECT %s, %s FROM %s INNER JOIN %s " - + "/*+ OPTIONS('%s'='full', '%s'='MERGE INTO') */ AS RT ON %s", + + "/*+ OPTIONS('%s'='full') */ AS RT ON %s", "`RT`.`_ROW_ID` as `_ROW_ID`", String.join(",", project), escapedSourceName(), escapedRowTrackingTargetName(), CoreOptions.SCALAR_INDEX_SEARCH_MODE.key(), - SCAN_REWRITE_OPERATION.key(), rewriteMergeCondition(mergeCondition)); } diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java index 5327928f6f5a..5b75e417dd60 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java @@ -39,7 +39,6 @@ import java.util.stream.Collectors; import static org.apache.paimon.CoreOptions.MergeEngine.DEDUPLICATE; -import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; /** Delete from table action for Flink, dispatching by table type. */ @@ -89,6 +88,7 @@ public DeleteAction withSinkParallelism(int sinkParallelism) { @Override public void run() throws Exception { rejectRewriteUnderQueryAuth(table, "DELETE"); + checkQueryAuthWhenScanningTarget("DELETE"); handleSqls(); if (dataEvolutionDelete != null) { dataEvolutionDelete.runInternal().await(); @@ -119,11 +119,10 @@ private void runPrimaryKeyDelete() throws Exception { Table queriedTable = batchTEnv.sqlQuery( String.format( - "SELECT * FROM `%s`.`%s`.`%s` /*+ OPTIONS('%s'='DELETE') */ WHERE %s", + "SELECT * FROM `%s`.`%s`.`%s` WHERE %s", catalogName, identifier.getDatabaseName(), identifier.getObjectName(), - SCAN_REWRITE_OPERATION.key(), filter)); List> converters = diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java index d56923c73784..1fc79d86cd4d 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java @@ -48,7 +48,6 @@ import static org.apache.paimon.CoreOptions.MergeEngine.DEDUPLICATE; import static org.apache.paimon.CoreOptions.MergeEngine.PARTIAL_UPDATE; -import static org.apache.paimon.CoreOptions.SCAN_REWRITE_OPERATION; import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; import static org.apache.paimon.utils.ParameterUtils.parseCommaSeparatedKeyValues; @@ -82,10 +81,6 @@ public class MergeIntoAction extends TableActionBase { public static final String IDENTIFIER_QUOTE = "`"; - // checks query auth again when the job reads the target - private static final String TARGET_SCAN_HINT = - String.format("/*+ OPTIONS('%s'='MERGE INTO') */", SCAN_REWRITE_OPERATION.key()); - // primary keys of target table private final List primaryKeys; @@ -260,6 +255,7 @@ public void run() throws Exception { public DataStream buildDataStream() { rejectRewriteUnderQueryAuth(table, "MERGE INTO"); + checkQueryAuthWhenScanningTarget("MERGE INTO"); // handle aliases handleTargetAlias(); @@ -287,14 +283,7 @@ private void handleTargetAlias() { // create a view 'targetAlias' in the path of target table, then we can find it with the // qualified name batchTEnv.createTemporaryView( - escapedTargetName(), - batchTEnv.sqlQuery( - String.format( - "SELECT * FROM `%s`.`%s`.`%s` %s", - catalogName, - identifier.getDatabaseName(), - identifier.getObjectName(), - TARGET_SCAN_HINT))); + escapedTargetName(), batchTEnv.from(identifier.getFullName())); } } @@ -351,7 +340,7 @@ private Optional> getMatchedUpsertDataStream() { String.format( "SELECT %s FROM %s INNER JOIN %s ON %s %s", String.join(",", normalizeFieldName(project)), - targetScan(), + escapedTargetName(), escapedSourceName(), mergeCondition, matchedUpsertCondition == null ? "" : "WHERE " + matchedUpsertCondition); @@ -395,7 +384,7 @@ private Optional> getNotMatchedUpsertDataStream() { String.format( "SELECT %s FROM %s WHERE NOT EXISTS (SELECT * FROM %s WHERE %s) %s", String.join(",", normalizeFieldName(project)), - targetScan(), + escapedTargetName(), escapedSourceName(), mergeCondition, notMatchedBySourceUpsertCondition == null @@ -426,7 +415,7 @@ private Optional> getMatchedDeleteDataStream() { String.format( "SELECT %s FROM %s INNER JOIN %s ON %s %s", String.join(",", normalizeFieldName(project)), - targetScan(), + escapedTargetName(), escapedSourceName(), mergeCondition, matchedDeleteCondition == null ? "" : "WHERE " + matchedDeleteCondition); @@ -448,7 +437,7 @@ private Optional> getNotMatchedDeleteDataStream() { String.format( "SELECT %s FROM %s WHERE NOT EXISTS (SELECT * FROM %s WHERE %s) %s", String.join(",", normalizeFieldName(targetFieldNames)), - targetScan(), + escapedTargetName(), escapedSourceName(), mergeCondition, notMatchedBySourceDeleteCondition == null @@ -473,7 +462,7 @@ private Optional> getInsertDataStream() { "SELECT %s FROM %s WHERE NOT EXISTS (SELECT * FROM %s WHERE %s) %s", notMatchedInsertValues, escapedSourceName(), - targetScan(), + escapedTargetName(), mergeCondition, notMatchedInsertCondition == null ? "" @@ -531,13 +520,6 @@ private String escapedTargetName() { "`%s`.`%s`.`%s`", catalogName, identifier.getDatabaseName(), targetTableName()); } - // the alias view reads the target with the hint already - private String targetScan() { - return targetAlias == null - ? escapedTargetName() + " " + TARGET_SCAN_HINT - : escapedTargetName(); - } - private String escapedSourceName() { return Arrays.stream(sourceTable.split("\\.")) .map(s -> String.format("`%s`", s)) diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/TableActionBase.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/TableActionBase.java index aa977a9e2bcb..92eb85bc96ea 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/TableActionBase.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/TableActionBase.java @@ -18,12 +18,15 @@ package org.apache.paimon.flink.action; +import org.apache.paimon.CoreOptions; import org.apache.paimon.catalog.Catalog; import org.apache.paimon.catalog.Identifier; +import org.apache.paimon.flink.FlinkConnectorOptions; import org.apache.paimon.flink.sink.FlinkSinkBuilder; import org.apache.paimon.table.Table; import org.apache.flink.api.dag.Transformation; +import org.apache.flink.configuration.ConfigOptions; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.table.api.TableResult; import org.apache.flink.table.api.bridge.java.StreamTableEnvironment; @@ -52,6 +55,24 @@ public abstract class TableActionBase extends ActionBase { } /** Sink {@link DataStream} dataStream to table with Flink Table API in batch environment. */ + /** + * Makes the scans of the target in this action fail when the query auth result they plan with + * has rules, so a rule added after the action is built is not applied to the rewrite. The + * option is passed as a table option in the table config of this action, which does not need + * dynamic table options to be enabled. + */ + protected void checkQueryAuthWhenScanningTarget(String operation) { + String key = + String.format( + "%s%s.%s.%s.%s", + FlinkConnectorOptions.TABLE_DYNAMIC_OPTION_PREFIX, + catalogName, + identifier.getDatabaseName(), + identifier.getTableName(), + CoreOptions.SCAN_REWRITE_OPERATION.key()); + batchTEnv.getConfig().set(ConfigOptions.key(key).stringType().noDefaultValue(), operation); + } + public TableResult batchSink(DataStream dataStream) { List> transformations = Collections.singletonList( diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java index 836dfd4985a3..aa514a711f73 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java @@ -54,6 +54,8 @@ import org.apache.paimon.shade.guava30.com.google.common.collect.ImmutableMap; import org.apache.flink.api.common.RuntimeExecutionMode; +import org.apache.flink.configuration.ConfigOptions; +import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.catalog.Catalog; @@ -351,7 +353,12 @@ public void testMergeIntoActionRequiresFullTableAccess(boolean dataEvolution) th assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); restCatalogServer.setRowFilterAuth(identifier, null); } - mergeAction(dataEvolution).run(); + ActionBase merge = mergeAction(dataEvolution); + if (!dataEvolution) { + // The Data Evolution merge already reads the target with an OPTIONS hint. + merge.withStreamExecutionEnvironment(withoutDynamicTableOptions()); + } + merge.run(); assertThat(batchSql("SELECT note FROM " + tableName + " ORDER BY id")) .extracting(row -> row.getField(0)) .containsExactly("merged", "original"); @@ -387,8 +394,10 @@ public void testDeleteActionRequiresFullTableAccess(boolean dataEvolution, boole assertThat(batchSql("SELECT * FROM " + tableName)) .containsExactlyInAnyOrder( Row.of("visible", "original", 1), Row.of("hidden", "original", 1)); + // The Data Evolution delete already reads the target with an OPTIONS hint. new DeleteAction(DATABASE_NAME, "t_delete", "TRUE", catalogOptions()) - .withStreamExecutionEnvironment(singleParallelismEnv()) + .withStreamExecutionEnvironment( + dataEvolution ? singleParallelismEnv() : withoutDynamicTableOptions()) .run(); assertThat(batchSql("SELECT * FROM " + tableName)).isEmpty(); } @@ -429,6 +438,16 @@ private static StreamExecutionEnvironment singleParallelismEnv() { return StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1); } + private static StreamExecutionEnvironment withoutDynamicTableOptions() { + Configuration conf = new Configuration(); + conf.set( + ConfigOptions.key("table.dynamic-table-options.enabled") + .booleanType() + .noDefaultValue(), + false); + return StreamExecutionEnvironment.getExecutionEnvironment(conf).setParallelism(1); + } + private ActionBase mergeAction(boolean dataEvolution) { String sourceSql = "CREATE TEMPORARY VIEW " From 8b276699869f714ab52dfe6343efcc3be45c8201 Mon Sep 17 00:00:00 2001 From: Li Jiajia Date: Mon, 23 Nov 2026 05:17:09 -0800 Subject: [PATCH 07/10] [spark] Check query auth for insert-only merges on Spark 4.2 and 4.3 On Spark 4.2 and 4.3, Spark42RowLevelCommandRewrite hands a merge on a V2 append table to Spark's native rewrite during resolution. A merge with only WHEN NOT MATCHED clauses becomes an append over an anti join, so neither the row-level operation nor PaimonMergeInto, which runs post hoc, checked query auth, and rows whose keys the row filter hid were inserted again. The rule now checks query auth before it rewrites an insert-only merge. Spark42CompatibilityTest, which both connectors run, covers it. Co-Authored-By: Claude Opus 5.5 --- .../Spark42RowLevelCommandRewrite.scala | 6 +++ .../spark/sql/Spark42CompatibilityTest.scala | 38 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/catalyst/analysis/Spark42RowLevelCommandRewrite.scala b/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/catalyst/analysis/Spark42RowLevelCommandRewrite.scala index 1e7468e77339..a6341c430c92 100644 --- a/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/catalyst/analysis/Spark42RowLevelCommandRewrite.scala +++ b/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/catalyst/analysis/Spark42RowLevelCommandRewrite.scala @@ -18,6 +18,7 @@ package org.apache.spark.sql.catalyst.analysis +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth import org.apache.paimon.spark.SparkTable import org.apache.paimon.spark.catalyst.analysis.{MergeSchemaEvolutionHelper, PaimonAssignmentUtils, PaimonRelation} @@ -55,6 +56,11 @@ object Spark42RowLevelCommandRewrite .map(_._1) .getOrElse(m) val aligned = alignAllMergeActions(evolved, evolved.targetTable.output) + if (aligned.matchedActions.isEmpty && aligned.notMatchedBySourceActions.isEmpty) { + // Spark rewrites an insert-only merge as an append over an anti join, without the + // row-level operation that checks query auth. + rejectRewriteUnderQueryAuth(table.getTable, "MERGE") + } RewriteMergeIntoTable(aligned.copy()) } } diff --git a/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/Spark42CompatibilityTest.scala b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/Spark42CompatibilityTest.scala index 9f36aa10db2f..37b84348ca79 100644 --- a/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/Spark42CompatibilityTest.scala +++ b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/Spark42CompatibilityTest.scala @@ -18,11 +18,14 @@ package org.apache.paimon.spark.sql +import org.apache.paimon.catalog.Identifier +import org.apache.paimon.predicate.{Equal, FieldRef, FieldTransform, LeafPredicate, Predicate} import org.apache.paimon.rest.RESTCatalogServer import org.apache.paimon.rest.auth.BearTokenAuthProvider import org.apache.paimon.rest.responses.ConfigResponse import org.apache.paimon.spark.SparkCatalog import org.apache.paimon.spark.extensions.PaimonSparkSessionExtensions +import org.apache.paimon.types.DataTypes import org.apache.spark.SparkConf import org.apache.spark.sql.{AnalysisException, QueryTest, Row} @@ -231,6 +234,41 @@ class Spark42CompatibilityTest extends QueryTest with SharedSparkSession { } } + test("insert-only merges with v2 writes require full-table access") { + withSQLConf("spark.paimon.write.use-v2-write" -> "true") { + withTable("t_auth") { + sql("CREATE TABLE t_auth (id INT, v INT) TBLPROPERTIES ('query-auth.enabled'='true')") + sql("INSERT INTO t_auth VALUES (1, 10), (2, 20)") + val identifier = Identifier.create("test", "t_auth") + val merge = "MERGE INTO t_auth t USING (SELECT 2 AS id, 22 AS v) s ON t.id = s.id " + + "WHEN NOT MATCHED THEN INSERT *" + // The row filter hides id = 2, so the merge would insert it again. + server.setRowFilterAuth( + identifier, + Collections.singletonList[Predicate]( + LeafPredicate.of( + new FieldTransform(new FieldRef(0, "id", DataTypes.INT())), + Equal.INSTANCE, + Collections.singletonList[AnyRef](Integer.valueOf(1)))) + ) + try { + val e = intercept[Exception](sql(merge).collect()) + assert( + Iterator + .iterate[Throwable](e)(_.getCause) + .takeWhile(_ != null) + .exists( + t => String.valueOf(t.getMessage).contains("MERGE requires full-table access"))) + } finally { + server.setRowFilterAuth(identifier, null) + } + checkAnswer(sql("SELECT * FROM t_auth"), Seq(Row(1, 10), Row(2, 20))) + sql(merge) + checkAnswer(sql("SELECT * FROM t_auth"), Seq(Row(1, 10), Row(2, 20))) + } + } + } + test("variant values and spatial scalar and array getters") { val point = "0101000000000000000000F03F0000000000000040" withTable("typed") { From 620375430b5259cadd5fcca81b062c1e1bb67b06 Mon Sep 17 00:00:00 2001 From: Li Jiajia Date: Mon, 23 Nov 2026 05:46:22 -0800 Subject: [PATCH 08/10] [flink] Quote names when matching table options in the table config AbstractFlinkTableFactory built the pattern for paimon...
. options from the unquoted names. A legal table name such as t+1 did not match its own key, and the key was passed on whole as a global option, so the scan.rewrite-operation that the merge-into and delete actions set for their target was lost: a column mask added after the action started was applied to the target scan instead of failing it. Names with '.' or '+' could also match the options of other tables. The names and the prefix are now quoted with Pattern.quote. Co-Authored-By: Claude Opus 5.5 --- .../flink/AbstractFlinkTableFactory.java | 9 ++++--- .../flink/AbstractFlinkTableFactoryTest.java | 21 +++++++++++++++ .../paimon/flink/RESTCatalogITCase.java | 27 +++++++++++++++++++ 3 files changed, 53 insertions(+), 4 deletions(-) diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/AbstractFlinkTableFactory.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/AbstractFlinkTableFactory.java index 10b7e2928f17..e15f74c78dd8 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/AbstractFlinkTableFactory.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/AbstractFlinkTableFactory.java @@ -322,13 +322,14 @@ static Map getDynamicConfigOptions(DynamicTableFactory.Context c new Identifier(identifier.getDatabaseName(), identifier.getObjectName()) .getTableName(); + // Quote the names, which may contain regex metacharacters, such as '+' in `t+1`. String template = String.format( "(%s)(%s|\\*)\\.(%s|\\*)\\.(%s|\\*)\\.(.+)", - FlinkConnectorOptions.TABLE_DYNAMIC_OPTION_PREFIX, - identifier.getCatalogName(), - identifier.getDatabaseName(), - tableName); + Pattern.quote(FlinkConnectorOptions.TABLE_DYNAMIC_OPTION_PREFIX), + Pattern.quote(identifier.getCatalogName()), + Pattern.quote(identifier.getDatabaseName()), + Pattern.quote(tableName)); Pattern pattern = Pattern.compile(template); Map optionsFromTableConfig = OptionsUtils.convertToDynamicTableProperties(conf, "", pattern, 5); diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/AbstractFlinkTableFactoryTest.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/AbstractFlinkTableFactoryTest.java index 38d48fa21d2d..2100df798201 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/AbstractFlinkTableFactoryTest.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/AbstractFlinkTableFactoryTest.java @@ -94,6 +94,27 @@ public void testGetDynamicOptions() { assertThat(options).isEqualTo(ImmutableMap.of("k1", "v1", "k2", "v2", "k3", "v3")); } + @Test + public void testGetDynamicOptionsForNamesWithRegexMetacharacters() { + Configuration configuration = new Configuration(); + configuration.setString("paimon.paimon-1.db+.t+1.k1", "v1"); + configuration.setString("paimon.*.db+.t+1.k2", "v2"); + // '.' and '+' in the names are not regex wildcards or quantifiers + configuration.setString("paimon.paimon-1.dbb.t+1.k3", "v3"); + configuration.setString("paimon.paimon-1.db+.tt1.k4", "v4"); + DynamicTableFactory.Context context = + new FactoryUtil.DefaultDynamicTableContext( + ObjectIdentifier.of("paimon-1", "db+", "t+1"), + null, + new HashMap<>(), + configuration, + AbstractFlinkTableFactoryTest.class.getClassLoader(), + false); + Map options = AbstractFlinkTableFactory.getDynamicConfigOptions(context); + assertThat(options).containsEntry("k1", "v1").containsEntry("k2", "v2"); + assertThat(options).doesNotContainKeys("k3", "k4"); + } + private void innerTest(RowType r1, RowType r2, boolean expectEquals) { assertThat(AbstractFlinkTableFactory.schemaEquals(r1, r2)).isEqualTo(expectEquals); } diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java index aa514a711f73..9f89212b7a56 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java @@ -364,6 +364,33 @@ public void testMergeIntoActionRequiresFullTableAccess(boolean dataEvolution) th .containsExactly("merged", "original"); } + @Test + public void testRewriteScanOptionReachesTableWithSpecialName() { + // The merge-into and delete actions mark their target scans with this table option. '+' + // is a regex metacharacter, so the name must be quoted when the option is matched. + String tableName = DATABASE_NAME + ".`t+1`"; + batchSql( + "CREATE TABLE " + + tableName + + " (id STRING, note STRING) WITH ('query-auth.enabled'='true'," + + " 'primary-key'='id', 'bucket'='1')"); + batchSql("INSERT INTO " + tableName + " VALUES ('a', 'original')"); + tEnv.getConfig() + .getConfiguration() + .setString( + String.format( + "paimon.PAIMON.%s.t+1.%s", + DATABASE_NAME, CoreOptions.SCAN_REWRITE_OPERATION.key()), + "DELETE"); + assertThat(batchSql("SELECT * FROM " + tableName)).containsExactly(Row.of("a", "original")); + + Identifier identifier = Identifier.create(DATABASE_NAME, "t+1"); + restCatalogServer.setColumnMaskingAuth(identifier, mask("note", "****")); + assertThatThrownBy(() -> batchSql("SELECT * FROM " + tableName)) + .hasStackTraceContaining("DELETE requires full-table access"); + restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); + } + @ParameterizedTest @CsvSource({"false,false", "false,true", "true,false", "true,true"}) public void testDeleteActionRequiresFullTableAccess(boolean dataEvolution, boolean filterAll) From 02f135974647940fc7bb5aed7a5dbfccfa4c765c Mon Sep 17 00:00:00 2001 From: Li Jiajia Date: Mon, 23 Nov 2026 06:27:50 -0800 Subject: [PATCH 09/10] [flink] Scope the rewrite scan option to the target branch The merge-into and delete actions set scan.rewrite-operation for their target as a paimon...
. option, which the table factory matches by the table name alone. A source on another branch of the target, such as t$branch_source, got the option too, so a merge failed when that branch had a legal row filter, though the target had full access. The table factory now also accepts a table name qualified with a branch, t$branch_, which reaches that branch and its system tables only, and the actions use it. The row tracking table of a Data Evolution target keeps the option, and fallback and chain branches are read through the target table itself. The delete action and the Data Evolution merge are now also tested with a rule added after they checked query auth. Co-Authored-By: Claude Opus 5.5 --- .../flink/AbstractFlinkTableFactory.java | 23 +++- .../paimon/flink/action/TableActionBase.java | 26 ++-- .../flink/AbstractFlinkTableFactoryTest.java | 35 ++++++ .../paimon/flink/RESTCatalogITCase.java | 111 +++++++++++++++--- 4 files changed, 162 insertions(+), 33 deletions(-) diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/AbstractFlinkTableFactory.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/AbstractFlinkTableFactory.java index e15f74c78dd8..e3c6fef8fc15 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/AbstractFlinkTableFactory.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/AbstractFlinkTableFactory.java @@ -307,7 +307,8 @@ static boolean schemaEquals(RowType rowType1, RowType rowType2) { * *

Table Options: {@link * FlinkConnectorOptions#TABLE_DYNAMIC_OPTION_PREFIX}${catalog}.${database}.${tableName}.key = - * value. + * value. The table name may also be qualified with a branch, see {@link + * #branchQualifiedTableName}, to give the options only to that branch and its system tables. * *

These job level options will be extracted and injected into the target table option. Table * options will override global options if there are conflicts. @@ -318,17 +319,18 @@ static boolean schemaEquals(RowType rowType1, RowType rowType2) { static Map getDynamicConfigOptions(DynamicTableFactory.Context context) { Map conf = getAllOptions(context); ObjectIdentifier identifier = context.getObjectIdentifier(); - String tableName = - new Identifier(identifier.getDatabaseName(), identifier.getObjectName()) - .getTableName(); + Identifier paimonIdentifier = + new Identifier(identifier.getDatabaseName(), identifier.getObjectName()); + String tableName = paimonIdentifier.getTableName(); // Quote the names, which may contain regex metacharacters, such as '+' in `t+1`. String template = String.format( - "(%s)(%s|\\*)\\.(%s|\\*)\\.(%s|\\*)\\.(.+)", + "(%s)(%s|\\*)\\.(%s|\\*)\\.(%s|%s|\\*)\\.(.+)", Pattern.quote(FlinkConnectorOptions.TABLE_DYNAMIC_OPTION_PREFIX), Pattern.quote(identifier.getCatalogName()), Pattern.quote(identifier.getDatabaseName()), + Pattern.quote(branchQualifiedTableName(paimonIdentifier)), Pattern.quote(tableName)); Pattern pattern = Pattern.compile(template); Map optionsFromTableConfig = @@ -343,6 +345,17 @@ static Map getDynamicConfigOptions(DynamicTableFactory.Context c return optionsFromTableConfig; } + /** + * The table name with the branch of {@code identifier}, such as {@code t$branch_main} for + * {@code t} and {@code t$row_tracking}, and {@code t$branch_b} for {@code t$branch_b}. + */ + public static String branchQualifiedTableName(Identifier identifier) { + return identifier.getTableName() + + Identifier.SYSTEM_TABLE_SPLITTER + + Identifier.SYSTEM_BRANCH_PREFIX + + identifier.getBranchNameOrDefault(); + } + public static Map getAllOptions(DynamicTableFactory.Context context) { ReadableConfig config = context.getConfiguration(); if (config instanceof Configuration) { diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/TableActionBase.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/TableActionBase.java index 92eb85bc96ea..2e24e3746c9f 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/TableActionBase.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/TableActionBase.java @@ -19,8 +19,10 @@ package org.apache.paimon.flink.action; import org.apache.paimon.CoreOptions; +import org.apache.paimon.annotation.VisibleForTesting; import org.apache.paimon.catalog.Catalog; import org.apache.paimon.catalog.Identifier; +import org.apache.paimon.flink.AbstractFlinkTableFactory; import org.apache.paimon.flink.FlinkConnectorOptions; import org.apache.paimon.flink.sink.FlinkSinkBuilder; import org.apache.paimon.table.Table; @@ -59,20 +61,26 @@ public abstract class TableActionBase extends ActionBase { * Makes the scans of the target in this action fail when the query auth result they plan with * has rules, so a rule added after the action is built is not applied to the rewrite. The * option is passed as a table option in the table config of this action, which does not need - * dynamic table options to be enabled. + * dynamic table options to be enabled. It is qualified with the branch of the target, so it + * reaches the target and its row tracking table, but not a source on another branch. */ protected void checkQueryAuthWhenScanningTarget(String operation) { - String key = - String.format( - "%s%s.%s.%s.%s", - FlinkConnectorOptions.TABLE_DYNAMIC_OPTION_PREFIX, - catalogName, - identifier.getDatabaseName(), - identifier.getTableName(), - CoreOptions.SCAN_REWRITE_OPERATION.key()); + String key = rewriteOperationOptionKey(catalogName, identifier); batchTEnv.getConfig().set(ConfigOptions.key(key).stringType().noDefaultValue(), operation); } + /** The table config key that gives the target scans the rewrite operation. */ + @VisibleForTesting + public static String rewriteOperationOptionKey(String catalogName, Identifier identifier) { + return String.format( + "%s%s.%s.%s.%s", + FlinkConnectorOptions.TABLE_DYNAMIC_OPTION_PREFIX, + catalogName, + identifier.getDatabaseName(), + AbstractFlinkTableFactory.branchQualifiedTableName(identifier), + CoreOptions.SCAN_REWRITE_OPERATION.key()); + } + public TableResult batchSink(DataStream dataStream) { List> transformations = Collections.singletonList( diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/AbstractFlinkTableFactoryTest.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/AbstractFlinkTableFactoryTest.java index 2100df798201..2a3d564f27b1 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/AbstractFlinkTableFactoryTest.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/AbstractFlinkTableFactoryTest.java @@ -115,6 +115,41 @@ public void testGetDynamicOptionsForNamesWithRegexMetacharacters() { assertThat(options).doesNotContainKeys("k3", "k4"); } + @Test + public void testGetDynamicOptionsForBranchQualifiedTableName() { + Configuration configuration = new Configuration(); + configuration.setString("paimon.c.db.t.k1", "v1"); + configuration.setString("paimon.c.db.t$branch_main.k2", "v2"); + configuration.setString("paimon.c.db.t$branch_b.k3", "v3"); + assertThat(dynamicOptions(configuration, "t")) + .containsEntry("k1", "v1") + .containsEntry("k2", "v2") + .doesNotContainKey("k3"); + // a system table gets the options of its branch + assertThat(dynamicOptions(configuration, "t$row_tracking")) + .containsEntry("k1", "v1") + .containsEntry("k2", "v2") + .doesNotContainKey("k3"); + assertThat(dynamicOptions(configuration, "t$branch_b")) + .containsEntry("k1", "v1") + .containsEntry("k3", "v3") + .doesNotContainKey("k2"); + assertThat(dynamicOptions(configuration, "t$branch_b$row_tracking")) + .containsEntry("k3", "v3") + .doesNotContainKey("k2"); + } + + private static Map dynamicOptions(Configuration configuration, String table) { + return AbstractFlinkTableFactory.getDynamicConfigOptions( + new FactoryUtil.DefaultDynamicTableContext( + ObjectIdentifier.of("c", "db", table), + null, + new HashMap<>(), + configuration, + AbstractFlinkTableFactoryTest.class.getClassLoader(), + false)); + } + private void innerTest(RowType r1, RowType r2, boolean expectEquals) { assertThat(AbstractFlinkTableFactory.schemaEquals(r1, r2)).isEqualTo(expectEquals); } diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java index 9f89212b7a56..44f309f81369 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java @@ -28,6 +28,7 @@ import org.apache.paimon.flink.action.MergeIntoAction; import org.apache.paimon.flink.action.RescaleAction; import org.apache.paimon.flink.action.SortCompactAction; +import org.apache.paimon.flink.action.TableActionBase; import org.apache.paimon.partition.Partition; import org.apache.paimon.predicate.ConcatTransform; import org.apache.paimon.predicate.ConcatWsTransform; @@ -58,15 +59,18 @@ import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; +import org.apache.flink.streaming.api.functions.sink.v2.DiscardingSink; import org.apache.flink.table.catalog.Catalog; import org.apache.flink.table.catalog.CatalogFunction; import org.apache.flink.table.catalog.CatalogFunctionImpl; import org.apache.flink.table.catalog.FunctionLanguage; import org.apache.flink.table.catalog.ObjectPath; import org.apache.flink.table.data.RowData; +import org.apache.flink.table.functions.ScalarFunction; import org.apache.flink.table.resource.ResourceType; import org.apache.flink.table.resource.ResourceUri; import org.apache.flink.types.Row; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -340,19 +344,29 @@ public void testMergeIntoActionRequiresFullTableAccess(boolean dataEvolution) th .hasMessageContaining("MERGE INTO requires full-table access"); restCatalogServer.setRowFilterAuth(identifier, null); - if (!dataEvolution) { - // A rule added after the merge is built is checked when the job plans the target scan. - MergeIntoAction merge = (MergeIntoAction) mergeAction(false); + // A rule added after the merge is built is checked when the job plans the target scan. + Table table = flinkCatalog().catalog().getTable(identifier); + long snapshotId = table.latestSnapshot().get().id(); + StreamExecutionEnvironment env = singleParallelismEnv(); + ActionBase builtMerge = mergeAction(dataEvolution).withStreamExecutionEnvironment(env); + ThrowingCallable runJob; + if (dataEvolution) { + // the source reads the target through its row tracking table + ((DataEvolutionMergeIntoAction) builtMerge) + .buildSource() + .f0 + .sinkTo(new DiscardingSink<>()); + runJob = env::execute; + } else { + MergeIntoAction merge = (MergeIntoAction) builtMerge; DataStream dataStream = merge.buildDataStream(); - Table table = flinkCatalog().catalog().getTable(identifier); - long snapshotId = table.latestSnapshot().get().id(); - restCatalogServer.setRowFilterAuth( - identifier, equalTo(0, "id", DataTypes.STRING(), "visible")); - assertThatThrownBy(() -> merge.batchSink(dataStream).await()) - .hasStackTraceContaining("MERGE INTO requires full-table access"); - assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); - restCatalogServer.setRowFilterAuth(identifier, null); + runJob = () -> merge.batchSink(dataStream).await(); } + restCatalogServer.setRowFilterAuth( + identifier, equalTo(0, "id", DataTypes.STRING(), "visible")); + assertThatThrownBy(runJob).hasStackTraceContaining("MERGE INTO requires full-table access"); + assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); + restCatalogServer.setRowFilterAuth(identifier, null); ActionBase merge = mergeAction(dataEvolution); if (!dataEvolution) { // The Data Evolution merge already reads the target with an OPTIONS hint. @@ -365,24 +379,32 @@ public void testMergeIntoActionRequiresFullTableAccess(boolean dataEvolution) th } @Test - public void testRewriteScanOptionReachesTableWithSpecialName() { - // The merge-into and delete actions mark their target scans with this table option. '+' - // is a regex metacharacter, so the name must be quoted when the option is matched. + public void testRewriteScanOptionReachesOnlyTheTargetBranch() { + // The merge-into and delete actions mark the scans of their target with this table option. + // '+' is a regex metacharacter, so the name must be quoted when the option is matched. String tableName = DATABASE_NAME + ".`t+1`"; batchSql( "CREATE TABLE " + tableName + " (id STRING, note STRING) WITH ('query-auth.enabled'='true'," + " 'primary-key'='id', 'bucket'='1')"); - batchSql("INSERT INTO " + tableName + " VALUES ('a', 'original')"); + batchSql("INSERT INTO " + tableName + " VALUES ('a', 'original'), ('b', 'original')"); + batchSql("CALL sys.create_branch('" + DATABASE_NAME + ".t+1', 'source')"); tEnv.getConfig() .getConfiguration() .setString( - String.format( - "paimon.PAIMON.%s.t+1.%s", - DATABASE_NAME, CoreOptions.SCAN_REWRITE_OPERATION.key()), + TableActionBase.rewriteOperationOptionKey( + "PAIMON", Identifier.create(DATABASE_NAME, "t+1")), "DELETE"); - assertThat(batchSql("SELECT * FROM " + tableName)).containsExactly(Row.of("a", "original")); + assertThat(batchSql("SELECT * FROM " + tableName)) + .containsExactlyInAnyOrder(Row.of("a", "original"), Row.of("b", "original")); + + // Another branch, such as a source of the rewrite, keeps its own rules. + Identifier source = Identifier.create(DATABASE_NAME, "t+1$branch_source"); + restCatalogServer.setRowFilterAuth(source, equalTo(0, "id", DataTypes.STRING(), "a")); + assertThat(batchSql("SELECT * FROM " + DATABASE_NAME + ".`t+1$branch_source`")) + .containsExactly(Row.of("a", "original")); + restCatalogServer.setRowFilterAuth(source, null); Identifier identifier = Identifier.create(DATABASE_NAME, "t+1"); restCatalogServer.setColumnMaskingAuth(identifier, mask("note", "****")); @@ -429,6 +451,57 @@ public void testDeleteActionRequiresFullTableAccess(boolean dataEvolution, boole assertThat(batchSql("SELECT * FROM " + tableName)).isEmpty(); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void testDeleteActionChecksTargetScanAfterItStarts(boolean dataEvolution) + throws Exception { + String tableName = DATABASE_NAME + ".t_delete_late"; + createAuthTable("t_delete_late", "(id STRING, note STRING)", dataEvolution, "id"); + batchSql("INSERT INTO " + tableName + " VALUES ('a', 'original'), ('b', 'original')"); + Identifier identifier = Identifier.create(DATABASE_NAME, "t_delete_late"); + // The source SQL runs after the action checked query auth and before it scans the target. + ChangeAuthRules.change = + () -> restCatalogServer.setColumnMaskingAuth(identifier, mask("id", "****")); + try { + DeleteAction delete = + new DeleteAction(DATABASE_NAME, "t_delete_late", "TRUE", catalogOptions()) + .withSourceSqls( + "CREATE TEMPORARY SYSTEM FUNCTION change_auth_rules AS '" + + ChangeAuthRules.class.getName() + + "'", + "CREATE TEMPORARY TABLE " + + DATABASE_NAME + + ".rules_changed (x INT) WITH ('connector'='blackhole')", + "INSERT INTO " + + DATABASE_NAME + + ".rules_changed SELECT change_auth_rules()"); + delete.withStreamExecutionEnvironment(singleParallelismEnv()); + assertThatThrownBy(delete::run) + .hasStackTraceContaining("DELETE requires full-table access"); + } finally { + ChangeAuthRules.change = null; + restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); + } + assertThat(batchSql("SELECT * FROM " + tableName)) + .containsExactlyInAnyOrder(Row.of("a", "original"), Row.of("b", "original")); + } + + /** Changes the query auth rules when a source SQL of an action calls it. */ + public static class ChangeAuthRules extends ScalarFunction { + + static volatile Runnable change; + + public Integer eval() { + change.run(); + return 1; + } + + @Override + public boolean isDeterministic() { + return false; + } + } + /** Creates a table with query auth, a Data Evolution table or one with the primary key. */ private void createAuthTable( String name, String schema, boolean dataEvolution, @Nullable String primaryKey) { From aacd8d1b00a9e2283af490e257da3a9ee92e47bc Mon Sep 17 00:00:00 2001 From: Li Jiajia Date: Mon, 23 Nov 2026 08:13:58 -0800 Subject: [PATCH 10/10] [core][spark][flink] Authorize rewrites again before they commit The rewrites checked query auth when they were planned or built, and the sort compaction, rescale, merge-into and delete actions also marked the scan of their target so that it checked the rules it planned with. That covered only the reads that Paimon builds: the reads of Flink SQL UPDATE / DELETE and of Spark are planned by the engine, and the marker needed dynamic table options, quoted names and branch scoping in the Flink table factory. The rewrites now write through a copy of the target with an internal commit.rewrite-operation option instead, and TableCommitImpl authorizes again before each commit and truncation of such a table. A rule that the read applied was added before the read, so it is seen before anything is written, wherever the read is planned and also when an overwrite has nothing to write. A delegated table, such as one with a fallback branch, authorizes as a whole. This covers the Flink actions, the Flink SQL row-level sink, the Spark row-level commands, the Spark V2 row-level operations and chain table compaction in both engines. The scan marker and the table factory changes are removed. Co-Authored-By: Claude Opus 5.5 --- .../java/org/apache/paimon/CoreOptions.java | 12 +- .../paimon/catalog/TableQueryAuthResult.java | 23 ++- .../paimon/table/AbstractFileStoreTable.java | 31 ++-- .../paimon/table/DelegatedFileStoreTable.java | 10 +- .../paimon/table/sink/TableCommitImpl.java | 17 +++ .../table/source/AbstractDataTableScan.java | 5 - .../paimon/rest/MockRESTCatalogTest.java | 55 +++++++ .../flink/AbstractFlinkTableFactory.java | 32 ++-- .../flink/action/CompactChainTableAction.java | 13 +- .../action/DataEvolutionMergeIntoAction.java | 6 +- .../paimon/flink/action/DeleteAction.java | 6 +- .../paimon/flink/action/MergeIntoAction.java | 6 +- .../paimon/flink/action/RescaleAction.java | 14 +- .../flink/action/SortCompactAction.java | 13 +- .../paimon/flink/action/TableActionBase.java | 29 ---- ...pportsRowLevelOperationFlinkTableSink.java | 20 ++- .../flink/AbstractFlinkTableFactoryTest.java | 56 ------- .../paimon/flink/RESTCatalogITCase.java | 138 ++++++++---------- .../MergeIntoPaimonDataEvolutionTable.scala | 4 +- .../spark/commands/MergeIntoPaimonTable.scala | 4 +- .../procedure/CompactChainTableProcedure.java | 11 +- .../org/apache/paimon/spark/SparkTable.scala | 10 +- .../DeleteFromPaimonTableCommand.scala | 4 +- .../MergeIntoPaimonDataEvolutionTable.scala | 4 +- .../spark/commands/MergeIntoPaimonTable.scala | 4 +- .../commands/PaimonRowLevelCommand.scala | 11 +- .../commands/UpdatePaimonTableCommand.scala | 4 +- .../spark/SparkCatalogWithRestTest.java | 47 ++++++ 28 files changed, 336 insertions(+), 253 deletions(-) diff --git a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java index c07f53494b42..94a2a53f2c98 100644 --- a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java +++ b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java @@ -2482,13 +2482,13 @@ public String toString() { + "column level and row level permission validation on queries."); @ExcludeFromDocumentation("Internal use only") - public static final ConfigOption SCAN_REWRITE_OPERATION = - key("scan.rewrite-operation") + public static final ConfigOption COMMIT_REWRITE_OPERATION = + key("commit.rewrite-operation") .stringType() .noDefaultValue() .withDescription( - "The rewrite that reads the table with this scan. The scan fails " - + "when query auth returns row filters or column masks."); + "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 MATERIALIZED_TABLE_DEFINITION_QUERY = @@ -3872,8 +3872,8 @@ public boolean queryAuthEnabled() { } @Nullable - public String scanRewriteOperation() { - return options.get(SCAN_REWRITE_OPERATION); + public String commitRewriteOperation() { + return options.get(COMMIT_REWRITE_OPERATION); } public boolean ignoreDelete() { diff --git a/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java b/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java index 7f1312ccd545..5b9a1f4f1508 100644 --- a/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java +++ b/paimon-core/src/main/java/org/apache/paimon/catalog/TableQueryAuthResult.java @@ -147,6 +147,27 @@ 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. @@ -180,7 +201,7 @@ public static void rejectRewriteUnderQueryAuth(@Nullable Table table, String ope } } - public static void rejectRewriteUnderQueryAuthRules( + private static void rejectRewriteUnderQueryAuthRules( @Nullable TableQueryAuthResult authResult, String operation) { if (authResult != null && authResult.hasRules()) { throw new UnsupportedOperationException( diff --git a/paimon-core/src/main/java/org/apache/paimon/table/AbstractFileStoreTable.java b/paimon-core/src/main/java/org/apache/paimon/table/AbstractFileStoreTable.java index ec8b71a8c4c1..c73f94cb846b 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/AbstractFileStoreTable.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/AbstractFileStoreTable.java @@ -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 { @@ -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 diff --git a/paimon-core/src/main/java/org/apache/paimon/table/DelegatedFileStoreTable.java b/paimon-core/src/main/java/org/apache/paimon/table/DelegatedFileStoreTable.java index ed541721fca0..00685bb6b24e 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/DelegatedFileStoreTable.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/DelegatedFileStoreTable.java @@ -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 { @@ -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 diff --git a/paimon-core/src/main/java/org/apache/paimon/table/sink/TableCommitImpl.java b/paimon-core/src/main/java/org/apache/paimon/table/sink/TableCommitImpl.java index ac41312b2fcb..6656eb6c771c 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/sink/TableCommitImpl.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/sink/TableCommitImpl.java @@ -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; @@ -219,15 +220,29 @@ public void commit(List 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> partitionSpecs) { + checkBeforeCommit(); commit.withOperation(Snapshot.Operation.TRUNCATE); commit.dropPartitions(partitionSpecs, COMMIT_IDENTIFIER); } @@ -235,6 +250,7 @@ public void truncatePartitions(List> partitionSpecs) { @Override public void truncatePartitions(PartitionPredicate partitionFilter) { checkNotNull(partitionFilter, "Partition filter cannot be null."); + checkBeforeCommit(); commit.withOperation(Snapshot.Operation.TRUNCATE); commit.dropPartitions(partitionFilter, COMMIT_IDENTIFIER); } @@ -296,6 +312,7 @@ public void commit(ManifestCommittable committable) { } public void commitMultiple(List committables, boolean checkAppendFiles) { + checkBeforeCommit(); if (overwritePartitionSpec == null && overwriteStaticPartitions == null) { int newSnapshots = 0; for (ManifestCommittable committable : committables) { diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java index e7d9fb424368..e126cd4a4094 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataTableScan.java @@ -316,11 +316,6 @@ protected TableQueryAuthResult authQuery() { select = new ArrayList<>(fields); } TableQueryAuthResult result = queryAuth.auth(select); - String rewriteOperation = options.scanRewriteOperation(); - if (rewriteOperation != null) { - // Checked before planning, so a rule that leaves no split still fails the rewrite. - TableQueryAuthResult.rejectRewriteUnderQueryAuthRules(result, rewriteOperation); - } if (result != null && result.hasRules()) { // re-validated every plan, so a schema change under a live scan fails closed RowType latestSchema = diff --git a/paimon-core/src/test/java/org/apache/paimon/rest/MockRESTCatalogTest.java b/paimon-core/src/test/java/org/apache/paimon/rest/MockRESTCatalogTest.java index ecf653f58c0f..58975a3794c1 100644 --- a/paimon-core/src/test/java/org/apache/paimon/rest/MockRESTCatalogTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/rest/MockRESTCatalogTest.java @@ -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; @@ -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; @@ -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 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> receivedHeaders = restCatalogServer.getReceivedHeaders(); diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/AbstractFlinkTableFactory.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/AbstractFlinkTableFactory.java index e3c6fef8fc15..10b7e2928f17 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/AbstractFlinkTableFactory.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/AbstractFlinkTableFactory.java @@ -307,8 +307,7 @@ static boolean schemaEquals(RowType rowType1, RowType rowType2) { * *

Table Options: {@link * FlinkConnectorOptions#TABLE_DYNAMIC_OPTION_PREFIX}${catalog}.${database}.${tableName}.key = - * value. The table name may also be qualified with a branch, see {@link - * #branchQualifiedTableName}, to give the options only to that branch and its system tables. + * value. * *

These job level options will be extracted and injected into the target table option. Table * options will override global options if there are conflicts. @@ -319,19 +318,17 @@ static boolean schemaEquals(RowType rowType1, RowType rowType2) { static Map getDynamicConfigOptions(DynamicTableFactory.Context context) { Map conf = getAllOptions(context); ObjectIdentifier identifier = context.getObjectIdentifier(); - Identifier paimonIdentifier = - new Identifier(identifier.getDatabaseName(), identifier.getObjectName()); - String tableName = paimonIdentifier.getTableName(); + String tableName = + new Identifier(identifier.getDatabaseName(), identifier.getObjectName()) + .getTableName(); - // Quote the names, which may contain regex metacharacters, such as '+' in `t+1`. String template = String.format( - "(%s)(%s|\\*)\\.(%s|\\*)\\.(%s|%s|\\*)\\.(.+)", - Pattern.quote(FlinkConnectorOptions.TABLE_DYNAMIC_OPTION_PREFIX), - Pattern.quote(identifier.getCatalogName()), - Pattern.quote(identifier.getDatabaseName()), - Pattern.quote(branchQualifiedTableName(paimonIdentifier)), - Pattern.quote(tableName)); + "(%s)(%s|\\*)\\.(%s|\\*)\\.(%s|\\*)\\.(.+)", + FlinkConnectorOptions.TABLE_DYNAMIC_OPTION_PREFIX, + identifier.getCatalogName(), + identifier.getDatabaseName(), + tableName); Pattern pattern = Pattern.compile(template); Map optionsFromTableConfig = OptionsUtils.convertToDynamicTableProperties(conf, "", pattern, 5); @@ -345,17 +342,6 @@ static Map getDynamicConfigOptions(DynamicTableFactory.Context c return optionsFromTableConfig; } - /** - * The table name with the branch of {@code identifier}, such as {@code t$branch_main} for - * {@code t} and {@code t$row_tracking}, and {@code t$branch_b} for {@code t$branch_b}. - */ - public static String branchQualifiedTableName(Identifier identifier) { - return identifier.getTableName() - + Identifier.SYSTEM_TABLE_SPLITTER - + Identifier.SYSTEM_BRANCH_PREFIX - + identifier.getBranchNameOrDefault(); - } - public static Map getAllOptions(DynamicTableFactory.Context context) { ReadableConfig config = context.getConfiguration(); if (config instanceof Configuration) { diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/CompactChainTableAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/CompactChainTableAction.java index 402737327d49..6721de5dbb0b 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/CompactChainTableAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/CompactChainTableAction.java @@ -44,6 +44,7 @@ import java.util.Map; import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuthOnCommit; import static org.apache.paimon.flink.FlinkConnectorOptions.SCAN_DEDICATED_SPLIT_GENERATION; import static org.apache.paimon.utils.Preconditions.checkArgument; @@ -144,10 +145,14 @@ public void build() throws Exception { FlinkSinkBuilder sinkBuilder = new FlinkSinkBuilder( - snapshotTable.copy( - Collections.singletonMap( - CoreOptions.DYNAMIC_PARTITION_OVERWRITE.key(), - "true"))) + // authorizes again before the commit + rejectRewriteUnderQueryAuthOnCommit( + snapshotTable.copy( + Collections.singletonMap( + CoreOptions.DYNAMIC_PARTITION_OVERWRITE + .key(), + "true")), + "Chain table compaction")) .forRowData(source); if (partitionExists) { sinkBuilder.overwrite(partitionSpec); diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java index 9ef7006760ff..cf9a54ff0301 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DataEvolutionMergeIntoAction.java @@ -87,7 +87,7 @@ import java.util.function.Function; import java.util.stream.Collectors; -import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuthOnCommit; import static org.apache.paimon.format.blob.BlobFileFormat.isBlobFile; import static org.apache.paimon.utils.ParameterUtils.parseCommaSeparatedKeyValues; @@ -257,8 +257,8 @@ public TableResult runInternal() { } public Tuple2, RowType> buildSource() { - rejectRewriteUnderQueryAuth(table, "MERGE INTO"); - checkQueryAuthWhenScanningTarget("MERGE INTO"); + // The job commits through this copy, which authorizes again before the commit. + table = rejectRewriteUnderQueryAuthOnCommit(table, "MERGE INTO"); if (targetTableName().equals(sourceTableName())) { throw new RuntimeException( String.format( diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java index 5b75e417dd60..6b9ce9d35763 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/DeleteAction.java @@ -39,7 +39,7 @@ import java.util.stream.Collectors; import static org.apache.paimon.CoreOptions.MergeEngine.DEDUPLICATE; -import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuthOnCommit; /** Delete from table action for Flink, dispatching by table type. */ public class DeleteAction extends TableActionBase { @@ -87,8 +87,8 @@ public DeleteAction withSinkParallelism(int sinkParallelism) { @Override public void run() throws Exception { - rejectRewriteUnderQueryAuth(table, "DELETE"); - checkQueryAuthWhenScanningTarget("DELETE"); + // The job commits through this copy, which authorizes again before the commit. + table = rejectRewriteUnderQueryAuthOnCommit(table, "DELETE"); handleSqls(); if (dataEvolutionDelete != null) { dataEvolutionDelete.runInternal().await(); diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java index 1fc79d86cd4d..1de1032ac558 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/MergeIntoAction.java @@ -48,7 +48,7 @@ import static org.apache.paimon.CoreOptions.MergeEngine.DEDUPLICATE; import static org.apache.paimon.CoreOptions.MergeEngine.PARTIAL_UPDATE; -import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuthOnCommit; import static org.apache.paimon.utils.ParameterUtils.parseCommaSeparatedKeyValues; /** @@ -254,8 +254,8 @@ public void run() throws Exception { } public DataStream buildDataStream() { - rejectRewriteUnderQueryAuth(table, "MERGE INTO"); - checkQueryAuthWhenScanningTarget("MERGE INTO"); + // The job commits through this copy, which authorizes again before the commit. + table = rejectRewriteUnderQueryAuthOnCommit(table, "MERGE INTO"); // handle aliases handleTargetAlias(); diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java index 993c978d37e0..f55db11c8774 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/RescaleAction.java @@ -36,13 +36,12 @@ import javax.annotation.Nullable; -import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Optional; -import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuthOnCommit; /** Action to rescale one partition of a table. */ public class RescaleAction extends TableActionBase { @@ -78,12 +77,13 @@ public RescaleAction withSinkParallelism(int sinkParallelism) { @Override public void build() throws Exception { - rejectRewriteUnderQueryAuth(table, "Rescale"); Configuration flinkConf = new Configuration(); flinkConf.set(ExecutionOptions.RUNTIME_MODE, RuntimeExecutionMode.BATCH); env.configure(flinkConf); - FileStoreTable fileStoreTable = (FileStoreTable) table; + // The job commits through this copy, which authorizes again before the commit. + FileStoreTable fileStoreTable = + rejectRewriteUnderQueryAuthOnCommit((FileStoreTable) table, "Rescale"); Optional optionalSnapshot = fileStoreTable.latestSnapshot(); if (!optionalSnapshot.isPresent()) { throw new IllegalArgumentException( @@ -105,11 +105,7 @@ public void build() throws Exception { fileStoreTable.coreOptions().partitionDefaultName()); DataStream source = - new FlinkSourceBuilder( - fileStoreTable.copy( - Collections.singletonMap( - CoreOptions.SCAN_REWRITE_OPERATION.key(), - "Rescale"))) + new FlinkSourceBuilder(fileStoreTable) .env(env) .sourceBounded(true) .sourceParallelism( diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java index 3c6ab3035b27..f84e91d486e5 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/SortCompactAction.java @@ -42,7 +42,7 @@ import java.util.Map; import java.util.stream.Collectors; -import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuthOnCommit; /** Compact with sort action. */ public class SortCompactAction extends CompactAction { @@ -69,7 +69,6 @@ public void run() throws Exception { @Override public void build() throws Exception { - rejectRewriteUnderQueryAuth(table, "Sort compaction"); if (bucketsSpecified()) { throw new IllegalArgumentException( "Specifying buckets is not supported for sort compact."); @@ -81,7 +80,9 @@ public void build() throws Exception { "Sort Compact only support batch mode yet. Please add -Dexecution.runtime-mode=BATCH. The action this time will shift to batch mode forcely."); env.setRuntimeMode(RuntimeExecutionMode.BATCH); } - FileStoreTable fileStoreTable = (FileStoreTable) table; + // The job commits through this copy, which authorizes again before the commit. + FileStoreTable fileStoreTable = + rejectRewriteUnderQueryAuthOnCommit((FileStoreTable) table, "Sort compaction"); if (fileStoreTable.coreOptions().dataEvolutionEnabled()) { throw new UnsupportedOperationException("Data Evolution table cannot be sorted!"); @@ -93,11 +94,7 @@ public void build() throws Exception { } Map tableConfig = fileStoreTable.options(); FlinkSourceBuilder sourceBuilder = - new FlinkSourceBuilder( - fileStoreTable.copy( - Collections.singletonMap( - CoreOptions.SCAN_REWRITE_OPERATION.key(), - "Sort compaction"))) + new FlinkSourceBuilder(fileStoreTable) .sourceName( ObjectIdentifier.of( catalogName, diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/TableActionBase.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/TableActionBase.java index 2e24e3746c9f..aa977a9e2bcb 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/TableActionBase.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/action/TableActionBase.java @@ -18,17 +18,12 @@ package org.apache.paimon.flink.action; -import org.apache.paimon.CoreOptions; -import org.apache.paimon.annotation.VisibleForTesting; import org.apache.paimon.catalog.Catalog; import org.apache.paimon.catalog.Identifier; -import org.apache.paimon.flink.AbstractFlinkTableFactory; -import org.apache.paimon.flink.FlinkConnectorOptions; import org.apache.paimon.flink.sink.FlinkSinkBuilder; import org.apache.paimon.table.Table; import org.apache.flink.api.dag.Transformation; -import org.apache.flink.configuration.ConfigOptions; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.table.api.TableResult; import org.apache.flink.table.api.bridge.java.StreamTableEnvironment; @@ -57,30 +52,6 @@ public abstract class TableActionBase extends ActionBase { } /** Sink {@link DataStream} dataStream to table with Flink Table API in batch environment. */ - /** - * Makes the scans of the target in this action fail when the query auth result they plan with - * has rules, so a rule added after the action is built is not applied to the rewrite. The - * option is passed as a table option in the table config of this action, which does not need - * dynamic table options to be enabled. It is qualified with the branch of the target, so it - * reaches the target and its row tracking table, but not a source on another branch. - */ - protected void checkQueryAuthWhenScanningTarget(String operation) { - String key = rewriteOperationOptionKey(catalogName, identifier); - batchTEnv.getConfig().set(ConfigOptions.key(key).stringType().noDefaultValue(), operation); - } - - /** The table config key that gives the target scans the rewrite operation. */ - @VisibleForTesting - public static String rewriteOperationOptionKey(String catalogName, Identifier identifier) { - return String.format( - "%s%s.%s.%s.%s", - FlinkConnectorOptions.TABLE_DYNAMIC_OPTION_PREFIX, - catalogName, - identifier.getDatabaseName(), - AbstractFlinkTableFactory.branchQualifiedTableName(identifier), - CoreOptions.SCAN_REWRITE_OPERATION.key()); - } - public TableResult batchSink(DataStream dataStream) { List> transformations = Collections.singletonList( diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/SupportsRowLevelOperationFlinkTableSink.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/SupportsRowLevelOperationFlinkTableSink.java index 142bb160dde6..5559b10a92a9 100644 --- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/SupportsRowLevelOperationFlinkTableSink.java +++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/SupportsRowLevelOperationFlinkTableSink.java @@ -67,6 +67,7 @@ import static org.apache.paimon.CoreOptions.MergeEngine.DEDUPLICATE; import static org.apache.paimon.CoreOptions.MergeEngine.PARTIAL_UPDATE; import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuthOnCommit; import static org.apache.paimon.table.PrimaryKeyTableUtils.validatePKUpsertDeletable; import static org.apache.paimon.utils.Preconditions.checkArgument; @@ -76,6 +77,8 @@ public abstract class SupportsRowLevelOperationFlinkTableSink extends FlinkTable @Nullable protected Predicate deletePredicate; @Nullable protected Long dataEvolutionDeleteSnapshotId; + // the row-level operation the sink writes, authorized again before the commit + @Nullable protected String rewriteOperation; public SupportsRowLevelOperationFlinkTableSink( ObjectIdentifier tableIdentifier, Table table, DynamicTableFactory.Context context) { @@ -90,6 +93,7 @@ public DynamicTableSink copy() { copied.rowLevelUpdate = rowLevelUpdate; copied.deletePredicate = deletePredicate; copied.dataEvolutionDeleteSnapshotId = dataEvolutionDeleteSnapshotId; + copied.rewriteOperation = rewriteOperation; return copied; } @@ -97,6 +101,7 @@ public DynamicTableSink copy() { public RowLevelUpdateInfo applyRowLevelUpdate( List updatedColumns, @Nullable RowLevelModificationScanContext context) { rejectRewriteUnderQueryAuth(table, "UPDATE"); + rewriteOperation = "UPDATE"; rowLevelUpdate = true; // Since only UPDATE_AFTER type messages can be received at present, // AppendOnlyFileStoreTable cannot correctly handle old data, so they are marked as @@ -145,6 +150,7 @@ public RowLevelUpdateInfo applyRowLevelUpdate( public RowLevelDeleteInfo applyRowLevelDelete( @Nullable RowLevelModificationScanContext rowLevelModificationScanContext) { rejectRewriteUnderQueryAuth(table, "DELETE"); + rewriteOperation = "DELETE"; if (isDataEvolutionTable()) { FileStoreTable fileStoreTable = (FileStoreTable) table; DataEvolutionDeleteSink.validateTable(fileStoreTable); @@ -208,7 +214,7 @@ public SinkRuntimeProvider getSinkRuntimeProvider(Context context) { "Data Evolution DELETE only supports batch mode."); } - FileStoreTable fileStoreTable = (FileStoreTable) table; + FileStoreTable fileStoreTable = (FileStoreTable) writeTable(); int sinkParallelism = Options.fromMap(table.options()) .getOptional(FlinkConnectorOptions.SINK_PARALLELISM) @@ -227,6 +233,18 @@ public SinkRuntimeProvider getSinkRuntimeProvider(Context context) { table); } + @Override + protected FlinkSinkBuilder createSinkBuilder() { + return new FlinkSinkBuilder(writeTable()); + } + + /** The table to write, whose commits authorize again for a row-level operation. */ + private Table writeTable() { + return rewriteOperation == null + ? table + : rejectRewriteUnderQueryAuthOnCommit(table, rewriteOperation); + } + @Override public Optional executeDeletion() { try (BatchTableCommit commit = table.newBatchWriteBuilder().newCommit()) { diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/AbstractFlinkTableFactoryTest.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/AbstractFlinkTableFactoryTest.java index 2a3d564f27b1..38d48fa21d2d 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/AbstractFlinkTableFactoryTest.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/AbstractFlinkTableFactoryTest.java @@ -94,62 +94,6 @@ public void testGetDynamicOptions() { assertThat(options).isEqualTo(ImmutableMap.of("k1", "v1", "k2", "v2", "k3", "v3")); } - @Test - public void testGetDynamicOptionsForNamesWithRegexMetacharacters() { - Configuration configuration = new Configuration(); - configuration.setString("paimon.paimon-1.db+.t+1.k1", "v1"); - configuration.setString("paimon.*.db+.t+1.k2", "v2"); - // '.' and '+' in the names are not regex wildcards or quantifiers - configuration.setString("paimon.paimon-1.dbb.t+1.k3", "v3"); - configuration.setString("paimon.paimon-1.db+.tt1.k4", "v4"); - DynamicTableFactory.Context context = - new FactoryUtil.DefaultDynamicTableContext( - ObjectIdentifier.of("paimon-1", "db+", "t+1"), - null, - new HashMap<>(), - configuration, - AbstractFlinkTableFactoryTest.class.getClassLoader(), - false); - Map options = AbstractFlinkTableFactory.getDynamicConfigOptions(context); - assertThat(options).containsEntry("k1", "v1").containsEntry("k2", "v2"); - assertThat(options).doesNotContainKeys("k3", "k4"); - } - - @Test - public void testGetDynamicOptionsForBranchQualifiedTableName() { - Configuration configuration = new Configuration(); - configuration.setString("paimon.c.db.t.k1", "v1"); - configuration.setString("paimon.c.db.t$branch_main.k2", "v2"); - configuration.setString("paimon.c.db.t$branch_b.k3", "v3"); - assertThat(dynamicOptions(configuration, "t")) - .containsEntry("k1", "v1") - .containsEntry("k2", "v2") - .doesNotContainKey("k3"); - // a system table gets the options of its branch - assertThat(dynamicOptions(configuration, "t$row_tracking")) - .containsEntry("k1", "v1") - .containsEntry("k2", "v2") - .doesNotContainKey("k3"); - assertThat(dynamicOptions(configuration, "t$branch_b")) - .containsEntry("k1", "v1") - .containsEntry("k3", "v3") - .doesNotContainKey("k2"); - assertThat(dynamicOptions(configuration, "t$branch_b$row_tracking")) - .containsEntry("k3", "v3") - .doesNotContainKey("k2"); - } - - private static Map dynamicOptions(Configuration configuration, String table) { - return AbstractFlinkTableFactory.getDynamicConfigOptions( - new FactoryUtil.DefaultDynamicTableContext( - ObjectIdentifier.of("c", "db", table), - null, - new HashMap<>(), - configuration, - AbstractFlinkTableFactoryTest.class.getClassLoader(), - false)); - } - private void innerTest(RowType r1, RowType r2, boolean expectEquals) { assertThat(AbstractFlinkTableFactory.schemaEquals(r1, r2)).isEqualTo(expectEquals); } diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java index 44f309f81369..f0cb08f6716e 100644 --- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java +++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/RESTCatalogITCase.java @@ -28,7 +28,6 @@ import org.apache.paimon.flink.action.MergeIntoAction; import org.apache.paimon.flink.action.RescaleAction; import org.apache.paimon.flink.action.SortCompactAction; -import org.apache.paimon.flink.action.TableActionBase; import org.apache.paimon.partition.Partition; import org.apache.paimon.predicate.ConcatTransform; import org.apache.paimon.predicate.ConcatWsTransform; @@ -57,20 +56,16 @@ import org.apache.flink.api.common.RuntimeExecutionMode; import org.apache.flink.configuration.ConfigOptions; import org.apache.flink.configuration.Configuration; -import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; -import org.apache.flink.streaming.api.functions.sink.v2.DiscardingSink; import org.apache.flink.table.catalog.Catalog; import org.apache.flink.table.catalog.CatalogFunction; import org.apache.flink.table.catalog.CatalogFunctionImpl; import org.apache.flink.table.catalog.FunctionLanguage; import org.apache.flink.table.catalog.ObjectPath; -import org.apache.flink.table.data.RowData; import org.apache.flink.table.functions.ScalarFunction; import org.apache.flink.table.resource.ResourceType; import org.apache.flink.table.resource.ResourceUri; import org.apache.flink.types.Row; -import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -318,6 +313,29 @@ public void testRowLevelOperationsRequireFullTableAccess( assertThat(batchSql("SELECT note FROM " + tableName)) .extracting(row -> row.getField(0)) .containsExactlyInAnyOrder("s1", "s2"); + + // A rule added while the update runs is checked before it commits. + batchSql( + "CREATE TEMPORARY SYSTEM FUNCTION change_auth_rules AS '" + + ChangeAuthRules.class.getName() + + "'"); + ChangeAuthRules.change = + () -> restCatalogServer.setColumnMaskingAuth(identifier, mask("ssn", "****")); + try { + assertThatThrownBy( + () -> + batchSql( + "UPDATE " + + tableName + + " SET note = change_auth_rules(note)")) + .hasStackTraceContaining("UPDATE requires full-table access"); + } finally { + ChangeAuthRules.change = null; + restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); + } + assertThat(batchSql("SELECT note FROM " + tableName)) + .extracting(row -> row.getField(0)) + .containsExactlyInAnyOrder("s1", "s2"); } batchSql("DELETE FROM " + tableName + " WHERE id = 2"); assertThat(batchSql("SELECT id FROM " + tableName)) @@ -344,29 +362,22 @@ public void testMergeIntoActionRequiresFullTableAccess(boolean dataEvolution) th .hasMessageContaining("MERGE INTO requires full-table access"); restCatalogServer.setRowFilterAuth(identifier, null); - // A rule added after the merge is built is checked when the job plans the target scan. + // A rule added while the merge runs, here by its source SQL, is checked before it commits. Table table = flinkCatalog().catalog().getTable(identifier); long snapshotId = table.latestSnapshot().get().id(); - StreamExecutionEnvironment env = singleParallelismEnv(); - ActionBase builtMerge = mergeAction(dataEvolution).withStreamExecutionEnvironment(env); - ThrowingCallable runJob; - if (dataEvolution) { - // the source reads the target through its row tracking table - ((DataEvolutionMergeIntoAction) builtMerge) - .buildSource() - .f0 - .sinkTo(new DiscardingSink<>()); - runJob = env::execute; - } else { - MergeIntoAction merge = (MergeIntoAction) builtMerge; - DataStream dataStream = merge.buildDataStream(); - runJob = () -> merge.batchSink(dataStream).await(); + // The rule leaves the row the merge updates, so the merge still writes. + ChangeAuthRules.change = + () -> + restCatalogServer.setRowFilterAuth( + identifier, equalTo(0, "id", DataTypes.STRING(), "hidden")); + try { + assertThatThrownBy(mergeAction(dataEvolution, changeAuthRulesSqls())::run) + .hasStackTraceContaining("MERGE INTO requires full-table access"); + } finally { + ChangeAuthRules.change = null; + restCatalogServer.setRowFilterAuth(identifier, null); } - restCatalogServer.setRowFilterAuth( - identifier, equalTo(0, "id", DataTypes.STRING(), "visible")); - assertThatThrownBy(runJob).hasStackTraceContaining("MERGE INTO requires full-table access"); assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); - restCatalogServer.setRowFilterAuth(identifier, null); ActionBase merge = mergeAction(dataEvolution); if (!dataEvolution) { // The Data Evolution merge already reads the target with an OPTIONS hint. @@ -378,41 +389,6 @@ public void testMergeIntoActionRequiresFullTableAccess(boolean dataEvolution) th .containsExactly("merged", "original"); } - @Test - public void testRewriteScanOptionReachesOnlyTheTargetBranch() { - // The merge-into and delete actions mark the scans of their target with this table option. - // '+' is a regex metacharacter, so the name must be quoted when the option is matched. - String tableName = DATABASE_NAME + ".`t+1`"; - batchSql( - "CREATE TABLE " - + tableName - + " (id STRING, note STRING) WITH ('query-auth.enabled'='true'," - + " 'primary-key'='id', 'bucket'='1')"); - batchSql("INSERT INTO " + tableName + " VALUES ('a', 'original'), ('b', 'original')"); - batchSql("CALL sys.create_branch('" + DATABASE_NAME + ".t+1', 'source')"); - tEnv.getConfig() - .getConfiguration() - .setString( - TableActionBase.rewriteOperationOptionKey( - "PAIMON", Identifier.create(DATABASE_NAME, "t+1")), - "DELETE"); - assertThat(batchSql("SELECT * FROM " + tableName)) - .containsExactlyInAnyOrder(Row.of("a", "original"), Row.of("b", "original")); - - // Another branch, such as a source of the rewrite, keeps its own rules. - Identifier source = Identifier.create(DATABASE_NAME, "t+1$branch_source"); - restCatalogServer.setRowFilterAuth(source, equalTo(0, "id", DataTypes.STRING(), "a")); - assertThat(batchSql("SELECT * FROM " + DATABASE_NAME + ".`t+1$branch_source`")) - .containsExactly(Row.of("a", "original")); - restCatalogServer.setRowFilterAuth(source, null); - - Identifier identifier = Identifier.create(DATABASE_NAME, "t+1"); - restCatalogServer.setColumnMaskingAuth(identifier, mask("note", "****")); - assertThatThrownBy(() -> batchSql("SELECT * FROM " + tableName)) - .hasStackTraceContaining("DELETE requires full-table access"); - restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); - } - @ParameterizedTest @CsvSource({"false,false", "false,true", "true,false", "true,true"}) public void testDeleteActionRequiresFullTableAccess(boolean dataEvolution, boolean filterAll) @@ -459,22 +435,13 @@ public void testDeleteActionChecksTargetScanAfterItStarts(boolean dataEvolution) createAuthTable("t_delete_late", "(id STRING, note STRING)", dataEvolution, "id"); batchSql("INSERT INTO " + tableName + " VALUES ('a', 'original'), ('b', 'original')"); Identifier identifier = Identifier.create(DATABASE_NAME, "t_delete_late"); - // The source SQL runs after the action checked query auth and before it scans the target. + // The source SQL runs after the action checked query auth; the commit checks again. ChangeAuthRules.change = () -> restCatalogServer.setColumnMaskingAuth(identifier, mask("id", "****")); try { DeleteAction delete = new DeleteAction(DATABASE_NAME, "t_delete_late", "TRUE", catalogOptions()) - .withSourceSqls( - "CREATE TEMPORARY SYSTEM FUNCTION change_auth_rules AS '" - + ChangeAuthRules.class.getName() - + "'", - "CREATE TEMPORARY TABLE " - + DATABASE_NAME - + ".rules_changed (x INT) WITH ('connector'='blackhole')", - "INSERT INTO " - + DATABASE_NAME - + ".rules_changed SELECT change_auth_rules()"); + .withSourceSqls(changeAuthRulesSqls()); delete.withStreamExecutionEnvironment(singleParallelismEnv()); assertThatThrownBy(delete::run) .hasStackTraceContaining("DELETE requires full-table access"); @@ -486,7 +453,20 @@ public void testDeleteActionChecksTargetScanAfterItStarts(boolean dataEvolution) .containsExactlyInAnyOrder(Row.of("a", "original"), Row.of("b", "original")); } - /** Changes the query auth rules when a source SQL of an action calls it. */ + /** Source SQLs of an action that change the query auth rules, see {@link ChangeAuthRules}. */ + private static String[] changeAuthRulesSqls() { + return new String[] { + "CREATE TEMPORARY SYSTEM FUNCTION change_auth_rules AS '" + + ChangeAuthRules.class.getName() + + "'", + "CREATE TEMPORARY TABLE " + + DATABASE_NAME + + ".rules_changed (x INT) WITH ('connector'='blackhole')", + "INSERT INTO " + DATABASE_NAME + ".rules_changed SELECT change_auth_rules()" + }; + } + + /** Changes the query auth rules when a SQL statement calls it. */ public static class ChangeAuthRules extends ScalarFunction { static volatile Runnable change; @@ -496,6 +476,11 @@ public Integer eval() { return 1; } + public String eval(String value) { + change.run(); + return value; + } + @Override public boolean isDeterministic() { return false; @@ -548,8 +533,10 @@ private static StreamExecutionEnvironment withoutDynamicTableOptions() { return StreamExecutionEnvironment.getExecutionEnvironment(conf).setParallelism(1); } - private ActionBase mergeAction(boolean dataEvolution) { - String sourceSql = + private ActionBase mergeAction(boolean dataEvolution, String... extraSourceSqls) { + String[] sourceSqls = new String[extraSourceSqls.length + 1]; + System.arraycopy(extraSourceSqls, 0, sourceSqls, 0, extraSourceSqls.length); + sourceSqls[extraSourceSqls.length] = "CREATE TEMPORARY VIEW " + DATABASE_NAME + ".S AS SELECT 'hidden' AS id, 'merged' AS note"; @@ -558,13 +545,13 @@ private ActionBase mergeAction(boolean dataEvolution) { dataEvolution ? new DataEvolutionMergeIntoAction( DATABASE_NAME, "t_merge", catalogOptions()) - .withSourceSqls(sourceSql) + .withSourceSqls(sourceSqls) .withSourceTable(DATABASE_NAME + ".S") .withMergeCondition(condition) .withMatchedUpdateSet("note = S.note") .withSinkParallelism(1) : new MergeIntoAction(DATABASE_NAME, "t_merge", catalogOptions()) - .withSourceSqls(sourceSql) + .withSourceSqls(sourceSqls) .withSourceTable(DATABASE_NAME + ".S") .withMergeCondition(condition) .withMatchedUpsert(null, "note = S.note"); @@ -687,6 +674,7 @@ public void testChainCompactionRequiresFullTableAccess() throws Exception { assertThat(table.latestSnapshot().get().id()).isEqualTo(snapshotId); restCatalogServer.setColumnMaskingAuth(chainIdentifier, Collections.emptyMap()); } + assertThatCode(action::run).doesNotThrowAnyException(); } diff --git a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala index b8abdc8ed90a..fd7691fe7afa 100644 --- a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala +++ b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala @@ -307,8 +307,10 @@ case class MergeIntoPaimonDataEvolutionTable( lazy val tableSchema: StructType = targetSparkTable.schema + override protected def rewriteOperation: String = "MERGE INTO" + override def run(sparkSession: SparkSession): Seq[Row] = { - rejectRewriteUnderQueryAuth(table, "MERGE INTO") + rejectRewriteUnderQueryAuth(table, rewriteOperation) // Persist the schema that the analyzer evolved in memory (commit deferred to execution). SchemaEvolutionHelper.commitEvolvedSchemaAtExecution(table, targetRelation, sparkSession) invokeMergeInto(sparkSession) diff --git a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala index d7d650e7de88..a252b639fa06 100644 --- a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala +++ b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala @@ -84,8 +84,10 @@ case class MergeIntoPaimonTable( .getOrElse(targetTable)) } + override protected def rewriteOperation: String = "MERGE INTO" + override def run(sparkSession: SparkSession): Seq[Row] = { - rejectRewriteUnderQueryAuth(table, "MERGE INTO") + rejectRewriteUnderQueryAuth(table, rewriteOperation) // Avoid that more than one source rows match the same target row. checkMatchRationality(sparkSession) // Persist the schema that the analyzer evolved in memory (commit deferred to execution). diff --git a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/CompactChainTableProcedure.java b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/CompactChainTableProcedure.java index 465a0f8f7913..3056f4c3f95e 100644 --- a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/CompactChainTableProcedure.java +++ b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/CompactChainTableProcedure.java @@ -49,6 +49,7 @@ import java.util.Map; import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth; +import static org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuthOnCommit; import static org.apache.paimon.utils.Preconditions.checkArgument; import static org.apache.spark.sql.types.DataTypes.BooleanType; import static org.apache.spark.sql.types.DataTypes.StringType; @@ -177,9 +178,13 @@ private boolean execute( // preserving other groups that have no delta data under the same partial partition. PaimonSparkWriter writer = PaimonSparkWriter.apply( - snapshotTable.copy( - Collections.singletonMap( - CoreOptions.DYNAMIC_PARTITION_OVERWRITE.key(), "true"))); + // authorizes again before the commit + rejectRewriteUnderQueryAuthOnCommit( + snapshotTable.copy( + Collections.singletonMap( + CoreOptions.DYNAMIC_PARTITION_OVERWRITE.key(), + "true")), + "Chain table compaction")); Map targetPartition = ParameterUtils.parseCommaSeparatedKeyValues(partitionStr); for (Map.Entry entry : targetPartition.entrySet()) { diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkTable.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkTable.scala index 3d7794c080fa..9096a631674c 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkTable.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkTable.scala @@ -18,7 +18,7 @@ package org.apache.paimon.spark -import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuth +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuthOnCommit import org.apache.paimon.spark.read.ObjectTableScanBuilder import org.apache.paimon.spark.rowops.{PaimonSparkCopyOnWriteOperation, PaimonSparkDeltaOperation} import org.apache.paimon.table.`object`.ObjectTable @@ -65,11 +65,13 @@ class SparkTableWithRowLevelOps(tableArg: Table) override def newRowLevelOperationBuilder( info: RowLevelOperationInfo): RowLevelOperationBuilder = { - rejectRewriteUnderQueryAuth(table, info.command().toString) table match { case t: FileStoreTable => - if (SparkTable.supportsV2DeltaOps(this)) { () => new PaimonSparkDeltaOperation(t, info) } - else { () => new PaimonSparkCopyOnWriteOperation(t, info) } + // The operation commits through this copy, which authorizes again before the commit. + val target = rejectRewriteUnderQueryAuthOnCommit(t, info.command().toString) + if (SparkTable.supportsV2DeltaOps(this)) { + () => new PaimonSparkDeltaOperation(target, info) + } else { () => new PaimonSparkCopyOnWriteOperation(target, info) } case _ => throw new UnsupportedOperationException( "Row-level write operation is only supported for FileStoreTable. " + diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DeleteFromPaimonTableCommand.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DeleteFromPaimonTableCommand.scala index e002abaa66c6..c09d6d34f886 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DeleteFromPaimonTableCommand.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DeleteFromPaimonTableCommand.scala @@ -42,8 +42,10 @@ case class DeleteFromPaimonTableCommand( with ExpressionHelper with SupportsSubquery { + override protected def rewriteOperation: String = "DELETE" + override def run(sparkSession: SparkSession): Seq[Row] = { - rejectRewriteUnderQueryAuth(table, "DELETE") + rejectRewriteUnderQueryAuth(table, rewriteOperation) val commitMessages = if (usePKUpsertDelete()) { performPrimaryKeyDelete(sparkSession) } else { diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala index b8abdc8ed90a..fd7691fe7afa 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala @@ -307,8 +307,10 @@ case class MergeIntoPaimonDataEvolutionTable( lazy val tableSchema: StructType = targetSparkTable.schema + override protected def rewriteOperation: String = "MERGE INTO" + override def run(sparkSession: SparkSession): Seq[Row] = { - rejectRewriteUnderQueryAuth(table, "MERGE INTO") + rejectRewriteUnderQueryAuth(table, rewriteOperation) // Persist the schema that the analyzer evolved in memory (commit deferred to execution). SchemaEvolutionHelper.commitEvolvedSchemaAtExecution(table, targetRelation, sparkSession) invokeMergeInto(sparkSession) diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala index d7d650e7de88..a252b639fa06 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala @@ -84,8 +84,10 @@ case class MergeIntoPaimonTable( .getOrElse(targetTable)) } + override protected def rewriteOperation: String = "MERGE INTO" + override def run(sparkSession: SparkSession): Seq[Row] = { - rejectRewriteUnderQueryAuth(table, "MERGE INTO") + rejectRewriteUnderQueryAuth(table, rewriteOperation) // Avoid that more than one source rows match the same target row. checkMatchRationality(sparkSession) // Persist the schema that the analyzer evolved in memory (commit deferred to execution). diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonRowLevelCommand.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonRowLevelCommand.scala index a99c7b36ab33..48d903d384aa 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonRowLevelCommand.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonRowLevelCommand.scala @@ -19,6 +19,7 @@ package org.apache.paimon.spark.commands import org.apache.paimon.CoreOptions +import org.apache.paimon.catalog.TableQueryAuthResult.rejectRewriteUnderQueryAuthOnCommit import org.apache.paimon.deletionvectors.{Bitmap64DeletionVector, BitmapDeletionVector, DeletionVector} import org.apache.paimon.fs.Path import org.apache.paimon.io.{CompactIncrement, DataFileMeta, DataIncrement} @@ -56,7 +57,12 @@ trait PaimonRowLevelCommand with ScanPlanHelper with SQLConfHelper { + /** The rewrite this command runs, authorized again before the writer commits. */ + protected def rewriteOperation: String + lazy val writer: PaimonSparkWriter = { + // The writer commits through this copy, which authorizes the rewrite again before the commit. + val writeTable = rejectRewriteUnderQueryAuthOnCommit(table, rewriteOperation) if (table.primaryKeys().isEmpty && table.bucketMode() == BucketMode.HASH_FIXED) { // todo: fix out why fix bucket non-pk table need write only /** @@ -67,9 +73,10 @@ trait PaimonRowLevelCommand * * For example: Update bucketed append table with deletion vectors enabled */ - PaimonSparkWriter(table.copy(Collections.singletonMap(CoreOptions.WRITE_ONLY.key(), "true"))) + PaimonSparkWriter( + writeTable.copy(Collections.singletonMap(CoreOptions.WRITE_ONLY.key(), "true"))) } else { - PaimonSparkWriter(table) + PaimonSparkWriter(writeTable) } } diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/UpdatePaimonTableCommand.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/UpdatePaimonTableCommand.scala index 4e36a0d01abb..8e89612532bd 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/UpdatePaimonTableCommand.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/UpdatePaimonTableCommand.scala @@ -47,8 +47,10 @@ case class UpdatePaimonTableCommand( case (expr, attr) => Alias(expr, attr.name)() } + override protected def rewriteOperation: String = "UPDATE" + override def run(sparkSession: SparkSession): Seq[Row] = { - rejectRewriteUnderQueryAuth(table, "UPDATE") + rejectRewriteUnderQueryAuth(table, rewriteOperation) val commitMessages = if (withPrimaryKeys) { performUpdateForPkTable(sparkSession) diff --git a/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java b/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java index e3b57930a6f3..28e9b30bf14c 100644 --- a/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java +++ b/paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkCatalogWithRestTest.java @@ -56,6 +56,7 @@ import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; +import org.apache.spark.sql.api.java.UDF1; import org.apache.spark.sql.connector.catalog.CatalogManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -345,6 +346,52 @@ private static Map mask(String column) { new ConcatTransform(Collections.singletonList(BinaryString.fromString("****")))); } + // run by the change_auth_rules UDF while a statement runs + private static volatile Runnable changeAuthRules; + + @ParameterizedTest + @MethodSource("rowLevelTableOptions") + public void testRowLevelOperationsAuthorizeAgainBeforeCommit( + boolean useV2Write, String options) { + spark.conf().set("spark.paimon.write.use-v2-write", useV2Write); + spark.sql( + "CREATE TABLE t_late (id INT, ssn STRING, note STRING, p INT) PARTITIONED BY (p)" + + " TBLPROPERTIES ('query-auth.enabled'='true', " + + options + + ")"); + spark.sql("INSERT INTO t_late VALUES (1, 's1', 'n1', 1), (2, 's2', 'n2', 1)"); + Identifier identifier = Identifier.create("db2", "t_late"); + spark.udf() + .register( + "change_auth_rules", + (UDF1) + value -> { + changeAuthRules.run(); + return value; + }, + org.apache.spark.sql.types.DataTypes.StringType); + // The UDF adds a column mask while the statement runs, after it was checked. + changeAuthRules = () -> restCatalogServer.setColumnMaskingAuth(identifier, mask("ssn")); + String[] statements = { + "UPDATE t_late SET note = change_auth_rules(note)", + "MERGE INTO t_late t USING (SELECT 2 AS id) s ON t.id = s.id" + + " WHEN MATCHED THEN UPDATE SET note = change_auth_rules(t.note)", + "DELETE FROM t_late WHERE change_auth_rules(note) = 'n2'" + }; + try { + for (String statement : statements) { + assertThatThrownBy(() -> spark.sql(statement).collectAsList()) + .hasStackTraceContaining("requires full-table access"); + restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); + assertThat(spark.sql("SELECT * FROM t_late ORDER BY id").collectAsList().toString()) + .isEqualTo("[[1,s1,n1,1], [2,s2,n2,1]]"); + } + } finally { + changeAuthRules = null; + restCatalogServer.setColumnMaskingAuth(identifier, Collections.emptyMap()); + } + } + private static Stream rowLevelTableOptions() { return Stream.of( Arguments.of(false, "'bucket'='-1'"),