Gabriel39 commented on code in PR #71239:
URL: https://github.com/apache/doris/pull/71239#discussion_r4784830307


##########
fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergParquetColumnKeys.java:
##########
@@ -0,0 +1,199 @@
+// 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.doris.connector.iceberg;
+
+import org.apache.doris.connector.spi.ConnectorConf;
+import org.apache.doris.connector.spi.ConnectorContext;
+
+import org.apache.iceberg.ContentFile;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.encryption.EncryptionUtil;
+import org.apache.iceberg.encryption.KeyManagementClient;
+import org.apache.iceberg.encryption.NativeEncryptionInputFile;
+import org.apache.iceberg.encryption.NativeEncryptionKeyMetadata;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.parquet.format.ColumnChunk;
+import org.apache.parquet.format.ColumnMetaData;
+import org.apache.parquet.format.EncryptionWithColumnKey;
+import org.apache.parquet.format.RowGroup;
+
+import java.nio.ByteBuffer;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/** Optional producer-specific column DEKs, resolved only inside the admitted 
statement's IO scope. */
+final class IcebergParquetColumnKeys {
+    static final String PROVIDER_CONFIG = "parquet_column_key_provider_class";
+    static final int MAX_COLUMN_KEYS = 65536;
+
+    private IcebergParquetColumnKeys() {
+    }
+
+    static Map<Integer, byte[]> read(FileIO io, ContentFile<?> file, 
ConnectorContext context) {
+        // Operator configuration is a separate namespace. 
Catalog/table/vended properties cannot load code.
+        String implementation = context == null ? null : 
ConnectorConf.get(context, PROVIDER_CONFIG, null, null);
+        if (implementation == null || implementation.isBlank()) {
+            return Collections.emptyMap();
+        }
+        try (IcebergParquetColumnKeyProvider provider = 
Class.forName(implementation, true,
+                
IcebergParquetColumnKeys.class.getClassLoader()).asSubclass(IcebergParquetColumnKeyProvider.class)
+                .getDeclaredConstructor().newInstance();
+                KeyUnwrapper kms = new KeyUnwrapper(io.properties())) {

Review Comment:
   Fixed in 780bd93b15da.
   
   Pass catalog KMS options to the column-key path and overlay the effective 
FileIO properties, retaining REST/vended overrides and the existing AWS 
HTTP-client default. New parameterized coverage uses a real default 
HadoopFileIO with empty properties and a provider that invokes the supplied 
unwrap callback; it verifies catalog initialization, IO precedence and client 
close. Both parameters fail with the old IO-only initialization.



##########
fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergScanPlanProvider.java:
##########
@@ -591,6 +598,16 @@ public ConnectorSplitSource streamSplits(ConnectorSession 
session, ConnectorScan
             // preserve that boundary instead of interpreting Iceberg's 
sentinel as the latest snapshot.
             return emptySplitSource();
         }
+        if (iceHandle.isSystemTable()) {
+            Table metadataTable = resolveSysTable(session, iceHandle);
+            if (isPositionDeletesSysTable(iceHandle) || 
IcebergLabelsSysTable.isLabels(iceHandle)
+                    || !IcebergEncryptionRead.isEncrypted(((BaseMetadataTable) 
metadataTable).table())) {
+                throw new UnsupportedOperationException("This Iceberg metadata 
table requires synchronous planning");
+            }
+            TableScan metadataScan = projectedMetadataScan(metadataTable, 
iceHandle, columns, filter, session);
+            return new IcebergMetadataSplitSource(metadataScan::planFiles, 
metadataScan.schema(),

Review Comment:
   Fixed in 780bd93b15da.
   
   Add a bounded PARTITIONS scan before SDK StaticDataTask materialization. It 
reads live entries sequentially, charges retained partition keys/aggregates and 
row-materialization overlap before adding each distinct partition, and fails at 
the separate 64 MiB aggregation limit even in batch mode. SDK differential 
tests cover deletes, evolved specs, NULL partitions, filters, projection and 
pinned snapshots; low-budget and cancellation controls cover the new boundary. 
The limit and sequential-reading tradeoff are documented.



##########
fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergProcedureOps.java:
##########
@@ -324,6 +328,8 @@ private ProcedureTableOperations(TableOperations delegate, 
int admittedFormat) {
 
         private TableMetadata validate(TableMetadata metadata) {
             Objects.requireNonNull(metadata, "Procedure table no longer 
exists");
+            // A concurrent encryption change also revokes maintenance on 
refresh and CAS replay.
+            IcebergEncryptionRead.checkWrite(metadata);

Review Comment:
   Fixed in 780bd93b15da.
   
   The pinned standard REST protocol has no encryption-state or 
metadata-generation requirement; UUID/ref checks cannot provide this guarantee. 
A new test round-trips the actual request parser and 
CatalogHandlers.updateTable to demonstrate acceptance by a backing catalog that 
does not enforce key immutability. When the operator enables PME, Doris 
therefore rejects REST v3+ native writers and manifest-writing procedures 
before staging with REST_ENCRYPTION_FENCE_UNAVAILABLE; native transaction/sink 
admission and metadata DELETE share the boundary. Default-off mode preserves 
existing plaintext writers and does not promise safety if encryption is enabled 
concurrently; that limitation and the upstream Catalog key-immutability 
requirement are explicit in the PR and bilingual docs. The new default/enabled 
matrix passes 35 cases; the intermediate unconditional guard fails eight of 
them and the existing read_guard INSERT. Known encrypted metadata DELETE 
targets are rejected before planning IO
  and before the REST policy: the four HMS/REST and default/enabled controls 
fail on the missing early guard. Row-level DELETE/UPDATE/MERGE also reject in 
their existing mode-validation hook before read-side planning, retaining 
statement/cache/auth ownership. The final 51 write/metadata-delete cases pass. 
A real mTLS DELETE smoke confirms WRITE_UNAVAILABLE, zero additional KMS 
decrypt requests, unchanged snapshot/object digest/rows and successful child 
cleanup.



##########
fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergMetadataSplitSource.java:
##########
@@ -0,0 +1,212 @@
+// 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.doris.connector.iceberg;
+
+import org.apache.doris.connector.spi.ConnectorContext;
+import org.apache.doris.connector.spi.scan.ConnectorScanContext;
+import org.apache.doris.connector.spi.scan.ConnectorScanRange;
+import org.apache.doris.connector.spi.scan.ConnectorSplitSource;
+
+import org.apache.iceberg.DorisMetadataRows;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.concurrent.Callable;
+import java.util.function.Supplier;
+
+/** Pulls authenticated metadata on the FE and publishes only bounded, 
sanitized row batches. */
+final class IcebergMetadataSplitSource implements ConnectorSplitSource {
+    private static final int MAX_BATCH_ROWS = 256;
+    private static final long TARGET_BATCH_BYTES = 1L << 20;
+    private static final int MAX_SERIALIZED_BYTES = 6 << 20;
+    private final Supplier<CloseableIterable<FileScanTask>> loader;
+    private final Schema schema;
+    private final ConnectorScanContext scanContext;
+    private final ConnectorContext context;
+    private CloseableIterable<FileScanTask> tasks;
+    private CloseableIterator<FileScanTask> taskIterator;
+    private CloseableIterable<StructLike> rows;
+    private CloseableIterator<StructLike> rowIterator;
+    private DorisMetadataRows.CopiedRow pending;
+    private ConnectorScanRange next;
+    private long batchOrdinal;
+    private boolean closed;
+
+    IcebergMetadataSplitSource(Supplier<CloseableIterable<FileScanTask>> 
loader, Schema schema,
+            ConnectorScanContext scanContext, ConnectorContext context) {
+        this.loader = loader;
+        this.schema = schema;
+        this.scanContext = scanContext;
+        this.context = context;
+    }
+
+    @Override
+    public boolean hasNext() {
+        if (closed) {
+            return false;
+        }
+        try {
+            return authenticated(this::advance);
+        } catch (RuntimeException failure) {
+            try {
+                close();
+            } catch (IOException cleanup) {
+                failure.addSuppressed(cleanup);
+            }
+            throw failure;
+        }
+    }
+
+    private boolean advance() throws IOException {
+        scanContext.checkCancelled();
+        if (next != null) {
+            return true;
+        }
+        if (tasks == null) {
+            tasks = loader.get();
+            taskIterator = tasks.iterator();
+        }
+        List<StructLike> batch = new ArrayList<>();
+        long bytes = 0;
+        while (batch.size() < MAX_BATCH_ROWS) {
+            scanContext.checkCancelled();
+            if (pending == null) {
+                while (rowIterator == null || !rowIterator.hasNext()) {
+                    closeRows();
+                    if (!taskIterator.hasNext()) {
+                        break;
+                    }
+                    rows = taskIterator.next().asDataTask().rows();

Review Comment:
   Fixed in 780bd93b15da.
   
   Check cancellation after task loading and on every empty-task advance, 
including before obtaining rows and iterators. Encrypted metadata now uses a 
request-local IcebergScanFileIO with the real scan cancellation callback; 
catalog-wide IO is neither mutated nor closed. New tests show that cancellation 
stops after one empty task and closes a planned iterable without opening its 
iterator. The empty-task assertion fails with the old loop.



##########
be/src/format_v2/parquet/parquet_crypto.cpp:
##########
@@ -302,32 +310,60 @@ ParquetColumnCrypto::~ParquetColumnCrypto() = default;
 Status ParquetFileCrypto::create(const TFileEncryptionInfo& info,
                                  const tparquet::FileCryptoMetaData& metadata,
                                  std::shared_ptr<ParquetFileCrypto>* crypto) {
-    if (!info.__isset.version || info.version != 1 || !info.__isset.key ||
+    if (!info.__isset.version || (info.version != 1 && info.version != 2) || 
!info.__isset.key ||
         (info.key.size() != 16 && info.key.size() != 24 && info.key.size() != 
32) ||
         !info.__isset.aad_prefix || info.aad_prefix.size() > 65536) {
         return Status::InvalidArgument("File encryption [INVALID_DESCRIPTOR]");
     }
+    if (info.__isset.column_keys) {
+        if (info.version != 2 || info.column_keys.size() > 65536) {
+            return Status::InvalidArgument("File encryption 
[INVALID_COLUMN_KEYS]");
+        }
+        for (const auto& [ordinal, key] : info.column_keys) {
+            if (ordinal < 0 || (ordinal & 65535) > 32767 ||
+                (key.size() != 16 && key.size() != 24 && key.size() != 32)) {
+                return Status::InvalidArgument("File encryption 
[INVALID_COLUMN_KEYS]");
+            }
+        }
+    }
     const auto& algorithm = metadata.encryption_algorithm;
-    if (!algorithm.__isset.AES_GCM_V1 || algorithm.__isset.AES_GCM_CTR_V1) {
+    if (algorithm.__isset.AES_GCM_V1 == algorithm.__isset.AES_GCM_CTR_V1) {
         return Status::NotSupported("File encryption [UNSUPPORTED_CIPHER]");
     }
-    const auto& aes = algorithm.AES_GCM_V1;
-    if (!aes.__isset.aad_file_unique || aes.aad_file_unique.size() != 8) {
-        return Status::Corruption("File encryption [INVALID_FILE_AAD]");
-    }
-    if (aes.supply_aad_prefix && info.aad_prefix.empty()) {
-        return Status::InvalidArgument("File encryption [MISSING_AAD]");
-    }
-    if ((!aes.aad_prefix.empty() && aes.aad_prefix != info.aad_prefix) ||
-        (aes.aad_prefix.empty() && !aes.supply_aad_prefix && 
!info.aad_prefix.empty())) {
-        return Status::InvalidArgument("File encryption [AAD_MISMATCH]");
-    }
+    std::string file_aad;
+    const auto validate_aad = [&](const auto& aes) -> Status {
+        if (!aes.__isset.aad_file_unique || aes.aad_file_unique.size() != 8) {
+            return Status::Corruption("File encryption [INVALID_FILE_AAD]");
+        }
+        if (aes.supply_aad_prefix && info.aad_prefix.empty()) {
+            return Status::InvalidArgument("File encryption [MISSING_AAD]");
+        }
+        if ((!aes.aad_prefix.empty() && aes.aad_prefix != info.aad_prefix) ||
+            (aes.aad_prefix.empty() && !aes.supply_aad_prefix && 
!info.aad_prefix.empty())) {
+            return Status::InvalidArgument("File encryption [AAD_MISMATCH]");
+        }
+        file_aad = info.aad_prefix + aes.aad_file_unique;
+        return Status::OK();
+    };
+    RETURN_IF_ERROR(algorithm.__isset.AES_GCM_V1 ? 
validate_aad(algorithm.AES_GCM_V1)
+                                                 : 
validate_aad(algorithm.AES_GCM_CTR_V1));
 #if __has_include(<parquet/encryption/encryption_internal.h>)
     auto impl = std::make_unique<Impl>();
     auto key = std::make_shared<crypto_detail::FileKey>();
     key->key = ::arrow::util::SecureString(std::string(info.key));
-    key->file_aad = info.aad_prefix + aes.aad_file_unique;
-    impl->key = std::move(key);
+    key->file_aad = std::make_shared<const std::string>(std::move(file_aad));
+    impl->cipher = algorithm.__isset.AES_GCM_CTR_V1 ? 
::parquet::ParquetCipher::AES_GCM_CTR_V1
+                                                    : 
::parquet::ParquetCipher::AES_GCM_V1;
+    impl->key = key;
+    if (info.__isset.column_keys) {
+        for (const auto& [ordinal, bytes] : info.column_keys) {
+            auto column_key = std::make_shared<crypto_detail::FileKey>();
+            column_key->key = ::arrow::util::SecureString(std::string(bytes));

Review Comment:
   Fixed in 780bd93b15da.
   
   ParquetReader now applies Arrow SecureString::SecureClear to the footer key 
and every temporary column_keys value before resetting the descriptor. All 
existing success/failure/close routes share this helper. A new test checks a 
live descriptor with 16/24/32-byte column keys and idempotent clearing without 
inspecting freed storage.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to