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


##########
fe/fe-core/src/main/java/org/apache/doris/rpc/BackendServiceClient.java:
##########
@@ -46,20 +67,238 @@ public static boolean supportsPrivateFileKeys() {
     private final PBackendServiceGrpc.PBackendServiceBlockingStub blockingStub;
     private final ManagedChannel channel;
     private final long execPlanTimeout;
+    private final boolean internalRpc;
+    private final AuthorityPublisher authorityPublisher;
+
+    @FunctionalInterface
+    interface AuthorityPublisher {
+        void publish(long backendId) throws Exception;
+    }
+
+    private volatile long authBackendId;
+
+    private record Target(long backendId, int clusterId, long epoch) {
+    }
+
+    private static final ListeningExecutorService REGISTRATION_EXECUTOR = 
MoreExecutors.listeningDecorator(
+            
ThreadPoolManager.newDaemonFixedThreadPool(Config.heartbeat_mgr_threads_num,
+                    Config.heartbeat_mgr_blocking_queue_size, 
"rpc-authority-registration", true,
+                    new 
java.util.concurrent.ThreadPoolExecutor.AbortPolicy()));
+    private static final ScheduledExecutorService ADMISSION_TIMER = 
admissionTimer();
+
+    private static ScheduledExecutorService admissionTimer() {
+        java.util.concurrent.ScheduledThreadPoolExecutor timer =
+                ThreadPoolManager.newDaemonScheduledThreadPool(1, 
"rpc-authority-deadline", true);
+        // Successful RPCs must not retain a timer node until their original 
deadline.
+        timer.setRemoveOnCancelPolicy(true);
+        return timer;
+    }
+
+    private Target admittedTarget;
+    private Admission admission;
+
+    // One owner can be blocked in a non-interruptible journal write. Keep 
only live,
+    // bounded waiters: nonCancellationPropagating would retain every 
cancelled wrapper
+    // on that owner's listener stack until the journal eventually completes.
+    private static final class Admission {
+        private final SettableFuture<Void> completed = SettableFuture.create();
+        private final Set<SettableFuture<Void>> waiters = new HashSet<>();
+
+        private Admission() {
+            completed.addListener(() -> {
+                List<SettableFuture<Void>> pending;
+                synchronized (this) {
+                    pending = new ArrayList<>(waiters);
+                    waiters.clear();
+                }
+                for (SettableFuture<Void> waiter : pending) {
+                    waiter.setFuture(completed);
+                }
+            }, MoreExecutors.directExecutor());
+        }
+
+        private synchronized ListenableFuture<Void> newWaiter() {
+            if (completed.isDone()) {
+                return completed;
+            }
+            if (waiters.size() >= Math.max(1, 
Config.grpc_threadmgr_threads_nums)) {
+                return Futures.immediateFailedFuture(new 
RejectedExecutionException("Too many authority waiters"));
+            }
+            SettableFuture<Void> waiter = SettableFuture.create();
+            waiters.add(waiter);
+            waiter.addListener(() -> {
+                synchronized (this) {
+                    waiters.remove(waiter);
+                }
+            }, MoreExecutors.directExecutor());
+            return waiter;
+        }
+    }
 
     public BackendServiceClient(TNetworkAddress address, String resolvedIp, 
Executor executor) {
         this(address, resolvedIp, executor, true);
     }
 
     public BackendServiceClient(TNetworkAddress address, String resolvedIp, 
Executor executor, boolean internalRpc) {
+        this(address, resolvedIp, executor, internalRpc, 
FrontendRpcAuthority::registerSelf);
+    }
+
+    BackendServiceClient(TNetworkAddress address, String resolvedIp, Executor 
executor, boolean internalRpc,
+            AuthorityPublisher authorityPublisher) {
+        this.authorityPublisher = authorityPublisher;
         this.address = address;
+        this.internalRpc = internalRpc;
         channel = CHANNEL_PROVIDER.createChannel(address, resolvedIp, 
executor, internalRpc);
         stub = PBackendServiceGrpc.newFutureStub(channel);
         blockingStub = PBackendServiceGrpc.newBlockingStub(channel);
         // execPlanTimeout should be greater than future.get timeout, 
otherwise future will throw ExecutionException
         execPlanTimeout = Config.remote_fragment_exec_timeout_ms + 5000;
     }
 
+    private Target localTarget() {
+        SystemInfoService system = Env.getCurrentSystemInfo();
+        Backend target = system.getBackend(authBackendId);
+        // Resolve through live metadata so endpoint reuse cannot retain a 
dropped backend's identity.
+        if (target == null || target.getBrpcPort() != address.port || 
!target.getHost().equals(address.hostname)) {
+            target = 
system.getAllClusterBackendsNoException().values().stream()
+                    .filter(backend -> backend.getBrpcPort() == address.port
+                            && backend.getHost().equals(address.hostname))
+                    .findFirst().orElseThrow(() -> new 
IllegalStateException("Unknown internal RPC backend"));
+            authBackendId = target.getId();
+        }
+        return new Target(target.getId(), Env.getCurrentEnv().getClusterId(), 
target.getProcessEpoch());
+    }
+
+    private synchronized Admission admit(Target target, boolean repair) {
+        if (target.equals(admittedTarget) && admission != null
+                && (!repair || !admission.completed.isDone())) {
+            return admission;
+        }
+        Admission shared = new Admission();
+        admittedTarget = target;
+        admission = shared;
+        String key = InternalRpcRequestSigner.getInstance().getPublicKey();
+        ListenableFuture<Void> work = 
Futures.transformAsync(isFrontendKeyRegistered(key), registered -> {
+            if (Boolean.TRUE.equals(registered)) {
+                return Futures.immediateVoidFuture();
+            }
+            if (registered == null) {
+                return Futures.immediateFailedFuture(new 
IllegalStateException("Backend authority is unreachable"));
+            }
+            // Blocking control-plane calls use a separate bounded executor, 
never gRPC's callbacks.
+            return Futures.transformAsync(REGISTRATION_EXECUTOR.submit(() -> {
+                authorityPublisher.publish(target.backendId());
+                return null;
+            }), unused -> Futures.transform(isFrontendKeyRegistered(key), 
acknowledged -> {
+                if (!Boolean.TRUE.equals(acknowledged)) {
+                    throw new IllegalStateException("Backend has not 
acknowledged frontend authority");
+                }
+                return null;
+            }, MoreExecutors.directExecutor()), 
MoreExecutors.directExecutor());
+        }, MoreExecutors.directExecutor());
+        // A registration may own a durable journal write. Interrupting it can 
terminate
+        // the FE. Bound each caller's view instead, and retain this shared 
work until it
+        // really finishes so timed-out callers cannot enqueue duplicate 
journal owners.
+        shared.completed.setFuture(work);
+        shared.completed.addListener(() -> {
+            if (hasFailed(shared.completed)) {
+                synchronized (this) {
+                    if (admission == shared) {
+                        admission = null;
+                    }
+                }
+            }
+        }, MoreExecutors.directExecutor());
+        return shared;
+    }
+
+    private static boolean hasFailed(ListenableFuture<?> future) {
+        try {
+            Futures.getDone(future);
+            return false;
+        } catch (Exception e) {
+            return true;
+        }
+    }
+
+    public ListenableFuture<Void> awaitExecutionAuthority() {
+        return Futures.withTimeout(admit(localTarget(), true).newWaiter(),
+                execPlanTimeout, TimeUnit.MILLISECONDS, ADMISSION_TIMER);
+    }
+
+    private <T> ListenableFuture<T> execute(String method, MessageLite 
request, long backendId, int clusterId,
+            Function<PBackendServiceGrpc.PBackendServiceFutureStub, 
ListenableFuture<T>> dispatch,
+            Function<T, Types.PStatus> status) {
+        // Preserve existing execution budgets: only fragment RPCs own this 
deadline.
+        // Other callers retain their existing wait policy; their admission is 
still bounded.
+        Deadline deadline = method.startsWith("exec_plan_fragment")
+                ? Deadline.after(execPlanTimeout, TimeUnit.MILLISECONDS) : 
null;
+        if (!internalRpc) {
+            // Remote authorities are explicitly configured by the destination 
administrator.
+            PBackendServiceGrpc.PBackendServiceFutureStub remote = backendId 
<= 0 ? stub
+                    : signedStub(method, request, backendId, clusterId);
+            return dispatch.apply(deadline == null ? remote : 
remote.withDeadline(deadline));
+        }
+        Target target = localTarget();
+        return executeAdmitted(method, request, target, deadline, dispatch, 
status, false);
+    }
+
+    private <T> ListenableFuture<T> executeAdmitted(String method, MessageLite 
request, Target target,
+            Deadline deadline, 
Function<PBackendServiceGrpc.PBackendServiceFutureStub, ListenableFuture<T>> 
dispatch,
+            Function<T, Types.PStatus> status, boolean repair) {
+        long remaining = deadline == null ? 
TimeUnit.MILLISECONDS.toNanos(execPlanTimeout)
+                : deadline.timeRemaining(TimeUnit.NANOSECONDS);
+        if (remaining <= 0) {
+            return 
Futures.immediateFailedFuture(io.grpc.Status.DEADLINE_EXCEEDED.asRuntimeException());
+        }
+        // Each waiter owns its deadline and cancellation. Neither can poison 
shared admission.
+        Admission owner = admit(target, repair);
+        remaining = deadline == null ? remaining : 
deadline.timeRemaining(TimeUnit.NANOSECONDS);
+        if (remaining <= 0) {
+            return 
Futures.immediateFailedFuture(io.grpc.Status.DEADLINE_EXCEEDED.asRuntimeException());
+        }
+        ListenableFuture<Void> ready = Futures.withTimeout(owner.newWaiter(), 
remaining, TimeUnit.NANOSECONDS,
+                ADMISSION_TIMER);
+        return Futures.transformAsync(ready, unused -> {

Review Comment:
   Fixed in f2850cae26d7. Each fragment task now owns its pending prepare/start 
futures and the original query deadline. Coordinator abort cancels these 
continuations before issuing BE cancellation; dispatch and cancellation share a 
guard so admission cannot send work after cancellation wins. Other waiting 
consumers also cancel their own continuations on exit, without interrupting the 
shared durable registration owner.
   
   The coordinator test covers both execution phases with another worker 
failing while admission is pending. Client and caller tests cover deadlines, 
cancellation during dispatch, abandoned stream/load/validation waits, and 
durable-owner survival. FE publication failures retain their origin and do not 
evict or penalize a healthy BE; real BE probe/execution transport failures 
retain health handling. Final local verification is recorded in the PR 
description.



##########
fe/fe-core/src/main/java/org/apache/doris/httpv2/rest/TableQueryPlanAction.java:
##########
@@ -160,15 +162,42 @@ public Object query_plan(
                     ConnectContext.get().getCloudCluster();
                 }
                 // parse/analysis/plan the sql and acquire tablet distributions
-                handleQuery(ConnectContext.get(), dbName, tblName, sql, 
resultMap);
+                handleQuery(ConnectContext.get(), dbName, tblName, sql, 
resultMap, executionTargets);
             } finally {
                 table.readUnlock();
             }
+            // Registration performs network I/O. Release metadata locks 
first, then admit
+            // every replica advertised to an external scanner, not just the 
chosen scan node.
+            List<java.util.concurrent.Future<Void>> admissions = new 
ArrayList<>();
+            try {
+                for (TNetworkAddress target : 
executionTargets.stream().distinct().toList()) {
+                    Backend backend = 
Env.getCurrentSystemInfo().getAllClusterBackendsNoException().values().stream()
+                            .filter(be -> be.getHost().equals(target.hostname) 
&& be.getBePort() == target.port)
+                            .findFirst().orElseThrow(() -> new 
IllegalStateException("Unknown scanner backend"));
+                    
admissions.add(BackendServiceProxy.getInstance().awaitExecutionAuthority(
+                            new TNetworkAddress(backend.getHost(), 
backend.getBrpcPort())));
+                }
+                for (java.util.concurrent.Future<Void> admission : admissions) 
{
+                    admission.get();

Review Comment:
   Fixed in f2850cae26d7. Scanner planning admits each distinct backend once, 
retains only admitted routes for each tablet, and fails only when a tablet has 
no usable route. This work runs after releasing the table lock. Synchronous 
failures are also remembered, and known backend IDs are validated against live 
endpoints to avoid repeated full topology scans.
   
   Unit tests cover partially available replicated tablets, an uncovered tablet 
and repeated synchronous failures. The packaged lifecycle regression creates an 
actual two-replica table, stops one replica while FE heartbeat metadata still 
reports it healthy, and reads the exported plan through the remaining 
advertised route.



##########
threat-model.md:
##########
@@ -436,6 +436,62 @@ Out-of-scope adversaries:
 
 ## 4.8 Security properties the project provides
 
+**Signed frontend execution requests (defense in depth).** With BE
+`enable_internal_rpc_request_auth=true` (default, restart required), the
+`exec_plan_fragment`, `exec_plan_fragment_prepare`, `exec_plan_fragment_start`,
+`test_jdbc_connection`, `group_commit_insert`, `tablet_fetch_data` and
+`fold_constant_expr` receivers require an FE Ed25519 signature before queueing
+or initializing executable content. It binds the complete request, method,
+destination cluster and backend IDs, and timestamp. Ordinary RPC 
authorizations expire after
+60 seconds with at most 30 seconds of future clock skew; retries within that
+window are allowed. The shared cluster token is not the signing key.
+
+Each FE persists its private signing identity in its metadata directory with
+owner-only permissions and atomic replacement. Keep this file in FE metadata
+backups. The separate `.pub` file contains only the public key. Public keys
+follow the existing master-heartbeat authority; the network-isolation and
+private-RPC transport requirements for that control plane still apply. An FE
+registers its full membership identity and actual RPC endpoint with the master.
+The master independently verifies the endpoint and journals the identity before
+acknowledging it. In-flight responses from replaced identities cannot overwrite
+new registrations. Master epoch and snapshot sequence fence delayed worker 
heartbeats.
+
+Management listeners do not wait for worker availability. Before each target's
+first local executable request, the sender obtains a positive authority 
acknowledgment;
+missing publication is repaired through the master. Shared admission has 
bounded
+resources and each caller retains its own cancellation and overall deadline. 
Only
+an explicit pre-execution registration-required response permits one repair 
retry.
+Optional handshake fields preserve older-worker compatibility. The receiver 
reads
+one immutable membership and destination snapshot per request, outside the 
writer lock.
+
+Exported `_query_plan` scanner capabilities authenticate the exact FE-issued
+legacy Thrift prefix with a bounded, versioned authorization trailer. The 
payload
+is stored once; older readers retain the original plan fields. The backend 
Thrift
+listener reserves 4 KiB above its configured message budget for the trailer's 
encoded
+overhead. Upgrade BEs first to obtain this reserve. Older BE transports need 
their
+`thrift_max_message_size` increased by 4 KiB and a restart before consuming 
newly
+issued capabilities at the previous size boundary. Issuance admits every 
advertised
+replica after releasing metadata locks.
+Capability lifetime follows the existing snapshot/split contract rather than a 
new
+wall-clock cutoff: connectors can persist a plan for delayed opens and 
checkpoint
+recovery. A normal FE restart retains its identity and those capabilities. 
Removing
+the issuer's trusted key revokes them; normal tablet snapshot retention still 
applies.
+Enforcing receivers also accept the preceding signed-envelope format during 
upgrades.
+
+For a BE-first upgrade, explicitly disable enforcement on upgraded BEs until
+all FEs can sign and publish their keys, then restart BEs with enforcement

Review Comment:
   Fixed in f2850cae26d7. The threat model and enforcement configuration 
comments now require operators to drain saved unsigned scanner 
plans/checkpoints, or deliberately re-export them, before restoring BE 
enforcement. They explicitly state that a new export can select a different 
snapshot, so upgrading FEs alone does not migrate existing reader state.



-- 
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