This is an automated email from the ASF dual-hosted git repository.

CalvinKirs pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new b53d1cac38d [feature](fe) Share authentication policy between MySQL 
and Flight SQL (#71078)
b53d1cac38d is described below

commit b53d1cac38dc878c6c661d3ef1aaea43ca068df7
Author: Calvin Kirs <[email protected]>
AuthorDate: Tue Dec 1 20:49:44 2026 +0800

    [feature](fe) Share authentication policy between MySQL and Flight SQL 
(#71078)
    
    ### Background
    
    Doris FE supports local accounts and configured authentication
    integrations. MySQL applies account bindings, the configured primary
    authenticator, and the fallback chain during login. Flight SQL
    previously checked plain passwords directly and kept only the mapped
    user in its session.
    
    ### What problem does this PR solve?
    
    Issue Number: #69944
    Related PR: #68923 (adds authentication integration bindings)
    PR Type: Feature
    
    Problem Summary:
    
    ADBC clients need the same account and authorization policies as MySQL
    clients. The Flight SQL login adapter now delegates to the same FE
    authentication manager, passing the credential type it can represent.
    The change also carries the authenticated principal and roles into
    Flight connection admission so authorization can use the complete
    identity. Ordinary unbound username/password and established FE-local
    bearer sessions continue to work.
    
    ### Details
    
    - **Change map:** 387 additions and 317 deletions in production, 223
    additions and 19 deletions in tests, and no generated files or docs.
    Shared selection, checks, and outcome application are in
    `AuthenticatorManager` and its authenticator implementations. Flight
    credential and session adapters replace the old password-only helpers.
    The tests cover both entry points, binding and account policy, and
    Flight session admission.
    - **Scope:** FE login policy, single-step credential adaptation, and
    Flight session admission. Handshake-only legacy authenticators stay
    available through MySQL. Flight TLS and live IAM Role STS login are
    outside this change.
    - **Design:** Reuse the selection, external identity mapping, role
    mapping, and JIT paths in #69944. Keeping credential exchange in each
    adapter preserves MySQL packet semantics while Flight supplies only the
    credentials and transport it actually has.
    - **Usage:** Connect an ADBC Flight SQL client with its existing
    `username` and `password` options. Administrators can use the existing
    `CREATE USER ... IDENTIFIED WITH AUTHENTICATION INTEGRATION ... AS`
    syntax. An initial Flight Basic exchange can declare a credential type
    through `x-doris-auth-credential-type`. The current listener rejects
    types that require secure transport.
    - **Default behavior:** Basic login declares `CLEAR_TEXT_PASSWORD`. An
    explicit binding selects one integration. Unbound users follow the
    configured primary authenticator and existing `authentication_chain`.
    JIT still requires an integration that enables it. The existing Flight
    connection limits and bearer session lookup still apply.
    - **Compatibility:** No FE/BE RPC or metadata format changes. The
    default method on the legacy authenticator interface preserves existing
    implementations. The historical test reused a 4.1.5 BE for a query.
    Rolling upgrades were not exercised.
    - **Behavior change:** Flight login now enforces bound-account and
    account-lock checks and applies authenticated roles and JIT context
    before pool admission.
    - **Security and privileges:** Bound identities must match the
    integration outcome. A bound login never falls back. Account locks and
    certificate requirements are checked before opening a session. The
    plaintext Flight listener reports its transport accurately, so
    secure-transport requirements remain enforced. No new outbound endpoint
    or SQL privilege is introduced.
    - **Follow-up plan:** Add and verify Flight TLS, then run OIDC and IAM
    Role end to end over supported transport. Verify live STS with the final
    IAM token contract.
    
    ```mermaid
    classDiagram
        direction LR
        class Authenticator {
            <<interface>>
        }
        class FlightSessionsManager {
            <<interface>>
        }
        MysqlProto ..> AuthenticatorManager : delegates login
        DorisFlightSqlService --> FlightBearerTokenAuthenticator : installs
        FlightBearerTokenAuthenticator --> FlightCredentialValidator : 
validates initial credentials
        FlightBearerTokenAuthenticator --> FlightSessionsManager : checks 
bearer sessions
        FlightCredentialValidator ..> AuthenticateRequest : builds
        FlightCredentialValidator --> AuthenticatorManager : authenticates
        FlightCredentialValidator --> FlightSessionsManager : opens session
        AuthenticatorManager ..> Authenticator : selects and invokes
        AuthenticatorManager ..> Auth : checks bindings and locks
        Authenticator <|.. DefaultAuthenticator
        Authenticator <|.. LdapAuthenticator
        Authenticator <|.. AuthenticationPluginAuthenticator
        Authenticator <|.. AuthenticationIntegrationAuthenticator
        AuthenticationIntegrationAuthenticator ..> 
AuthenticationIntegrationRuntime : executes integrations
        AuthenticationIntegrationRuntime --> AuthenticationPluginManager : 
loads plugins
        AuthenticationIntegrationRuntime --> RoleMappingEvaluator : evaluates 
roles
        AuthenticationIntegrationAuthenticator ..> AuthenticateResponse : maps 
outcome
        FlightSessionsManager <|.. FlightSessionsInConnectPool
        FlightSessionsInConnectPool ..> AuthenticatorManager : applies outcome
        FlightSessionsInConnectPool ..> ConnectContext : initializes session
        FlightSessionsInConnectPool ..> ConnectPoolMgr : registers session
    ```
    
    ```mermaid
    flowchart TD
        MYSQL["MySQL: MysqlProto"] --> WIRE["MySQL packet resolvers and 
TLS/certificate checks"]
        WIRE --> SHARED["AuthenticatorManager: shared login policy"]
        FLIGHT["Flight SQL: FlightBearerTokenAuthenticator"] --> 
KIND{"Credential for this RPC"}
        KIND -->|"Doris-issued bearer"| LOOKUP["Resolve a live FE-local Flight 
session"]
        KIND -->|"Initial Basic"| ADAPTER["FlightCredentialValidator: typed 
single-step request and listener transport"]
        ADAPTER --> SHARED
        SHARED --> BOUND{"Binding for this username and host?"}
        BOUND -->|"Yes"| SINGLE["Check credential and transport requirements, 
then try the bound integration only"]
        BOUND -->|"No"| PRIMARY["Try the configured primary authenticator or 
native password"]
        SINGLE --> INTEGRATIONS["AuthenticationIntegrationRuntime: match 
credentials and evaluate roles"]
        SINGLE -->|"Unsupported credential or transport"| 
ERROR["Protocol-specific failure response"]
        PRIMARY -->|"Success"| RESULT["AuthenticateResponse: resolved identity 
and any principal, roles or delegation"]
        PRIMARY -->|"Eligible fallback"| CHAIN["Try the configured integration 
chain"]
        PRIMARY -->|"Failed without fallback"| ERROR
        CHAIN --> INTEGRATIONS
        INTEGRATIONS -->|"Accepted"| MAP["Enforce bound external identity or 
map an existing user or permitted JIT identity"]
        MAP --> RESULT
        INTEGRATIONS -->|"Rejected"| ERROR
        RESULT --> GUARDS["Recheck bindings and account lock, enforce protocol 
certificate policy"]
        GUARDS -->|"Rejected"| ERROR
        GUARDS -->|"Accepted on MySQL"| MYSQLSESSION["Apply ConnectContext and 
use MySQL connection admission"]
        GUARDS -->|"Accepted on Flight"| FLIGHTSESSION["Apply ConnectContext, 
admit through ConnectPoolMgr and return FE-local bearer"]
    ```
    
    ### Testing
    
    - **Previous FE run:** 102 targeted tests passed on the feature patch
    with the previous master baseline. Tests covered MySQL selection,
    bindings and lock checks, the Flight credential adapter, and session
    admission.
    - **Previous real ADBC OIDC run:** ADBC Flight SQL 1.13.0 authenticated
    against an isolated FE using the OIDC plugin and a short-lived loopback
    issuer with JWKS. A bound user could read only the granted table, a
    wrong audience failed, and a JIT user received CEL-mapped SELECT without
    creating a permanent account. A control run with the default FE rejected
    plaintext OIDC. The positive run used a temporary loopback-only
    transport exception that is absent from the PR. It reused an existing
    4.1.5 BE.
    - **Current run on the updated master baseline:** The same ten FE
    classes passed all 102 tests with zero failures, errors, or skips on
    `e46677d8008`. In a separate loopback-only smoke test against the
    unmodified candidate FE, the MySQL client and ADBC Flight SQL 1.13.0
    each logged in with the native account and read `query_timeout`. The
    same ADBC client received `UNAUTHENTICATED` and the secure-transport
    requirement for a typed OIDC login over plaintext.
    
    ### Notes for Reviewers
    
    The two protocols share policy and outcome application. Their packet
    exchange, transport signals, and error responses stay in their
    respective adapters. The Flight bearer is issued after connection
    admission and reused only to locate the live FE session.
    
    ### Release note
    
    Arrow Flight SQL now applies the FE authentication policy for account
    bindings, configured authenticators, and the authenticated identity and
    roles used by the session.
    
    ### Check List (For Author)
    
    - Behavior changed: Yes (see Details)
    - Does this need documentation: Yes. Document Flight credential types
    and transport requirements in the Doris website guide.
    - Pre-submission status: Partially verified: Flight TLS, live IAM STS
    integration, and a full distributable FE package were not verified.
    
    ### AI Disclosure
    
    - Tool: Codex (GPT-6)
    - Generated: FE changes, targeted tests, and PR description
    - Human review: not stated
---
 .../doris/arrowflight/DorisFlightSqlService.java   |   4 +-
 .../doris/arrowflight/auth2/FlightAuthResult.java  |  43 ---
 .../doris/arrowflight/auth2/FlightAuthUtils.java   |  66 ----
 .../auth2/FlightBearerTokenAuthenticator.java      |  20 +-
 .../auth2/FlightCredentialValidator.java           | 107 ++++--
 .../sessions/FlightSessionsInConnectPool.java      |  57 ++--
 .../sessions/FlightSessionsManager.java            |  23 +-
 .../AuthenticationIntegrationRuntime.java          |  15 +
 .../AuthenticationTransportPolicy.java             |  38 +++
 .../mysql/authenticate/AuthenticateRequest.java    |  23 +-
 .../authenticate/AuthenticationFailureSummary.java |  25 +-
 .../doris/mysql/authenticate/Authenticator.java    |  10 +
 .../mysql/authenticate/AuthenticatorManager.java   | 371 +++++++++++++--------
 .../mysql/authenticate/DefaultAuthenticator.java   |  54 ++-
 .../AuthenticationIntegrationAuthenticator.java    |  30 +-
 .../mysql/authenticate/ldap/LdapAuthenticator.java |   5 +
 .../plugin/AuthenticationPluginAuthenticator.java  |  18 +-
 .../org/apache/doris/mysql/privilege/Auth.java     |  17 +-
 .../arrowflight/DorisFlightSqlProducerTest.java    |   4 +-
 .../auth2/FlightBearerTokenAuthenticatorTest.java  |  99 ++++++
 .../sessions/FlightSessionsInConnectPoolTest.java  |  46 ++-
 .../AuthenticationIntegrationRuntimeTest.java      |  37 ++
 .../UserAuthenticationBindingTest.java             |  48 ++-
 .../apache/doris/mysql/ConnectionExceedTest.java   |   8 +-
 .../authenticate/AuthenticatorManagerTest.java     | 123 ++++++-
 ...AuthenticationIntegrationAuthenticatorTest.java |  22 +-
 .../AuthenticationPluginAuthenticatorTest.java     |  27 +-
 27 files changed, 959 insertions(+), 381 deletions(-)

diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/DorisFlightSqlService.java
 
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/DorisFlightSqlService.java
index 1e9a309196b..530842e39e4 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/DorisFlightSqlService.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/DorisFlightSqlService.java
@@ -21,6 +21,7 @@ import 
org.apache.doris.arrowflight.auth2.FlightBearerTokenAuthenticator;
 import org.apache.doris.arrowflight.auth2.FlightRemoteIpServerStreamTracer;
 import org.apache.doris.arrowflight.sessions.FlightSessionsInConnectPool;
 import org.apache.doris.arrowflight.sessions.FlightSessionsManager;
+import org.apache.doris.catalog.Env;
 import org.apache.doris.common.Config;
 import org.apache.doris.qe.ConnectPoolMgr;
 import org.apache.doris.service.ExecuteEnv;
@@ -113,7 +114,8 @@ public class DorisFlightSqlService {
         flightServer = FlightServer.builder(allocator, 
Location.forGrpcInsecure("0.0.0.0", port), producer)
                 .transportHint(GRPC_BUILDER_CONSUMER, 
(Consumer<ServerBuilder<?>>) builder ->
                         builder.addStreamTracerFactory(new 
FlightRemoteIpServerStreamTracer.Factory()))
-                .headerAuthenticator(new 
FlightBearerTokenAuthenticator(flightSessionsManager)).build();
+                .headerAuthenticator(new 
FlightBearerTokenAuthenticator(flightSessionsManager,
+                        
Env.getCurrentEnv().getAuthenticatorManager())).build();
         LOG.info("Arrow Flight SQL service is created, port: {}, 
arrow_flight_max_connections: {} (effective: {},"
                         + " within qe_max_connection: {})", port,
                 Config.arrow_flight_max_connections, flightMaxConnections, 
Config.qe_max_connection);
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/auth2/FlightAuthResult.java
 
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/auth2/FlightAuthResult.java
deleted file mode 100644
index 96c0b0ac1a1..00000000000
--- 
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/auth2/FlightAuthResult.java
+++ /dev/null
@@ -1,43 +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.
-// This file is copied from
-
-package org.apache.doris.arrowflight.auth2;
-
-import org.apache.doris.analysis.UserIdentity;
-
-import org.immutables.value.Value;
-
-/**
- * Result of Authentication.
- */
[email protected]
-public interface FlightAuthResult {
-    String getUserName();
-
-    UserIdentity getUserIdentity();
-
-    String getRemoteIp();
-
-    static FlightAuthResult of(String userName, UserIdentity userIdentity, 
String remoteIp) {
-        return ImmutableFlightAuthResult.builder()
-                .userName(userName)
-                .userIdentity(userIdentity)
-                .remoteIp(remoteIp)
-                .build();
-    }
-}
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/auth2/FlightAuthUtils.java
 
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/auth2/FlightAuthUtils.java
deleted file mode 100644
index 60bf4699208..00000000000
--- 
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/auth2/FlightAuthUtils.java
+++ /dev/null
@@ -1,66 +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.doris.arrowflight.auth2;
-
-import org.apache.doris.analysis.UserIdentity;
-import org.apache.doris.catalog.Env;
-import org.apache.doris.common.AuthenticationException;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import org.apache.arrow.flight.CallStatus;
-import org.apache.logging.log4j.Logger;
-
-import java.util.List;
-
-/**
- * A collection of common Flight server authentication methods.
- */
-public final class FlightAuthUtils {
-    private FlightAuthUtils() {
-    }
-
-    /**
-     * Authenticate against with the provided credentials.
-     *
-     * @param username username.
-     * @param password password.
-     * @param logger the slf4j logger for logging.
-     * @throws org.apache.arrow.flight.FlightRuntimeException if unable to 
authenticate against
-     *         with the provided credentials.
-     */
-    public static FlightAuthResult authenticateCredentials(String username, 
String password, String remoteIp,
-            Logger logger) {
-        try {
-            List<UserIdentity> currentUserIdentity = Lists.newArrayList();
-            // If the password is empty, DBeaver will pass "null" string for 
authentication.
-            // This behavior of DBeaver is strange, but we have to be 
compatible with it, of course,
-            // it may be a problem with Arrow Flight Jdbc driver.
-            // Here, "null" is converted to null, if user's password is really 
the string "null",
-            // authentication will fail. Usually, the user's password will not 
be "null", let's hope so.
-            password = (password.equals("null")) ? null : password;
-            Env.getCurrentEnv().getAuth().checkPlainPassword(username, 
remoteIp, password, currentUserIdentity);
-            Preconditions.checkState(currentUserIdentity.size() == 1);
-            return FlightAuthResult.of(username, currentUserIdentity.get(0), 
remoteIp);
-        } catch (AuthenticationException e) {
-            logger.error("Unable to authenticate user {}", username, e);
-            final String errMsg = "Unable to authenticate user " + username + 
", exception: " + e.getMessage();
-            throw 
CallStatus.UNAUTHENTICATED.withCause(e).withDescription(errMsg).toRuntimeException();
-        }
-    }
-}
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/auth2/FlightBearerTokenAuthenticator.java
 
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/auth2/FlightBearerTokenAuthenticator.java
index 4b3cae5cea0..bbacb8d2c95 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/auth2/FlightBearerTokenAuthenticator.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/auth2/FlightBearerTokenAuthenticator.java
@@ -21,6 +21,7 @@
 package org.apache.doris.arrowflight.auth2;
 
 import org.apache.doris.arrowflight.sessions.FlightSessionsManager;
+import org.apache.doris.mysql.authenticate.AuthenticatorManager;
 
 import org.apache.arrow.flight.CallHeaders;
 import org.apache.arrow.flight.FlightRuntimeException;
@@ -41,13 +42,17 @@ import org.apache.logging.log4j.Logger;
 public class FlightBearerTokenAuthenticator implements CallHeaderAuthenticator 
{
     private static final Logger LOG = 
LogManager.getLogger(FlightBearerTokenAuthenticator.class);
 
+    static final String CREDENTIAL_TYPE_HEADER = 
"x-doris-auth-credential-type";
+
+    private final FlightCredentialValidator credentialValidator;
     private final CallHeaderAuthenticator initialAuthenticator;
     private final FlightSessionsManager flightSessionsManager;
 
-    public FlightBearerTokenAuthenticator(FlightSessionsManager 
flightSessionsManager) {
+    public FlightBearerTokenAuthenticator(FlightSessionsManager 
flightSessionsManager,
+            AuthenticatorManager authenticator) {
         this.flightSessionsManager = flightSessionsManager;
-        this.initialAuthenticator = new BasicCallHeaderAuthenticator(
-                new FlightCredentialValidator(this.flightSessionsManager));
+        this.credentialValidator = new 
FlightCredentialValidator(authenticator, flightSessionsManager);
+        this.initialAuthenticator = new 
BasicCallHeaderAuthenticator(credentialValidator);
     }
 
     /**
@@ -68,10 +73,13 @@ public class FlightBearerTokenAuthenticator implements 
CallHeaderAuthenticator {
 
         if (bearerToken != null) {
             return validateBearer(bearerToken);
-        } else {
-            final AuthResult result = 
initialAuthenticator.authenticate(incomingHeaders);
-            return createAuthResultWithBearerToken(result.getPeerIdentity());
         }
+
+        String credentialType = incomingHeaders.get(CREDENTIAL_TYPE_HEADER);
+        CallHeaderAuthenticator initial = credentialType == null ? 
initialAuthenticator
+                : new BasicCallHeaderAuthenticator(
+                        (user, secret) -> credentialValidator.validate(user, 
secret, credentialType));
+        return 
createAuthResultWithBearerToken(initial.authenticate(incomingHeaders).getPeerIdentity());
     }
 
     /**
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/auth2/FlightCredentialValidator.java
 
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/auth2/FlightCredentialValidator.java
index 77c38a565e4..bc9ebc911d1 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/auth2/FlightCredentialValidator.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/auth2/FlightCredentialValidator.java
@@ -21,49 +21,106 @@
 package org.apache.doris.arrowflight.auth2;
 
 import org.apache.doris.arrowflight.sessions.FlightSessionsManager;
+import org.apache.doris.authentication.AuthenticationFailureType;
+import org.apache.doris.authentication.CredentialType;
+import org.apache.doris.mysql.authenticate.AuthenticateRequest;
+import org.apache.doris.mysql.authenticate.AuthenticateResponse;
+import org.apache.doris.mysql.authenticate.AuthenticationFailureSummary;
+import org.apache.doris.mysql.authenticate.AuthenticatorManager;
+import org.apache.doris.mysql.authenticate.password.ClearPassword;
+import org.apache.doris.qe.ConnectContext;
 
+import org.apache.arrow.flight.CallStatus;
 import org.apache.arrow.flight.auth2.BasicCallHeaderAuthenticator;
 import org.apache.arrow.flight.auth2.CallHeaderAuthenticator.AuthResult;
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 
-/**
- * Authentication specialized CredentialValidator implementation.
- */
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+
 public class FlightCredentialValidator implements 
BasicCallHeaderAuthenticator.CredentialValidator {
     private static final Logger LOG = 
LogManager.getLogger(FlightCredentialValidator.class);
 
-    private final FlightSessionsManager flightSessionsManager;
+    private final AuthenticatorManager authenticator;
+    private final FlightSessionsManager sessions;
 
-    public FlightCredentialValidator(FlightSessionsManager 
flightSessionsManager) {
-        this.flightSessionsManager = flightSessionsManager;
+    public FlightCredentialValidator(AuthenticatorManager authenticator, 
FlightSessionsManager sessions) {
+        this.authenticator = authenticator;
+        this.sessions = sessions;
     }
 
-    /**
-     * Authenticates against with the provided username and password.
-     *
-     * @param username username.
-     * @param password user password.
-     * @return AuthResult with username as the peer identity.
-     */
     @Override
     public AuthResult validate(String username, String password) {
-        String remoteIp = FlightRemoteIpServerStreamTracer.getRemoteIp();
-        FlightAuthResult flightAuthResult = 
FlightAuthUtils.authenticateCredentials(username, password, remoteIp, LOG);
-        return getAuthResultWithBearerToken(flightAuthResult);
+        return validate(username, password, 
CredentialType.CLEAR_TEXT_PASSWORD);
     }
 
+    AuthResult validate(String username, String secret, String credentialType) 
{
+        String remoteIp = FlightRemoteIpServerStreamTracer.getRemoteIp();
+        AuthenticateResponse response = authenticate(username, secret, 
credentialType, remoteIp);
+        String token = sessions.openSession(response, remoteIp);
+        return () -> token;
+    }
 
     /**
-     * Opens the session of the user just authenticated, with the client 
address the stream tracer
-     * captured, and answers with the bearer token the session is known by: 
the token is the peer
-     * identity of this and every later call of the session.
-     *
-     * @param flightAuthResult the FlightAuthResult from initial 
authentication, with peer identity captured.
-     * @return an AuthResult whose peer identity is the bearer token.
+     * Flight supplies a single credential and its explicit type. The current 
Flight listener is
+     * plaintext, so the shared strategy refuses any method requiring a secure 
connection.
      */
-    AuthResult getAuthResultWithBearerToken(FlightAuthResult flightAuthResult) 
{
-        final String token = 
flightSessionsManager.openSession(flightAuthResult);
-        return () -> token;
+    private AuthenticateResponse authenticate(String username, String secret, 
String credentialType, String remoteIp) {
+        if (!CredentialType.CLEAR_TEXT_PASSWORD.equals(credentialType)
+                && !CredentialType.OAUTH_TOKEN.equals(credentialType)
+                && !CredentialType.OIDC_ID_TOKEN.equals(credentialType)
+                && !CredentialType.JWT_TOKEN.equals(credentialType)) {
+            throw CallStatus.UNAUTHENTICATED.withDescription("Unsupported 
Flight SQL credential type")
+                    .toRuntimeException();
+        }
+
+        boolean password = 
CredentialType.CLEAR_TEXT_PASSWORD.equals(credentialType);
+        // Some DBeaver configurations encode an empty password as the literal 
"null".
+        String normalized = password && "null".equals(secret) ? null : secret;
+        AuthenticateRequest request = AuthenticateRequest.builder()
+                .userName(username)
+                .remoteHost(remoteIp)
+                .clientType("arrow-flight-sql")
+                .credentialType(credentialType)
+                .credential(normalized == null ? new byte[0] : 
normalized.getBytes(StandardCharsets.UTF_8))
+                .password(password ? new ClearPassword(normalized) : null)
+                .build();
+        AuthenticateResponse response;
+        // Legacy authenticators report MySQL errors through the current 
thread's QueryState.
+        ConnectContext previous = ConnectContext.get();
+        if (previous != null) {
+            ConnectContext.remove();
+        }
+        try {
+            response = authenticator.authenticate(request, false);
+        } catch (IOException e) {
+            LOG.warn("Flight SQL authentication could not complete: {}", 
e.getClass().getSimpleName());
+            throw CallStatus.UNAVAILABLE.withDescription("Flight SQL 
authentication could not complete")
+                    .toRuntimeException();
+        } finally {
+            if (previous != null) {
+                previous.setThreadLocalInfo();
+            }
+        }
+        if (!response.isSuccess()) {
+            throw 
authenticationFailure(response.getFailureSummary()).toRuntimeException();
+        }
+        return response;
+    }
+
+    private CallStatus authenticationFailure(AuthenticationFailureSummary 
failure) {
+        if (failure == null) {
+            return CallStatus.UNAUTHENTICATED.withDescription("Flight SQL 
authentication failed");
+        }
+        if (failure.hasClientVisibleMessage()) {
+            return 
CallStatus.UNAUTHENTICATED.withDescription(failure.getClientVisibleMessage());
+        }
+        if (failure.isOperationalFailure()) {
+            CallStatus status = failure.getFailureType() == 
AuthenticationFailureType.SOURCE_UNAVAILABLE
+                    ? CallStatus.UNAVAILABLE : CallStatus.INTERNAL;
+            return status.withDescription("Flight SQL authentication could not 
complete");
+        }
+        return CallStatus.UNAUTHENTICATED.withDescription("Flight SQL 
authentication failed");
     }
 }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/sessions/FlightSessionsInConnectPool.java
 
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/sessions/FlightSessionsInConnectPool.java
index 90c4f2a6650..6a51531f09e 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/sessions/FlightSessionsInConnectPool.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/sessions/FlightSessionsInConnectPool.java
@@ -17,9 +17,11 @@
 
 package org.apache.doris.arrowflight.sessions;
 
-import org.apache.doris.arrowflight.auth2.FlightAuthResult;
+import org.apache.doris.catalog.Env;
 import org.apache.doris.common.Status;
 import org.apache.doris.common.util.TokenMasker;
+import org.apache.doris.mysql.authenticate.AuthenticateResponse;
+import org.apache.doris.mysql.authenticate.AuthenticatorManager;
 import org.apache.doris.qe.ConnectContext;
 import org.apache.doris.qe.ConnectPoolMgr;
 import org.apache.doris.qe.ConnectScheduler;
@@ -64,25 +66,42 @@ public class FlightSessionsInConnectPool implements 
FlightSessionsManager {
     }
 
     @Override
-    public String openSession(FlightAuthResult authResult) {
+    public String openSession(AuthenticateResponse authenticated, String 
remoteIp) {
+        Preconditions.checkArgument(authenticated.isSuccess(), "Flight session 
requires an authenticated identity");
         final String token = newToken();
-        ConnectContext connectContext = 
FlightSessionsManager.buildConnectContext(token,
-                authResult.getUserIdentity(), authResult.getRemoteIp(), 
connectScheduler);
-        connectScheduler.submit(connectContext);
-        // The one pool every protocol registers in: qe_max_connection, the 
user's
-        // max_user_connections and the Arrow Flight SQL sub-quota, refused in 
the words a MySQL
-        // client is refused in. Nothing is left of a refused session: the 
client gets no token, so it
-        // does not keep a credential that can never open a session.
-        ConnectPoolMgr pool = connectScheduler.getConnectPoolMgr();
-        int res = pool.registerConnection(connectContext);
-        if (res >= 0) {
-            String errMsg = pool.limitReachedMessage(connectContext, res);
-            // The refused session never entered the pool, so nothing else 
releases what its
-            // adapter allocated (the channel's allocator).
-            connectContext.releaseProtocolSession();
-            LOG.warn("refuse arrow flight sql session, user: {}, remote: {}: 
{}", connectContext.getQualifiedUser(),
-                    connectContext.getRemoteHostPortString(), errMsg);
-            throw 
CallStatus.RESOURCE_EXHAUSTED.withDescription(errMsg).toRuntimeException();
+        ConnectContext connectContext = ConnectContext.forFlight(token);
+        ConnectContext previous = ConnectContext.get();
+        boolean registered = false;
+        try {
+            connectContext.setEnv(Env.getCurrentEnv());
+            connectContext.setStartTime();
+            connectContext.setConnectScheduler(connectScheduler);
+            AuthenticatorManager.applyAuthenticateResponse(connectContext, 
remoteIp, authenticated);
+            // User properties may depend on the authenticated principal of a 
temporary user.
+            connectContext.setThreadLocalInfo();
+            connectContext.setUserQueryTimeout(
+                    
connectContext.getEnv().getAuth().getQueryTimeout(connectContext.getQualifiedUser()));
+            connectContext.setUserInsertTimeout(
+                    
connectContext.getEnv().getAuth().getInsertTimeout(connectContext.getQualifiedUser()));
+            connectScheduler.submit(connectContext);
+            ConnectPoolMgr pool = connectScheduler.getConnectPoolMgr();
+            int res = pool.registerConnection(connectContext);
+            if (res >= 0) {
+                String errMsg = pool.limitReachedMessage(connectContext, res);
+                LOG.warn("refuse arrow flight sql session, user: {}, remote: 
{}: {}",
+                        connectContext.getQualifiedUser(), 
connectContext.getRemoteHostPortString(), errMsg);
+                throw 
CallStatus.RESOURCE_EXHAUSTED.withDescription(errMsg).toRuntimeException();
+            }
+            registered = true;
+        } finally {
+            if (previous == null) {
+                ConnectContext.remove();
+            } else {
+                previous.setThreadLocalInfo();
+            }
+            if (!registered) {
+                connectContext.releaseProtocolSession();
+            }
         }
         // Never log the token itself: fe.log is routinely shipped off the FE 
host, and the token is
         // accepted as a full credential for as long as the session lives. The 
id is enough to trace
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/sessions/FlightSessionsManager.java
 
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/sessions/FlightSessionsManager.java
index 8e96f639425..9a402eea37f 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/sessions/FlightSessionsManager.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/sessions/FlightSessionsManager.java
@@ -18,11 +18,8 @@
 
 package org.apache.doris.arrowflight.sessions;
 
-import org.apache.doris.analysis.UserIdentity;
-import org.apache.doris.arrowflight.auth2.FlightAuthResult;
-import org.apache.doris.catalog.Env;
+import org.apache.doris.mysql.authenticate.AuthenticateResponse;
 import org.apache.doris.qe.ConnectContext;
-import org.apache.doris.qe.ConnectScheduler;
 
 /**
  * The Arrow Flight SQL sessions of this frontend and the bearer tokens they 
are known by.
@@ -47,7 +44,7 @@ public interface FlightSessionsManager {
      *         user's limit is reached), in the words a MySQL client is 
refused in; no session and
      *         no token exist then
      */
-    String openSession(FlightAuthResult authResult);
+    String openSession(AuthenticateResponse authenticated, String remoteIp);
 
     /**
      * The session known by this bearer token (the peer identity of an 
authenticated call).
@@ -64,20 +61,4 @@ public interface FlightSessionsManager {
      * session that has already ended is not an error.
      */
     void closeConnectContext(String peerIdentity);
-
-    static ConnectContext buildConnectContext(String peerIdentity, 
UserIdentity userIdentity, String remoteIP,
-            ConnectScheduler connectScheduler) {
-        ConnectContext connectContext = ConnectContext.forFlight(peerIdentity);
-        connectContext.setEnv(Env.getCurrentEnv());
-        connectContext.setStartTime();
-        connectContext.setCurrentUserIdentity(userIdentity);
-        connectContext.setRemoteIP(remoteIP);
-        connectContext.setUserQueryTimeout(
-                
connectContext.getEnv().getAuth().getQueryTimeout(connectContext.getQualifiedUser()));
-        connectContext.setUserInsertTimeout(
-                
connectContext.getEnv().getAuth().getInsertTimeout(connectContext.getQualifiedUser()));
-
-        connectContext.setConnectScheduler(connectScheduler);
-        return connectContext;
-    }
 }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/authentication/AuthenticationIntegrationRuntime.java
 
b/fe/fe-core/src/main/java/org/apache/doris/authentication/AuthenticationIntegrationRuntime.java
index 485f412a71d..e05ff775d76 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/authentication/AuthenticationIntegrationRuntime.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/authentication/AuthenticationIntegrationRuntime.java
@@ -17,6 +17,7 @@
 
 package org.apache.doris.authentication;
 
+import 
org.apache.doris.authentication.AuthenticationTransportPolicy.SecureTransportRequiredException;
 import org.apache.doris.authentication.handler.AuthenticationOutcome;
 import org.apache.doris.authentication.handler.AuthenticationPluginManager;
 import 
org.apache.doris.authentication.rolemapping.DefinitionBackedRoleMappingEvaluator;
@@ -167,6 +168,11 @@ public class AuthenticationIntegrationRuntime {
 
     public AuthenticationOutcome 
authenticate(List<AuthenticationIntegrationMeta> chain, AuthenticationRequest 
request)
             throws AuthenticationException {
+        return authenticate(chain, request, false);
+    }
+
+    public AuthenticationOutcome 
authenticate(List<AuthenticationIntegrationMeta> chain, AuthenticationRequest 
request,
+            boolean secureTransport) throws AuthenticationException {
         Objects.requireNonNull(chain, "chain");
         Objects.requireNonNull(request, "request");
         if (chain.isEmpty()) {
@@ -177,6 +183,7 @@ public class AuthenticationIntegrationRuntime {
 
         AuthenticationOutcome lastFailure = null;
         boolean anySupported = false;
+        boolean secureTransportRequired = false;
         for (AuthenticationIntegrationMeta meta : chain) {
             ResolvedAuthenticationPlugin resolved;
             try {
@@ -198,6 +205,10 @@ public class AuthenticationIntegrationRuntime {
             if (!plugin.supports(request)) {
                 continue;
             }
+            if (!secureTransport && 
AuthenticationTransportPolicy.requiresSecureTransport(integration.getType())) {
+                secureTransportRequired = true;
+                continue;
+            }
             anySupported = true;
 
             AuthenticationOutcome outcome;
@@ -215,6 +226,10 @@ public class AuthenticationIntegrationRuntime {
             }
         }
 
+        // A recorded transport refusal matters only after the eligible 
candidates are exhausted.
+        if (secureTransportRequired) {
+            throw new SecureTransportRequiredException();
+        }
         if (lastFailure != null) {
             return lastFailure;
         }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/authentication/AuthenticationTransportPolicy.java
 
b/fe/fe-core/src/main/java/org/apache/doris/authentication/AuthenticationTransportPolicy.java
new file mode 100644
index 00000000000..1385037f1f6
--- /dev/null
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/authentication/AuthenticationTransportPolicy.java
@@ -0,0 +1,38 @@
+// 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.authentication;
+
+/** Transport requirements of authentication integration types that handle 
bearer credentials. */
+public final class AuthenticationTransportPolicy {
+    public static final String SECURE_TRANSPORT_REQUIRED = "Authentication 
requires secure transport";
+
+    private AuthenticationTransportPolicy() {
+    }
+
+    public static boolean requiresSecureTransport(String integrationType) {
+        // TODO: Add a secure-transport capability to the authentication SPI 
in a separate change,
+        // with compatibility coverage for existing plugins and defaults for 
bearer credential handlers.
+        return "oidc".equalsIgnoreCase(integrationType) || 
"aws_iam".equalsIgnoreCase(integrationType);
+    }
+
+    public static final class SecureTransportRequiredException extends 
AuthenticationException {
+        public SecureTransportRequiredException() {
+            super(SECURE_TRANSPORT_REQUIRED, 
AuthenticationFailureType.ACCESS_DENIED);
+        }
+    }
+}
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/AuthenticateRequest.java
 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/AuthenticateRequest.java
index 5c617c028be..87115a1fcec 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/AuthenticateRequest.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/AuthenticateRequest.java
@@ -37,6 +37,7 @@ public class AuthenticateRequest {
     private final byte[] credential;
     private final Map<String, Object> properties;
     private final UserIdentity userIdentity;
+    private final boolean secureTransport;
 
     public AuthenticateRequest(String userName, Password password, String 
remoteIp) {
         this(builder()
@@ -65,6 +66,7 @@ public class AuthenticateRequest {
                 ? Collections.emptyMap()
                 : Collections.unmodifiableMap(new 
HashMap<>(builder.properties));
         this.userIdentity = builder.userIdentity;
+        this.secureTransport = builder.secureTransport;
     }
 
     public String getUserName() {
@@ -107,7 +109,20 @@ public class AuthenticateRequest {
         return userIdentity;
     }
 
+    public boolean isSecureTransport() {
+        return secureTransport;
+    }
+
     public AuthenticateRequest withUserIdentity(UserIdentity userIdentity) {
+        return copy().userIdentity(userIdentity).build();
+    }
+
+    /** Attach server-verified transport state. An authentication adapter must 
derive it from the connection. */
+    public AuthenticateRequest withSecureTransport(boolean secureTransport) {
+        return this.secureTransport == secureTransport ? this : 
copy().secureTransport(secureTransport).build();
+    }
+
+    private Builder copy() {
         return builder()
                 .userName(userName)
                 .password(password)
@@ -118,7 +133,7 @@ public class AuthenticateRequest {
                 .credential(credential)
                 .properties(properties)
                 .userIdentity(userIdentity)
-                .build();
+                .secureTransport(secureTransport);
     }
 
     public static Builder builder() {
@@ -135,10 +150,16 @@ public class AuthenticateRequest {
         private byte[] credential;
         private Map<String, Object> properties;
         private UserIdentity userIdentity;
+        private boolean secureTransport;
 
         private Builder() {
         }
 
+        private Builder secureTransport(boolean secureTransport) {
+            this.secureTransport = secureTransport;
+            return this;
+        }
+
         public Builder userName(String userName) {
             this.userName = userName;
             return this;
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/AuthenticationFailureSummary.java
 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/AuthenticationFailureSummary.java
index a6d5385b60f..664d5c2ee09 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/AuthenticationFailureSummary.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/AuthenticationFailureSummary.java
@@ -19,6 +19,7 @@ package org.apache.doris.mysql.authenticate;
 
 import org.apache.doris.authentication.AuthenticationException;
 import org.apache.doris.authentication.AuthenticationFailureType;
+import org.apache.doris.authentication.AuthenticationTransportPolicy;
 
 import com.google.common.base.Strings;
 
@@ -28,22 +29,24 @@ public final class AuthenticationFailureSummary {
     private final AuthenticationFailureType failureType;
     private final String detailMessage;
     private final String clientVisibleMessage;
+    private final boolean secureTransportRequired;
 
     private AuthenticationFailureSummary(AuthenticationFailureType 
failureType, String detailMessage,
-            String clientVisibleMessage) {
+            String clientVisibleMessage, boolean secureTransportRequired) {
         this.failureType = Objects.requireNonNull(failureType, "failureType");
         this.detailMessage = Strings.nullToEmpty(detailMessage);
         this.clientVisibleMessage = Strings.nullToEmpty(clientVisibleMessage);
+        this.secureTransportRequired = secureTransportRequired;
     }
 
     public static AuthenticationFailureSummary 
forFailureType(AuthenticationFailureType failureType,
             String detailMessage) {
-        return new AuthenticationFailureSummary(failureType, detailMessage, 
"");
+        return new AuthenticationFailureSummary(failureType, detailMessage, 
"", false);
     }
 
     public static AuthenticationFailureSummary 
forClientVisibleFailure(AuthenticationFailureType failureType,
             String detailMessage, String clientVisibleMessage) {
-        return new AuthenticationFailureSummary(failureType, detailMessage, 
clientVisibleMessage);
+        return new AuthenticationFailureSummary(failureType, detailMessage, 
clientVisibleMessage, false);
     }
 
     public static AuthenticationFailureSummary 
forException(AuthenticationException exception, String fallbackMessage) {
@@ -56,13 +59,27 @@ public final class AuthenticationFailureSummary {
         String detailMessage = 
Strings.isNullOrEmpty(safeException.getMessage())
                 ? fallbackMessage
                 : safeException.getMessage();
-        return new 
AuthenticationFailureSummary(safeException.getFailureType(), detailMessage, 
clientVisibleMessage);
+        return new 
AuthenticationFailureSummary(safeException.getFailureType(), detailMessage,
+                clientVisibleMessage, false);
     }
 
     public AuthenticationFailureType getFailureType() {
         return failureType;
     }
 
+    public static AuthenticationFailureSummary secureTransportRequired() {
+        String message = 
AuthenticationTransportPolicy.SECURE_TRANSPORT_REQUIRED;
+        return new 
AuthenticationFailureSummary(AuthenticationFailureType.ACCESS_DENIED, message, 
message, true);
+    }
+
+    public boolean isSecureTransportRequired() {
+        return secureTransportRequired;
+    }
+
+    String getDiagnosticCode() {
+        return secureTransportRequired ? "SECURE_TRANSPORT_REQUIRED" : 
failureType.name();
+    }
+
     public String getDetailMessage() {
         return detailMessage;
     }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/Authenticator.java
 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/Authenticator.java
index 56d045f4340..ecd32fd5618 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/Authenticator.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/Authenticator.java
@@ -26,5 +26,15 @@ public interface Authenticator {
 
     boolean canDeal(String qualifiedUser);
 
+    /** Whether this authenticator can consume a request without its MySQL 
password resolver. */
+    default boolean acceptsSingleStepRequest() {
+        return false;
+    }
+
+    /** Whether the selected authenticator requires a protected connection 
before resolving credentials. */
+    default boolean requiresSecureTransport() {
+        return false;
+    }
+
     PasswordResolver getPasswordResolver();
 }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/AuthenticatorManager.java
 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/AuthenticatorManager.java
index c0f813d0e97..8e5f243c364 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/AuthenticatorManager.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/AuthenticatorManager.java
@@ -22,6 +22,7 @@ import 
org.apache.doris.auth.certificate.CertificateAuthDecision;
 import org.apache.doris.auth.certificate.CertificateRuntimeAuthFactory;
 import org.apache.doris.auth.certificate.CertificateRuntimeAuthService;
 import org.apache.doris.authentication.AuthenticationFailureType;
+import org.apache.doris.authentication.AuthenticationTransportPolicy;
 import org.apache.doris.authentication.CredentialType;
 import org.apache.doris.catalog.Env;
 import org.apache.doris.common.AuthenticationException;
@@ -39,6 +40,7 @@ import 
org.apache.doris.mysql.authenticate.integration.AuthenticationIntegration
 import org.apache.doris.mysql.authenticate.password.ClearPassword;
 import org.apache.doris.mysql.authenticate.password.Password;
 import 
org.apache.doris.mysql.authenticate.plugin.AuthenticationPluginAuthenticator;
+import org.apache.doris.mysql.privilege.Auth;
 import org.apache.doris.mysql.privilege.User;
 import org.apache.doris.plugin.PropertiesUtils;
 import org.apache.doris.qe.ConnectContext;
@@ -59,7 +61,7 @@ import java.util.Properties;
 import java.util.ServiceLoader;
 
 /**
- * MySQL authenticator entry that keeps legacy auth-type compatibility while 
supporting plugin-based authenticators.
+ * Shared login strategy with a MySQL adapter for the legacy credential 
exchanges and error packets.
  *
  * <p>The compatibility rules are:
  * <ul>
@@ -192,76 +194,157 @@ public class AuthenticatorManager {
         }
         UserIdentity preferredUserIdentity = certDecision.isVerified() ? 
certDecision.getUserIdentity() : null;
 
+        LoginCredentials credentials = new 
LoginCredentials(channel.isSslMode(),
+                authenticator -> resolveAuthenticateRequest(authenticator, 
userName, context, channel, serializer,
+                        authPacket, handshakePacket),
+                (authenticator, primary) -> 
resolveAuthenticationChainRequest(authenticator, primary, context,
+                        userName, channel, serializer, authPacket, 
handshakePacket));
+        LoginResult result = authenticate(userName, remoteIp, 
preferredUserIdentity, credentials);
+        if (result.status() == LoginStatus.NO_REQUEST) {
+            return false;
+        }
+        if (result.status() == LoginStatus.AUTHENTICATOR_TLS_REQUIRED) {
+            
context.getState().setError(ErrorCode.ERR_SECURE_TRANSPORT_REQUIRED,
+                    AuthenticationTransportPolicy.SECURE_TRANSPORT_REQUIRED);
+            MysqlProto.sendResponsePacket(context);
+            return false;
+        }
+        if (result.status() == LoginStatus.TOKEN_TLS_REQUIRED) {
+            setInsecureOidcTransportError(context);
+        }
+        if (result.response() != null) {
+            return finishSuccessfulAuthentication(context, result.remoteIp(), 
result.response(),
+                    result.status() == LoginStatus.CHAIN_SUCCESS);
+        }
+        return reportAuthenticationFailure(context, userName, 
result.remoteIp(), result.password(), result.failures());
+    }
+
+    /**
+     * Authenticate a credential delivered by a single-step protocol. The 
secure transport flag
+     * describes the actual connection, and is supplied by the server's 
protocol adapter.
+     */
+    public AuthenticateResponse authenticate(AuthenticateRequest request, 
boolean secureTransport) throws IOException {
+        LoginCredentials credentials = new LoginCredentials(secureTransport,
+                authenticator -> singleStepRequest(authenticator, request), 
this::singleStepRequest);
+        LoginResult result = authenticate(request.getUserName(), 
request.getRemoteIp(), null, credentials);
+        if (result.status() == LoginStatus.AUTHENTICATOR_TLS_REQUIRED
+                || result.status() == LoginStatus.TOKEN_TLS_REQUIRED) {
+            AuthenticationFailureSummary failure = 
AuthenticationFailureSummary.secureTransportRequired();
+            logAuthenticationFailureSummary(request.getUserName(), 
result.remoteIp(), List.of(failure));
+            return AuthenticateResponse.failed(failure);
+        }
+        if (result.status() == LoginStatus.NO_REQUEST) {
+            LOG.warn("Single-step authentication rejected from '{}': 
UNSUPPORTED_AUTHENTICATION_METHOD",
+                    result.remoteIp());
+            return 
AuthenticateResponse.failed(AuthenticationFailureSummary.forClientVisibleFailure(
+                    AuthenticationFailureType.ACCESS_DENIED, "Authentication 
method is unavailable on this protocol",
+                    "Authentication method is unavailable on this protocol"));
+        }
+        AuthenticateResponse response = result.response();
+        if (response == null) {
+            logAuthenticationFailureSummary(request.getUserName(), 
result.remoteIp(), result.failures());
+            if (!containsSensitiveFailure(result.failures())) {
+                for (AuthenticationFailureSummary failure : result.failures()) 
{
+                    if (failure.hasClientVisibleMessage()) {
+                        return AuthenticateResponse.failed(failure);
+                    }
+                }
+            }
+            if (containsOnlyOperationalFailures(result.failures())) {
+                return 
AuthenticateResponse.failed(AuthenticationFailureSummary.forFailureType(
+                        result.failures().get(0).getFailureType(), 
OPERATIONAL_AUTHENTICATION_FAILURE_MESSAGE));
+            }
+            return AuthenticateResponse.failedResponse;
+        }
+
+        ErrorCode policyError = validateSuccessfulAuthentication(response, 
result.remoteIp());
+        if (policyError != null) {
+            LOG.warn("Single-step authentication rejected from '{}': {}", 
result.remoteIp(),
+                    policyError == ErrorCode.ERR_ACCESS_DENIED_ERROR ? 
"AUTHENTICATION_BINDING_MISMATCH"
+                            : policyError.name());
+            return AuthenticateResponse.failedResponse;
+        }
+        if 
(Env.getCurrentEnv().getAuth().requiresCertificateAuth(response.getUserIdentity()))
 {
+            LOG.warn("Single-step authentication rejected from '{}': 
CLIENT_CERTIFICATE_REQUIRED", result.remoteIp());
+            return AuthenticateResponse.failedResponse;
+        }
+        return response;
+    }
+
+    private Optional<AuthenticateRequest> singleStepRequest(Authenticator 
authenticator, AuthenticateRequest request) {
+        return authenticator.acceptsSingleStepRequest() ? Optional.of(request) 
: Optional.empty();
+    }
+
+    private LoginResult authenticate(String userName, String remoteIp, 
UserIdentity preferredUserIdentity,
+            LoginCredentials credentials) throws IOException {
         Authenticator primaryAuthenticator = chooseAuthenticator(userName, 
remoteIp);
         boolean boundAuthentication = primaryAuthenticator instanceof 
AuthenticationIntegrationAuthenticator
                 && ((AuthenticationIntegrationAuthenticator) 
primaryAuthenticator).isBoundAuthentication();
+        boolean requiresSecureTransport = 
primaryAuthenticator.requiresSecureTransport();
         if (boundAuthentication) {
             try {
-                boolean requiresClear = 
((AuthenticationIntegrationAuthenticator) primaryAuthenticator)
+                requiresSecureTransport = 
((AuthenticationIntegrationAuthenticator) primaryAuthenticator)
                         .prepareBoundAuthentication();
-                if (requiresClear && !channel.isSslMode()) {
-                    
context.getState().setError(ErrorCode.ERR_SECURE_TRANSPORT_REQUIRED,
-                            "Authentication-bound users require TLS before 
supplying clear text credentials");
-                    MysqlProto.sendResponsePacket(context);
-                    return false;
-                }
             } catch (org.apache.doris.authentication.AuthenticationException 
e) {
-                return reportAuthenticationFailure(context, userName, 
remoteIp, null,
-                        
java.util.Collections.singletonList(AuthenticationFailureSummary.forException(e,
+                return new LoginResult(LoginStatus.REJECTED, null, remoteIp, 
null,
+                        List.of(AuthenticationFailureSummary.forException(e,
                                 "Unable to resolve bound authentication 
integration")));
             }
         }
-
-        boolean debugEnabled = LOG.isDebugEnabled();
-        long resolveStart = 0L;
-        if (debugEnabled) {
-            LOG.debug("AuthenticatorManager: user={}, authenticator={}",
-                    userName, primaryAuthenticator.getClass().getSimpleName());
-            resolveStart = System.currentTimeMillis();
-        }
-        Optional<AuthenticateRequest> primaryRequest = 
resolveAuthenticateRequest(primaryAuthenticator, userName,
-                context, channel, serializer, authPacket, handshakePacket);
-        if (!primaryRequest.isPresent()) {
-            return false;
+        if (requiresSecureTransport && !credentials.secureTransport()) {
+            return new LoginResult(LoginStatus.AUTHENTICATOR_TLS_REQUIRED, 
null, remoteIp, null, List.of());
         }
 
+        Optional<AuthenticateRequest> primaryRequest = 
credentials.primary().resolve(primaryAuthenticator);
+        if (primaryRequest.isEmpty()) {
+            return new LoginResult(LoginStatus.NO_REQUEST, null, remoteIp, 
null, List.of());
+        }
         AuthenticateRequest request = primaryRequest.get();
         if (preferredUserIdentity != null) {
             request = request.withUserIdentity(preferredUserIdentity);
         }
-        if (debugEnabled) {
-            long resolveElapsed = System.currentTimeMillis() - resolveStart;
-            LOG.debug("resolvePassword: user={}, elapsed={}ms", userName, 
resolveElapsed);
-            resolveStart = System.currentTimeMillis();
-        }
-        remoteIp = request.getRemoteIp();
-        if (isOidcAuthenticationWithoutSsl(authPacket, request)) {
-            setInsecureOidcTransportError(context);
-            return reportAuthenticationFailure(context, userName, remoteIp, 
request.getPassword(),
-                    new ArrayList<>());
-        }
-        AuthenticateResponse primaryResponse = 
authenticateWith(primaryAuthenticator, request);
-        if (debugEnabled) {
-            long authenticateElapsed = System.currentTimeMillis() - 
resolveStart;
-            LOG.debug("authenticate: user={}, elapsed={}ms", userName, 
authenticateElapsed);
+        if (requiresSecureTokenTransport(request, credentials)) {
+            return new LoginResult(LoginStatus.TOKEN_TLS_REQUIRED, null, 
request.getRemoteIp(),
+                    request.getPassword(), List.of());
         }
-        if (primaryResponse.isSuccess()) {
-            return finishSuccessfulAuthentication(context, remoteIp, 
primaryResponse, false);
+        AuthenticateResponse response = authenticateWith(primaryAuthenticator,
+                request.withSecureTransport(credentials.secureTransport()));
+        if (response.isSuccess()) {
+            return new LoginResult(LoginStatus.PRIMARY_SUCCESS, response, 
request.getRemoteIp(), null, List.of());
         }
-        List<AuthenticationFailureSummary> failureSummaries = new 
ArrayList<>();
-        addFailureSummary(failureSummaries, primaryResponse);
+        List<AuthenticationFailureSummary> failures = new ArrayList<>();
+        addFailureSummary(failures, response);
 
-        if (boundAuthentication) {
-            return reportAuthenticationFailure(context, userName, remoteIp, 
request.getPassword(), failureSummaries);
-        }
-        AuthenticateResponse chainResponse = 
tryAuthenticationChainFallback(context, userName, remoteIp,
-                channel, serializer, authPacket, handshakePacket, request);
-        if (chainResponse != null && chainResponse.isSuccess()) {
-            return finishSuccessfulAuthentication(context, remoteIp, 
chainResponse, true);
+        if (!boundAuthentication) {
+            LoginResult fallback = tryAuthenticationChainFallback(userName, 
request, credentials, failures);
+            if (fallback != null) {
+                return fallback;
+            }
         }
-        addFailureSummary(failureSummaries, chainResponse);
+        return new LoginResult(LoginStatus.REJECTED, null, 
request.getRemoteIp(), request.getPassword(), failures);
+    }
+
+    @FunctionalInterface
+    private interface PrimaryCredentialResolver {
+        Optional<AuthenticateRequest> resolve(Authenticator authenticator) 
throws IOException;
+    }
 
-        return reportAuthenticationFailure(context, userName, remoteIp, 
request.getPassword(), failureSummaries);
+    @FunctionalInterface
+    private interface ChainCredentialResolver {
+        Optional<AuthenticateRequest> resolve(Authenticator authenticator, 
AuthenticateRequest primary)
+                throws IOException;
+    }
+
+    private record LoginCredentials(boolean secureTransport, 
PrimaryCredentialResolver primary,
+            ChainCredentialResolver chain) {
+    }
+
+    private enum LoginStatus {
+        PRIMARY_SUCCESS, CHAIN_SUCCESS, REJECTED, NO_REQUEST, 
AUTHENTICATOR_TLS_REQUIRED, TOKEN_TLS_REQUIRED
+    }
+
+    private record LoginResult(LoginStatus status, AuthenticateResponse 
response, String remoteIp, Password password,
+            List<AuthenticationFailureSummary> failures) {
     }
 
     Authenticator chooseAuthenticator(String userName, String remoteIp) {
@@ -277,7 +360,8 @@ public class AuthenticatorManager {
         return new 
AuthenticationIntegrationAuthenticator(Config.authentication_chain, 
"authentication_chain");
     }
 
-    private void applyAuthenticateResponse(ConnectContext context, String 
remoteIp, AuthenticateResponse response) {
+    public static void applyAuthenticateResponse(ConnectContext context, 
String remoteIp,
+            AuthenticateResponse response) {
         context.setCurrentUserIdentity(response.getUserIdentity());
         context.setRemoteIP(remoteIp);
         context.setIsTempUser(response.isTemp());
@@ -337,37 +421,57 @@ public class AuthenticatorManager {
      * ACCOUNT_LOCK, enforced after ANY authentication succeeded -- local 
password, LDAP, an
      * authentication integration or plugin, or a client certificate -- so 
none of them can open a
      * locked Doris account (the local-password path also checks it inside the 
password policy).
-     * Returns true when the login was refused: the 3118 error is set and 
sent, nothing is applied.
+     * Returns the account policy error, or null when the authenticated 
identity may log in.
      */
-    @VisibleForTesting
-    boolean refuseIfAccountLocked(ConnectContext context, UserIdentity 
userIdentity) throws IOException {
+    private ErrorCode validateSuccessfulAuthentication(AuthenticateResponse 
response, String remoteIp) {
+        Auth auth = Env.getCurrentEnv().getAuth();
+        User binding = 
auth.getAuthenticationBinding(response.getUserIdentity().getQualifiedUser(), 
remoteIp);
+        if ((binding == null && (response.getAuthenticationIntegration() != 
null
+                || auth.isAuthenticationBound(response.getUserIdentity())))
+                || (binding != null && 
(!binding.getUserIdentity().equals(response.getUserIdentity())
+                || response.isTemp()
+                || 
!binding.getAuthIntegration().equals(response.getAuthenticationIntegration())
+                || !java.util.Objects.equals(binding.getAuthIdentity(), 
response.getBoundIdentity())))) {
+            return ErrorCode.ERR_ACCESS_DENIED_ERROR;
+        }
+        return checkAccountLock(response.getUserIdentity());
+    }
+
+    private ErrorCode checkAccountLock(UserIdentity userIdentity) {
         try {
             Env.getCurrentEnv().getAuth().checkAccountLocked(userIdentity);
-            return false;
+            return null;
         } catch (AuthenticationException e) {
-            context.getState().setError(ErrorCode.ERR_ACCOUNT_HAS_BEEN_LOCKED,
-                    
ErrorCode.ERR_ACCOUNT_HAS_BEEN_LOCKED.formatErrorMsg(userIdentity.getQualifiedUser(),
-                            userIdentity.getHost()));
-            MysqlProto.sendResponsePacket(context);
-            return true;
+            return ErrorCode.ERR_ACCOUNT_HAS_BEEN_LOCKED;
+        }
+    }
+
+    @VisibleForTesting
+    boolean refuseIfAccountLocked(ConnectContext context, UserIdentity 
userIdentity) throws IOException {
+        if (checkAccountLock(userIdentity) == null) {
+            return false;
         }
+        reportAccountLocked(context, userIdentity);
+        return true;
+    }
+
+    private void reportAccountLocked(ConnectContext context, UserIdentity 
userIdentity) throws IOException {
+        context.getState().setError(ErrorCode.ERR_ACCOUNT_HAS_BEEN_LOCKED,
+                
ErrorCode.ERR_ACCOUNT_HAS_BEEN_LOCKED.formatErrorMsg(userIdentity.getQualifiedUser(),
+                        userIdentity.getHost()));
+        MysqlProto.sendResponsePacket(context);
     }
 
     @VisibleForTesting
     boolean finishSuccessfulAuthentication(ConnectContext context, String 
remoteIp,
             AuthenticateResponse response, boolean setOkState) throws 
IOException {
-        User binding = Env.getCurrentEnv().getAuth().getAuthenticationBinding(
-                response.getUserIdentity().getQualifiedUser(), remoteIp);
-        if ((binding == null && (response.getAuthenticationIntegration() != 
null
-                || 
Env.getCurrentEnv().getAuth().isAuthenticationBound(response.getUserIdentity())))
-                || (binding != null && 
(!binding.getUserIdentity().equals(response.getUserIdentity())
-                || response.isTemp()
-                || 
!binding.getAuthIntegration().equals(response.getAuthenticationIntegration())
-                || !java.util.Objects.equals(binding.getAuthIdentity(), 
response.getBoundIdentity())))) {
+        ErrorCode error = validateSuccessfulAuthentication(response, remoteIp);
+        if (error == ErrorCode.ERR_ACCESS_DENIED_ERROR) {
             return reportAuthenticationFailure(context, 
response.getUserIdentity().getQualifiedUser(), remoteIp,
-                    null, java.util.Collections.emptyList());
+                    null, List.of());
         }
-        if (refuseIfAccountLocked(context, response.getUserIdentity())) {
+        if (error == ErrorCode.ERR_ACCOUNT_HAS_BEEN_LOCKED) {
+            reportAccountLocked(context, response.getUserIdentity());
             return false;
         }
         if (setOkState) {
@@ -377,15 +481,9 @@ public class AuthenticatorManager {
         return true;
     }
 
-    private AuthenticateResponse tryAuthenticationChainFallback(ConnectContext 
context,
-            String userName,
-            String remoteIp,
-            MysqlChannel channel,
-            MysqlSerializer serializer,
-            MysqlAuthPacket authPacket,
-            MysqlHandshakePacket handshakePacket,
-            AuthenticateRequest primaryRequest) throws IOException {
-        if (!hasAuthenticationChain()) {
+    private LoginResult tryAuthenticationChainFallback(String userName, 
AuthenticateRequest primaryRequest,
+            LoginCredentials credentials, List<AuthenticationFailureSummary> 
failures) throws IOException {
+        if 
(AuthenticationIntegrationAuthenticator.parseAuthenticationChain(Config.authentication_chain).isEmpty())
 {
             return null;
         }
 
@@ -394,69 +492,38 @@ public class AuthenticatorManager {
             chainAuthenticator = getAuthenticationChainAuthenticator();
         } catch (RuntimeException e) {
             LOG.warn("Failed to initialize authentication_chain fallback 
authenticator: {}", e.getMessage(), e);
-            return 
AuthenticateResponse.failed(AuthenticationFailureSummary.forFailureType(
-                    AuthenticationFailureType.MISCONFIGURED,
+            
failures.add(AuthenticationFailureSummary.forFailureType(AuthenticationFailureType.MISCONFIGURED,
                     "Failed to initialize authentication_chain fallback 
authenticator: " + e.getMessage()));
+            return null;
         }
         if (!chainAuthenticator.canDeal(userName)) {
             return null;
         }
 
-        AuthenticateRequest chainRequest = 
normalizeAuthenticationChainRequest(userName, channel, authPacket,
-                primaryRequest);
-        if (!canReuseRequestForAuthenticationChain(chainRequest)) {
-            Optional<AuthenticateRequest> fallbackRequest = 
resolveAuthenticateRequest(chainAuthenticator, userName,
-                    context, channel, serializer, authPacket, handshakePacket);
-            if (!fallbackRequest.isPresent()) {
-                return null;
-            }
-            chainRequest = fallbackRequest.get();
+        Optional<AuthenticateRequest> resolved = 
credentials.chain().resolve(chainAuthenticator, primaryRequest);
+        if (resolved.isEmpty()) {
+            return null;
         }
-
-        if (isOidcAuthenticationWithoutSsl(authPacket, chainRequest)) {
-            setInsecureOidcTransportError(context);
-            return AuthenticateResponse.failedResponse;
+        AuthenticateRequest chainRequest = resolved.get();
+        if (requiresSecureTokenTransport(chainRequest, credentials)) {
+            return new LoginResult(LoginStatus.TOKEN_TLS_REQUIRED, null, 
primaryRequest.getRemoteIp(),
+                    primaryRequest.getPassword(), failures);
         }
         LOG.info("Try authentication_chain fallback for user '{}'", userName);
-        return authenticateWith(chainAuthenticator, chainRequest);
-    }
-
-    private boolean hasAuthenticationChain() {
-        return 
!AuthenticationIntegrationAuthenticator.parseAuthenticationChain(Config.authentication_chain).isEmpty();
-    }
-
-    private boolean isOidcAuthenticationWithoutSsl(MysqlAuthPacket authPacket, 
AuthenticateRequest request) {
-        return isOidcAuthenticateRequest(request) && 
!authPacket.getCapability().isClientUseSsl();
-    }
-
-    private boolean isOidcAuthenticateRequest(AuthenticateRequest request) {
-        if (CredentialType.OIDC_ID_TOKEN.equals(request.getCredentialType())
-                || 
CredentialType.OAUTH_TOKEN.equals(request.getCredentialType())
-                || 
CredentialType.JWT_TOKEN.equals(request.getCredentialType())) {
-            return true;
-        }
-        if (!(request.getPassword() instanceof ClearPassword)) {
-            return false;
+        AuthenticateResponse response = authenticateWith(chainAuthenticator,
+                
chainRequest.withSecureTransport(credentials.secureTransport()));
+        if (response.isSuccess()) {
+            return new LoginResult(LoginStatus.CHAIN_SUCCESS, response, 
primaryRequest.getRemoteIp(), null, List.of());
         }
-        String clearPassword = ((ClearPassword) 
request.getPassword()).getPassword();
-        if (Strings.isNullOrEmpty(clearPassword)) {
-            return false;
-        }
-        return looksLikeJwt(clearPassword);
+        addFailureSummary(failures, response);
+        return null;
     }
 
-    private boolean looksLikeJwt(String token) {
-        if (!token.startsWith("eyJ")) {
-            return false;
-        }
-
-        int segmentSeparatorCount = 0;
-        for (int i = 0; i < token.length(); i++) {
-            if (token.charAt(i) == '.') {
-                segmentSeparatorCount++;
-            }
-        }
-        return segmentSeparatorCount == 2;
+    private boolean requiresSecureTokenTransport(AuthenticateRequest request, 
LoginCredentials credentials) {
+        String type = request.getCredentialType();
+        return !credentials.secureTransport() && 
(CredentialType.OIDC_ID_TOKEN.equalsIgnoreCase(type)
+                || CredentialType.OAUTH_TOKEN.equalsIgnoreCase(type)
+                || CredentialType.JWT_TOKEN.equalsIgnoreCase(type));
     }
 
     private void setInsecureOidcTransportError(ConnectContext context) {
@@ -464,6 +531,24 @@ public class AuthenticatorManager {
                 "OIDC authentication requires TLS/SSL; reconnect with 
sslMode=REQUIRED");
     }
 
+    private Optional<AuthenticateRequest> 
resolveAuthenticationChainRequest(Authenticator authenticator,
+            AuthenticateRequest primary, ConnectContext context, String 
userName, MysqlChannel channel,
+            MysqlSerializer serializer, MysqlAuthPacket authPacket, 
MysqlHandshakePacket handshakePacket)
+            throws IOException {
+        AuthenticateRequest normalized = 
normalizeAuthenticationChainRequest(userName, channel, authPacket, primary);
+        if 
(CredentialType.CLEAR_TEXT_PASSWORD.equals(normalized.getCredentialType())
+                || normalized.getPassword() instanceof ClearPassword) {
+            return Optional.of(normalized);
+        }
+        if (!channel.isSslMode() && authenticator instanceof 
AuthenticationIntegrationAuthenticator
+                && ((AuthenticationIntegrationAuthenticator) 
authenticator).requiresTlsForClearPasswordExchange()) {
+            // Try the existing credential without asking the client to send a 
new clear credential.
+            return Optional.of(normalized);
+        }
+        return resolveAuthenticateRequest(authenticator, userName, context, 
channel, serializer, authPacket,
+                handshakePacket);
+    }
+
     private AuthenticateRequest normalizeAuthenticationChainRequest(String 
userName, MysqlChannel channel,
             MysqlAuthPacket authPacket, AuthenticateRequest primaryRequest) {
         Optional<AuthenticateRequest> authPacketRequest =
@@ -488,13 +573,6 @@ public class AuthenticatorManager {
                 .build();
     }
 
-    private boolean canReuseRequestForAuthenticationChain(AuthenticateRequest 
request) {
-        if 
(CredentialType.CLEAR_TEXT_PASSWORD.equals(request.getCredentialType())) {
-            return true;
-        }
-        return request.getPassword() instanceof ClearPassword;
-    }
-
     private boolean reportAuthenticationFailure(ConnectContext context, String 
userName, String remoteIp,
             Password password, List<AuthenticationFailureSummary> 
failureSummaries) throws IOException {
         logAuthenticationFailureSummary(userName, remoteIp, failureSummaries);
@@ -507,10 +585,12 @@ public class AuthenticatorManager {
 
     private void ensureAuthenticationErrorReported(ConnectContext context, 
String userName, String remoteIp,
             Password password, List<AuthenticationFailureSummary> 
failureSummaries) {
-        Optional<String> clientVisibleFailureMessage = 
findClientVisibleFailureMessage(failureSummaries);
-        if (clientVisibleFailureMessage.isPresent()
-                && shouldExposeClientVisibleFailureMessage(context, 
failureSummaries)) {
-            context.getState().setError(ErrorCode.ERR_UNKNOWN_ERROR, 
clientVisibleFailureMessage.get());
+        Optional<AuthenticationFailureSummary> clientVisibleFailure = 
findClientVisibleFailure(failureSummaries);
+        if (clientVisibleFailure.isPresent() && 
shouldExposeClientVisibleFailureMessage(context, failureSummaries)) {
+            AuthenticationFailureSummary failure = clientVisibleFailure.get();
+            ErrorCode errorCode = failure.isSecureTransportRequired()
+                    ? ErrorCode.ERR_SECURE_TRANSPORT_REQUIRED : 
ErrorCode.ERR_UNKNOWN_ERROR;
+            context.getState().setError(errorCode, 
failure.getClientVisibleMessage());
             return;
         }
         if (context.getState().getStateType() == 
QueryState.MysqlStateType.ERR) {
@@ -532,10 +612,11 @@ public class AuthenticatorManager {
         failureSummaries.add(response.getFailureSummary());
     }
 
-    private Optional<String> 
findClientVisibleFailureMessage(List<AuthenticationFailureSummary> 
failureSummaries) {
+    private Optional<AuthenticationFailureSummary> findClientVisibleFailure(
+            List<AuthenticationFailureSummary> failureSummaries) {
         for (AuthenticationFailureSummary failureSummary : failureSummaries) {
             if (failureSummary.hasClientVisibleMessage()) {
-                return Optional.of(failureSummary.getClientVisibleMessage());
+                return Optional.of(failureSummary);
             }
         }
         return Optional.empty();
@@ -578,8 +659,10 @@ public class AuthenticatorManager {
         if (failureSummaries.isEmpty()) {
             return;
         }
+        // Provider exception messages can contain credentials. Log only the 
failure categories.
         LOG.warn("Authentication failed for user '{}' from '{}'. Failure 
summary: {}",
-                userName, remoteIp, failureSummaries);
+                userName, remoteIp, 
failureSummaries.stream().map(AuthenticationFailureSummary::getDiagnosticCode)
+                        .toList());
     }
 
     private boolean hasPassword(Password password) {
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/DefaultAuthenticator.java
 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/DefaultAuthenticator.java
index f7553b10420..52161f833b8 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/DefaultAuthenticator.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/DefaultAuthenticator.java
@@ -18,13 +18,16 @@
 package org.apache.doris.mysql.authenticate;
 
 import org.apache.doris.analysis.UserIdentity;
+import org.apache.doris.authentication.CredentialType;
 import org.apache.doris.catalog.Env;
 import org.apache.doris.common.AuthenticationException;
 import org.apache.doris.common.ErrorReport;
+import org.apache.doris.mysql.authenticate.password.ClearPassword;
 import org.apache.doris.mysql.authenticate.password.NativePassword;
 import org.apache.doris.mysql.authenticate.password.NativePasswordResolver;
 import org.apache.doris.mysql.authenticate.password.Password;
 import org.apache.doris.mysql.authenticate.password.PasswordResolver;
+import org.apache.doris.qe.ConnectContext;
 
 import com.google.common.collect.Lists;
 import org.apache.logging.log4j.LogManager;
@@ -47,27 +50,56 @@ public class DefaultAuthenticator implements Authenticator {
             LOG.debug("user:{} start to default authenticate.", 
request.getUserName());
         }
         Password password = request.getPassword();
-        if (!(password instanceof NativePassword)) {
-            return AuthenticateResponse.failedResponse;
-        }
-        NativePassword nativePassword = (NativePassword) password;
-
         List<UserIdentity> currentUserIdentity = Lists.newArrayList();
         try {
-            if (request.getUserIdentity() != null) {
-                
Env.getCurrentEnv().getAuth().checkPasswordForUserIdentity(request.getUserIdentity(),
-                        nativePassword.getRemotePasswd(), 
nativePassword.getRandomString(), currentUserIdentity);
+            if 
(CredentialType.CLEAR_TEXT_PASSWORD.equals(request.getCredentialType())
+                    && password instanceof ClearPassword) {
+                checkPlainPassword(request, (ClearPassword) password, 
currentUserIdentity);
+            } else if (password instanceof NativePassword) {
+                checkNativePassword(request, (NativePassword) password, 
currentUserIdentity);
             } else {
-                
Env.getCurrentEnv().getAuth().checkPassword(request.getUserName(), 
request.getRemoteIp(),
-                        nativePassword.getRemotePasswd(), 
nativePassword.getRandomString(), currentUserIdentity);
+                return AuthenticateResponse.failedResponse;
             }
         } catch (AuthenticationException e) {
-            ErrorReport.report(e.errorCode, e.msgs);
+            if (ConnectContext.get() == null) {
+                // Single-step protocols have no MySQL QueryState. Only log 
the server's error code.
+                LOG.warn("Local password authentication refused from '{}': {}",
+                        request.getRemoteIp(), e.errorCode);
+            } else {
+                ErrorReport.report(e.errorCode, e.msgs);
+            }
             return AuthenticateResponse.failedResponse;
         }
         return new AuthenticateResponse(true, currentUserIdentity.get(0));
     }
 
+    private void checkPlainPassword(AuthenticateRequest request, ClearPassword 
clearPassword,
+            List<UserIdentity> currentUserIdentity) throws 
AuthenticationException {
+        if (request.getUserIdentity() != null) {
+            
Env.getCurrentEnv().getAuth().checkPlainPasswordForUserIdentity(request.getUserIdentity(),
+                    clearPassword.getPassword(), currentUserIdentity);
+        } else {
+            
Env.getCurrentEnv().getAuth().checkLocalPlainPassword(request.getUserName(), 
request.getRemoteIp(),
+                    clearPassword.getPassword(), currentUserIdentity);
+        }
+    }
+
+    private void checkNativePassword(AuthenticateRequest request, 
NativePassword nativePassword,
+            List<UserIdentity> currentUserIdentity) throws 
AuthenticationException {
+        if (request.getUserIdentity() != null) {
+            
Env.getCurrentEnv().getAuth().checkPasswordForUserIdentity(request.getUserIdentity(),
+                    nativePassword.getRemotePasswd(), 
nativePassword.getRandomString(), currentUserIdentity);
+        } else {
+            Env.getCurrentEnv().getAuth().checkPassword(request.getUserName(), 
request.getRemoteIp(),
+                    nativePassword.getRemotePasswd(), 
nativePassword.getRandomString(), currentUserIdentity);
+        }
+    }
+
+    @Override
+    public boolean acceptsSingleStepRequest() {
+        return true;
+    }
+
     @Override
     public boolean canDeal(String qualifiedUser) {
         return true;
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/integration/AuthenticationIntegrationAuthenticator.java
 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/integration/AuthenticationIntegrationAuthenticator.java
index d0b397954c7..5b78d0fd7ad 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/integration/AuthenticationIntegrationAuthenticator.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/integration/AuthenticationIntegrationAuthenticator.java
@@ -23,6 +23,8 @@ import 
org.apache.doris.authentication.AuthenticationFailureType;
 import org.apache.doris.authentication.AuthenticationIntegration;
 import org.apache.doris.authentication.AuthenticationIntegrationMeta;
 import org.apache.doris.authentication.AuthenticationRequest;
+import org.apache.doris.authentication.AuthenticationTransportPolicy;
+import 
org.apache.doris.authentication.AuthenticationTransportPolicy.SecureTransportRequiredException;
 import org.apache.doris.authentication.Principal;
 import org.apache.doris.authentication.handler.AuthenticationOutcome;
 import org.apache.doris.catalog.Env;
@@ -85,7 +87,7 @@ public class AuthenticationIntegrationAuthenticator 
implements Authenticator {
         return binding != null;
     }
 
-    /** Resolve credential requirements before asking the client to supply any 
clear text. */
+    /** Prepare the resolver and report whether this binding requires a 
protected connection. */
     public boolean prepareBoundAuthentication() throws AuthenticationException 
{
         AuthenticationIntegrationMeta meta = 
Env.getCurrentEnv().getAuthenticationIntegrationMgr()
                 .getAuthenticationIntegration(binding.getAuthIntegration());
@@ -96,7 +98,18 @@ public class AuthenticationIntegrationAuthenticator 
implements Authenticator {
         boolean clear = 
Env.getCurrentEnv().getAuthenticationIntegrationRuntime().requiresClearPassword(meta);
         passwordResolver = new AuthPacketAwarePasswordResolver(clear
                 ? new ClearPasswordResolver() : new NativePasswordResolver());
-        return clear;
+        return clear || 
AuthenticationTransportPolicy.requiresSecureTransport(meta.getType());
+    }
+
+    /** Avoid a clear credential exchange when every integration in the chain 
needs TLS. */
+    public boolean requiresTlsForClearPasswordExchange() {
+        try {
+            return resolveAuthenticationChain().stream()
+                    .allMatch(meta -> 
AuthenticationTransportPolicy.requiresSecureTransport(meta.getType()));
+        } catch (AuthenticationException e) {
+            // The runtime will report the broken chain without a new clear 
credential.
+            return true;
+        }
     }
 
     @Override
@@ -123,10 +136,12 @@ public class AuthenticationIntegrationAuthenticator 
implements Authenticator {
         AuthenticationOutcome outcome;
         try {
             outcome = Env.getCurrentEnv().getAuthenticationIntegrationRuntime()
-                    .authenticate(resolveAuthenticationChain(), 
integrationRequest);
+                    .authenticate(resolveAuthenticationChain(), 
integrationRequest, request.isSecureTransport());
+        } catch (SecureTransportRequiredException e) {
+            return 
AuthenticateResponse.failed(AuthenticationFailureSummary.secureTransportRequired());
         } catch (AuthenticationException e) {
             LOG.warn("Authentication integration chain failed for user '{}': 
{}", request.getUserName(),
-                    e.getMessage());
+                    e.getFailureType());
             return 
AuthenticateResponse.failed(AuthenticationFailureSummary.forException(e,
                     "Authentication integration chain failed"));
         }
@@ -144,7 +159,7 @@ public class AuthenticationIntegrationAuthenticator 
implements Authenticator {
                 LOG.info("Authentication integration '{}' rejected user '{}': 
{}",
                         outcome.getIntegration().getName(),
                         request.getUserName(),
-                        outcome.getAuthResult().getException().getMessage());
+                        
outcome.getAuthResult().getException().getFailureType());
                 return 
AuthenticateResponse.failed(summarizeFailure(outcome.getIntegration(),
                         outcome.getAuthResult().getException(),
                         "Authentication integration '" + 
outcome.getIntegration().getName()
@@ -159,6 +174,11 @@ public class AuthenticationIntegrationAuthenticator 
implements Authenticator {
         return mapSuccessfulAuthentication(request.getUserName(), 
request.getRemoteIp(), outcome);
     }
 
+    @Override
+    public boolean acceptsSingleStepRequest() {
+        return true;
+    }
+
     @Override
     public boolean canDeal(String qualifiedUser) {
         return !Auth.ROOT_USER.equals(qualifiedUser) && 
!Auth.ADMIN_USER.equals(qualifiedUser);
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/ldap/LdapAuthenticator.java
 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/ldap/LdapAuthenticator.java
index b5502f7bcaf..dd449cf4428 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/ldap/LdapAuthenticator.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/ldap/LdapAuthenticator.java
@@ -77,6 +77,11 @@ public class LdapAuthenticator implements Authenticator {
         return response;
     }
 
+    @Override
+    public boolean acceptsSingleStepRequest() {
+        return true;
+    }
+
     @Override
     public boolean canDeal(String qualifiedUser) {
         if (qualifiedUser.equals(Auth.ROOT_USER) || 
qualifiedUser.equals(Auth.ADMIN_USER)) {
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/plugin/AuthenticationPluginAuthenticator.java
 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/plugin/AuthenticationPluginAuthenticator.java
index 10883c18d01..d6f0ad2cf50 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/plugin/AuthenticationPluginAuthenticator.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/plugin/AuthenticationPluginAuthenticator.java
@@ -23,6 +23,7 @@ import 
org.apache.doris.authentication.AuthenticationFailureType;
 import org.apache.doris.authentication.AuthenticationIntegration;
 import org.apache.doris.authentication.AuthenticationRequest;
 import org.apache.doris.authentication.AuthenticationResult;
+import org.apache.doris.authentication.AuthenticationTransportPolicy;
 import org.apache.doris.authentication.CredentialType;
 import org.apache.doris.authentication.Principal;
 import org.apache.doris.authentication.handler.AuthenticationPluginManager;
@@ -91,6 +92,9 @@ public class AuthenticationPluginAuthenticator implements 
Authenticator {
 
     @Override
     public AuthenticateResponse authenticate(AuthenticateRequest request) 
throws IOException {
+        if (requiresSecureTransport() && !request.isSecureTransport()) {
+            return 
AuthenticateResponse.failed(AuthenticationFailureSummary.secureTransportRequired());
+        }
         if 
(Env.getCurrentEnv().getAuth().getAuthenticationBinding(request.getUserName(), 
request.getRemoteIp())
                 != null) {
             return AuthenticateResponse.failedResponse;
@@ -107,7 +111,7 @@ public class AuthenticationPluginAuthenticator implements 
Authenticator {
             result = plugin.authenticate(pluginRequest, integration);
         } catch (AuthenticationException e) {
             LOG.warn("Authentication plugin '{}' failed for user '{}': {}", 
integration.getType(),
-                    request.getUserName(), e.getMessage(), e);
+                    request.getUserName(), e.getFailureType());
             return 
AuthenticateResponse.failed(AuthenticationFailureSummary.forException(e,
                     "Authentication plugin '" + integration.getType() + "' 
failed"));
         }
@@ -122,7 +126,7 @@ public class AuthenticationPluginAuthenticator implements 
Authenticator {
         if (!result.isSuccess()) {
             if (result.getException() != null) {
                 LOG.info("Authentication plugin '{}' rejected user '{}': {}", 
integration.getType(),
-                        request.getUserName(), 
result.getException().getMessage());
+                        request.getUserName(), 
result.getException().getFailureType());
                 return 
AuthenticateResponse.failed(summarizeFailure(result.getException(),
                         "Authentication plugin '" + integration.getType() + "' 
rejected the credential"));
             }
@@ -134,6 +138,16 @@ public class AuthenticationPluginAuthenticator implements 
Authenticator {
         return mapSuccessfulAuthentication(request.getUserName(), 
request.getRemoteIp(), result);
     }
 
+    @Override
+    public boolean acceptsSingleStepRequest() {
+        return true;
+    }
+
+    @Override
+    public boolean requiresSecureTransport() {
+        return 
AuthenticationTransportPolicy.requiresSecureTransport(integration.getType());
+    }
+
     @Override
     public boolean canDeal(String qualifiedUser) {
         return !Auth.ROOT_USER.equals(qualifiedUser) && 
!Auth.ADMIN_USER.equals(qualifiedUser);
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/mysql/privilege/Auth.java 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/privilege/Auth.java
index aabc9773e85..c3b8fdc627d 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/mysql/privilege/Auth.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/mysql/privilege/Auth.java
@@ -258,12 +258,17 @@ public class Auth implements Writable {
                 checkAccountLocked(currentUser.get(0));
             }
         } else {
-            readLock();
-            try {
-                userManager.checkPlainPassword(remoteUser, remoteHost, 
remotePasswd, currentUser);
-            } finally {
-                readUnlock();
-            }
+            checkLocalPlainPassword(remoteUser, remoteHost, remotePasswd, 
currentUser);
+        }
+    }
+
+    public void checkLocalPlainPassword(String remoteUser, String remoteHost, 
String remotePasswd,
+            List<UserIdentity> currentUser) throws AuthenticationException {
+        readLock();
+        try {
+            userManager.checkPlainPassword(remoteUser, remoteHost, 
remotePasswd, currentUser);
+        } finally {
+            readUnlock();
         }
     }
 
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/arrowflight/DorisFlightSqlProducerTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/arrowflight/DorisFlightSqlProducerTest.java
index 071c3744ec7..6319fd97bf2 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/arrowflight/DorisFlightSqlProducerTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/arrowflight/DorisFlightSqlProducerTest.java
@@ -18,7 +18,6 @@
 package org.apache.doris.arrowflight;
 
 import org.apache.doris.analysis.UserIdentity;
-import org.apache.doris.arrowflight.auth2.FlightAuthResult;
 import org.apache.doris.arrowflight.protocol.FlightProtocolAdapter;
 import org.apache.doris.arrowflight.results.FlightSqlChannel;
 import org.apache.doris.arrowflight.results.FlightSqlEndpointsLocation;
@@ -32,6 +31,7 @@ import org.apache.doris.common.IncrWindowNotReadyException;
 import org.apache.doris.common.Status;
 import org.apache.doris.common.util.DebugUtil;
 import org.apache.doris.mysql.MysqlCommand;
+import org.apache.doris.mysql.authenticate.AuthenticateResponse;
 import org.apache.doris.qe.ConnectContext;
 import org.apache.doris.qe.ConnectPoolTestSupport;
 import org.apache.doris.qe.ConnectScheduler;
@@ -224,7 +224,7 @@ public class DorisFlightSqlProducerTest {
 
         FlightSessionsManager sessionsManager = new FlightSessionsManager() {
             @Override
-            public String openSession(FlightAuthResult authResult) {
+            public String openSession(AuthenticateResponse response, String 
remoteIp) {
                 throw new UnsupportedOperationException("not exercised by this 
test");
             }
 
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/arrowflight/auth2/FlightBearerTokenAuthenticatorTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/arrowflight/auth2/FlightBearerTokenAuthenticatorTest.java
new file mode 100644
index 00000000000..feb083eeb93
--- /dev/null
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/arrowflight/auth2/FlightBearerTokenAuthenticatorTest.java
@@ -0,0 +1,99 @@
+// 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.arrowflight.auth2;
+
+import org.apache.doris.analysis.UserIdentity;
+import org.apache.doris.arrowflight.sessions.FlightSessionsManager;
+import org.apache.doris.authentication.AuthenticationFailureType;
+import org.apache.doris.authentication.CredentialType;
+import org.apache.doris.mysql.authenticate.AuthenticateRequest;
+import org.apache.doris.mysql.authenticate.AuthenticateResponse;
+import org.apache.doris.mysql.authenticate.AuthenticationFailureSummary;
+import org.apache.doris.mysql.authenticate.AuthenticatorManager;
+
+import org.apache.arrow.flight.FlightCallHeaders;
+import org.apache.arrow.flight.FlightRuntimeException;
+import org.apache.arrow.flight.FlightStatusCode;
+import org.apache.arrow.flight.auth2.Auth2Constants;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+
+class FlightBearerTokenAuthenticatorTest {
+    private final FlightSessionsManager sessions = 
Mockito.mock(FlightSessionsManager.class);
+    private final AuthenticatorManager authenticator = 
Mockito.mock(AuthenticatorManager.class);
+    private final FlightBearerTokenAuthenticator headers = new 
FlightBearerTokenAuthenticator(sessions, authenticator);
+
+    @Test
+    void testBasicUsesSharedAuthenticatorAndBearerOnlyLooksUpSession() throws 
Exception {
+        UserIdentity user = 
UserIdentity.createAnalyzedUserIdentWithIp("alice", "%");
+        AuthenticateResponse accepted = new AuthenticateResponse(true, user);
+        
Mockito.when(authenticator.authenticate(Mockito.any(AuthenticateRequest.class), 
Mockito.eq(false)))
+                .thenReturn(accepted);
+        Mockito.when(sessions.openSession(Mockito.eq(accepted), 
Mockito.anyString())).thenReturn("session-token");
+
+        FlightCallHeaders outgoing = new FlightCallHeaders();
+        headers.authenticate(basic("null")).appendToOutgoingHeaders(outgoing);
+        Assertions.assertEquals("Bearer session-token", 
outgoing.get(Auth2Constants.AUTHORIZATION_HEADER));
+
+        ArgumentCaptor<AuthenticateRequest> request = 
ArgumentCaptor.forClass(AuthenticateRequest.class);
+        Mockito.verify(authenticator).authenticate(request.capture(), 
Mockito.eq(false));
+        Assertions.assertEquals("alice", request.getValue().getUserName());
+        Assertions.assertEquals("arrow-flight-sql", 
request.getValue().getClientType());
+        Assertions.assertEquals(CredentialType.CLEAR_TEXT_PASSWORD, 
request.getValue().getCredentialType());
+        Assertions.assertArrayEquals(new byte[0], 
request.getValue().getCredential());
+
+        Assertions.assertEquals("session-token", 
headers.authenticate(outgoing).getPeerIdentity());
+        Mockito.verify(sessions).getConnectContext("session-token");
+        Mockito.verifyNoMoreInteractions(authenticator);
+    }
+
+    @Test
+    void 
testTypedCredentialReachesSharedAuthenticatorAndRejectionCreatesNoSession() 
throws Exception {
+        FlightCallHeaders requestHeaders = basic("fixture-token");
+        
requestHeaders.insert(FlightBearerTokenAuthenticator.CREDENTIAL_TYPE_HEADER, 
CredentialType.OAUTH_TOKEN);
+        
Mockito.when(authenticator.authenticate(Mockito.any(AuthenticateRequest.class), 
Mockito.eq(false)))
+                
.thenReturn(AuthenticateResponse.failed(AuthenticationFailureSummary.forClientVisibleFailure(
+                        AuthenticationFailureType.ACCESS_DENIED, "secure 
transport required",
+                        "secure transport required")));
+
+        FlightRuntimeException refusal = 
Assertions.assertThrows(FlightRuntimeException.class,
+                () -> headers.authenticate(requestHeaders));
+        Assertions.assertEquals(FlightStatusCode.UNAUTHENTICATED, 
refusal.status().code());
+        Assertions.assertTrue(refusal.status().description().contains("secure 
transport"));
+
+        ArgumentCaptor<AuthenticateRequest> request = 
ArgumentCaptor.forClass(AuthenticateRequest.class);
+        Mockito.verify(authenticator).authenticate(request.capture(), 
Mockito.eq(false));
+        Assertions.assertEquals(CredentialType.OAUTH_TOKEN, 
request.getValue().getCredentialType());
+        
Assertions.assertArrayEquals("fixture-token".getBytes(StandardCharsets.UTF_8),
+                request.getValue().getCredential());
+        Assertions.assertNull(request.getValue().getPassword());
+        Mockito.verifyNoInteractions(sessions);
+    }
+
+    private static FlightCallHeaders basic(String credential) {
+        FlightCallHeaders headers = new FlightCallHeaders();
+        String encoded = Base64.getEncoder().encodeToString(("alice:" + 
credential).getBytes(StandardCharsets.UTF_8));
+        headers.insert(Auth2Constants.AUTHORIZATION_HEADER, "Basic " + 
encoded);
+        return headers;
+    }
+}
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/arrowflight/sessions/FlightSessionsInConnectPoolTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/arrowflight/sessions/FlightSessionsInConnectPoolTest.java
index f171c602b27..09ef60f2cfc 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/arrowflight/sessions/FlightSessionsInConnectPoolTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/arrowflight/sessions/FlightSessionsInConnectPoolTest.java
@@ -18,11 +18,13 @@
 package org.apache.doris.arrowflight.sessions;
 
 import org.apache.doris.analysis.UserIdentity;
-import org.apache.doris.arrowflight.auth2.FlightAuthResult;
+import org.apache.doris.authentication.BasicPrincipal;
 import org.apache.doris.catalog.Env;
 import org.apache.doris.common.FeConstants;
 import org.apache.doris.common.Status;
 import org.apache.doris.common.util.TokenMasker;
+import org.apache.doris.mysql.authenticate.AuthenticateResponse;
+import org.apache.doris.mysql.privilege.UserPropertyMgr;
 import org.apache.doris.qe.ConnectContext;
 import org.apache.doris.qe.ConnectContext.ConnectType;
 import org.apache.doris.qe.ConnectPoolTestSupport;
@@ -39,6 +41,8 @@ import org.mockito.ArgumentCaptor;
 import org.mockito.MockedStatic;
 import org.mockito.Mockito;
 
+import java.util.Set;
+
 /**
  * A bearer token is the name an Arrow Flight SQL session is registered in the 
connection pool
  * under, and nothing else: it is issued by opening the session and is invalid 
the moment the
@@ -46,7 +50,8 @@ import org.mockito.Mockito;
  */
 public class FlightSessionsInConnectPoolTest {
     private static final UserIdentity ALICE = 
UserIdentity.createAnalyzedUserIdentWithIp("alice", "%");
-    private static final FlightAuthResult ALICE_AUTH = 
FlightAuthResult.of("alice", ALICE, "10.26.20.3");
+    private static final AuthenticateResponse ALICE_AUTH = new 
AuthenticateResponse(true, ALICE);
+    private static final String REMOTE_IP = "10.26.20.3";
 
     private boolean savedRunningUnitTest;
     private MockedStatic<Env> mockedEnv;
@@ -79,7 +84,7 @@ public class FlightSessionsInConnectPoolTest {
         ConnectScheduler scheduler = new ConnectScheduler(10, 5);
         FlightSessionsInConnectPool sessions = new 
FlightSessionsInConnectPool(scheduler);
 
-        String token = sessions.openSession(ALICE_AUTH);
+        String token = sessions.openSession(ALICE_AUTH, REMOTE_IP);
         ConnectContext ctx = sessions.getConnectContext(token);
 
         Assertions.assertSame(scheduler.getContextWithPeerIdentity(token), 
ctx);
@@ -93,13 +98,36 @@ public class FlightSessionsInConnectPoolTest {
         Assertions.assertEquals(1, 
scheduler.getConnectPoolMgr().getFlightConnectionNum());
 
         // Every session has a token of its own, and each names only its own 
session.
-        String other = sessions.openSession(ALICE_AUTH);
+        String other = sessions.openSession(ALICE_AUTH, REMOTE_IP);
         Assertions.assertNotEquals(token, other);
         Assertions.assertNotSame(ctx, sessions.getConnectContext(other));
         Assertions.assertSame(ctx, sessions.getConnectContext(token));
         Assertions.assertEquals(2, scheduler.getConnectionNum());
     }
 
+    @Test
+    public void testTemporaryPrincipalIsVisibleDuringConnectionAdmission() {
+        BasicPrincipal principal = 
BasicPrincipal.builder().name("alice").authenticator("test_integration").build();
+        AuthenticateResponse authenticated = new AuthenticateResponse(true, 
ALICE, true, principal, Set.of("reader"));
+        UserPropertyMgr properties = new UserPropertyMgr();
+        Assertions.assertEquals(0L, properties.getMaxConn("alice"));
+        Mockito.when(env.getAuth().getMaxConn("alice")).thenAnswer(ignored -> 
properties.getMaxConn("alice"));
+        
Mockito.when(env.getAuth().getQueryTimeout("alice")).thenAnswer(ignored -> {
+            Assertions.assertSame(principal, 
ConnectContext.get().getAuthenticatedPrincipal());
+            return properties.getQueryTimeout("alice");
+        });
+        ConnectContext previous = ConnectContext.get();
+        FlightSessionsInConnectPool sessions = new 
FlightSessionsInConnectPool(new ConnectScheduler(10, 5));
+
+        String token = sessions.openSession(authenticated, REMOTE_IP);
+        ConnectContext context = sessions.getConnectContext(token);
+        Assertions.assertTrue(context.getIsTempUser());
+        Assertions.assertSame(principal, context.getAuthenticatedPrincipal());
+        Assertions.assertEquals(Set.of("reader"), 
context.getAuthenticatedRoles());
+        Assertions.assertSame(previous, ConnectContext.get());
+        sessions.closeConnectContext(token);
+    }
+
     @Test
     public void testATokenNoSessionIsRegisteredUnderIsUnauthenticated() {
         FlightSessionsInConnectPool sessions = new 
FlightSessionsInConnectPool(new ConnectScheduler(10, 5));
@@ -119,7 +147,7 @@ public class FlightSessionsInConnectPoolTest {
     public void testCloseSessionEndsTheSessionAndWithItTheToken() {
         ConnectScheduler scheduler = new ConnectScheduler(10, 5);
         FlightSessionsInConnectPool sessions = new 
FlightSessionsInConnectPool(scheduler);
-        String token = sessions.openSession(ALICE_AUTH);
+        String token = sessions.openSession(ALICE_AUTH, REMOTE_IP);
         ConnectContext ctx = sessions.getConnectContext(token);
         // A statement may still be running on another thread when the client 
closes the session.
         StmtExecutor running = Mockito.mock(StmtExecutor.class);
@@ -143,7 +171,7 @@ public class FlightSessionsInConnectPoolTest {
     public void testKillConnectionEndsTheToken() {
         ConnectScheduler scheduler = new ConnectScheduler(10, 5);
         FlightSessionsInConnectPool sessions = new 
FlightSessionsInConnectPool(scheduler);
-        String token = sessions.openSession(ALICE_AUTH);
+        String token = sessions.openSession(ALICE_AUTH, REMOTE_IP);
 
         sessions.getConnectContext(token).kill(true);
 
@@ -155,7 +183,7 @@ public class FlightSessionsInConnectPoolTest {
     public void testWaitTimeoutEndsTheToken() {
         ConnectScheduler scheduler = new ConnectScheduler(10, 5);
         FlightSessionsInConnectPool sessions = new 
FlightSessionsInConnectPool(scheduler);
-        String token = sessions.openSession(ALICE_AUTH);
+        String token = sessions.openSession(ALICE_AUTH, REMOTE_IP);
         ConnectContext ctx = sessions.getConnectContext(token);
         long waitTimeoutMs = ctx.getSessionVariable().getWaitTimeoutS() * 
1000L;
 
@@ -176,10 +204,10 @@ public class FlightSessionsInConnectPoolTest {
     public void testASessionThatDoesNotFitIsRefusedAndLeavesNothing() {
         ConnectScheduler scheduler = new ConnectScheduler(10, 1);
         FlightSessionsInConnectPool sessions = new 
FlightSessionsInConnectPool(scheduler);
-        String first = sessions.openSession(ALICE_AUTH);
+        String first = sessions.openSession(ALICE_AUTH, REMOTE_IP);
 
         FlightRuntimeException refused = 
Assertions.assertThrows(FlightRuntimeException.class,
-                () -> sessions.openSession(ALICE_AUTH));
+                () -> sessions.openSession(ALICE_AUTH, REMOTE_IP));
 
         Assertions.assertEquals(FlightStatusCode.RESOURCE_EXHAUSTED, 
refused.status().code());
         Assertions.assertEquals("Reach limit of connections. Total: 10, User: 
100, Current: 1, Arrow Flight SQL: 1"
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/authentication/AuthenticationIntegrationRuntimeTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/authentication/AuthenticationIntegrationRuntimeTest.java
index de91062c439..63b57c6924c 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/authentication/AuthenticationIntegrationRuntimeTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/authentication/AuthenticationIntegrationRuntimeTest.java
@@ -94,6 +94,43 @@ class AuthenticationIntegrationRuntimeTest {
         Assertions.assertEquals("second", outcome.getIntegration().getName());
     }
 
+    @Test
+    void testPlaintextChainSkipsIamBeforeLdap() throws Exception {
+        AuthenticationIntegrationMeta iam = meta("corp_iam", "aws_iam", 
Collections.emptyMap());
+        AuthenticationIntegrationMeta ldap = meta("corp_ldap", "ldap", 
Collections.emptyMap());
+        AuthenticationPlugin iamPlugin = 
Mockito.mock(AuthenticationPlugin.class);
+        AuthenticationPlugin ldapPlugin = 
Mockito.mock(AuthenticationPlugin.class);
+        AuthenticationPluginManager pluginManager = 
Mockito.mock(AuthenticationPluginManager.class);
+        Mockito.when(pluginManager.hasFactory("aws_iam")).thenReturn(true);
+        Mockito.when(pluginManager.hasFactory("ldap")).thenReturn(true);
+        Mockito.when(pluginManager.getPlugin(Mockito.argThat(
+                integration -> integration != null && 
integration.getType().equals("aws_iam"))))
+                .thenReturn(iamPlugin);
+        Mockito.when(pluginManager.getPlugin(Mockito.argThat(
+                integration -> integration != null && 
integration.getType().equals("ldap"))))
+                .thenReturn(ldapPlugin);
+
+        AuthenticationRequest request = request();
+        Mockito.when(iamPlugin.supports(request)).thenReturn(true);
+        Mockito.when(ldapPlugin.supports(request)).thenReturn(true);
+        Mockito.when(ldapPlugin.authenticate(Mockito.eq(request), 
Mockito.any())).thenReturn(
+                
AuthenticationResult.success(BasicPrincipal.builder().name("alice").authenticator("corp_ldap").build()),
+                
AuthenticationResult.failure(AuthenticationFailureType.USER_NOT_FOUND, "User 
not found"),
+                
AuthenticationResult.failure(AuthenticationFailureType.BAD_CREDENTIAL, "Bad 
credential"));
+
+        AuthenticationIntegrationRuntime runtime = new 
AuthenticationIntegrationRuntime(pluginManager);
+        List<AuthenticationIntegrationMeta> chain = Arrays.asList(iam, ldap);
+        AuthenticationOutcome accepted = runtime.authenticate(chain, request, 
false);
+        Assertions.assertTrue(accepted.isSuccess());
+        Assertions.assertEquals("corp_ldap", 
accepted.getIntegration().getName());
+        
Assertions.assertThrows(AuthenticationTransportPolicy.SecureTransportRequiredException.class,
+                () -> runtime.authenticate(chain, request, false));
+        AuthenticationOutcome refused = runtime.authenticate(chain, request, 
false);
+        Assertions.assertEquals(AuthenticationFailureType.BAD_CREDENTIAL,
+                refused.getAuthResult().getException().getFailureType());
+        Mockito.verify(iamPlugin, Mockito.never()).authenticate(Mockito.any(), 
Mockito.any());
+    }
+
     @Test
     void testAuthenticateStopsOnBadCredential() throws Exception {
         AuthenticationPluginManager pluginManager = new 
AuthenticationPluginManager();
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/authentication/UserAuthenticationBindingTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/authentication/UserAuthenticationBindingTest.java
index 9e788e45f08..5ee7709a136 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/authentication/UserAuthenticationBindingTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/authentication/UserAuthenticationBindingTest.java
@@ -18,11 +18,13 @@
 package org.apache.doris.authentication;
 
 import org.apache.doris.analysis.UserIdentity;
-import org.apache.doris.arrowflight.auth2.FlightAuthUtils;
+import org.apache.doris.arrowflight.auth2.FlightCredentialValidator;
+import org.apache.doris.arrowflight.sessions.FlightSessionsManager;
 import org.apache.doris.authentication.handler.AuthenticationPluginManager;
 import org.apache.doris.authentication.spi.AuthenticationPlugin;
 import org.apache.doris.authentication.spi.AuthenticationPluginFactory;
 import org.apache.doris.catalog.Env;
+import org.apache.doris.common.Config;
 import org.apache.doris.common.DdlException;
 import org.apache.doris.common.io.Text;
 import org.apache.doris.datasource.InternalCatalog;
@@ -30,6 +32,7 @@ import org.apache.doris.metric.MetricRepo;
 import org.apache.doris.mysql.MysqlPassword;
 import org.apache.doris.mysql.authenticate.AuthenticateRequest;
 import org.apache.doris.mysql.authenticate.AuthenticateResponse;
+import org.apache.doris.mysql.authenticate.AuthenticatorManager;
 import 
org.apache.doris.mysql.authenticate.integration.AuthenticationIntegrationAuthenticator;
 import org.apache.doris.mysql.authenticate.ldap.LdapAuthenticator;
 import org.apache.doris.mysql.authenticate.ldap.LdapManager;
@@ -53,7 +56,7 @@ import org.apache.doris.qe.SqlModeHelper;
 import com.google.gson.JsonElement;
 import com.google.gson.JsonObject;
 import org.apache.arrow.flight.FlightRuntimeException;
-import org.apache.logging.log4j.LogManager;
+import org.apache.arrow.flight.FlightStatusCode;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.BeforeEach;
@@ -181,8 +184,45 @@ class UserAuthenticationBindingTest {
                 () -> auth.checkPassword("alice", "10.1.2.3", new byte[0], new 
byte[20], null));
         Assertions.assertThrows(DdlException.class,
                 () -> auth.setPassword(user("alice").getUserIdentity(), 
MysqlPassword.makeScrambledPassword("new")));
-        Assertions.assertThrows(FlightRuntimeException.class, () -> 
FlightAuthUtils.authenticateCredentials(
-                "alice", "external", "10.1.2.3", 
LogManager.getLogger(getClass())));
+        FlightSessionsManager sessions = 
Mockito.mock(FlightSessionsManager.class);
+        FlightCredentialValidator flight = new FlightCredentialValidator(new 
AuthenticatorManager("default"), sessions);
+        FlightRuntimeException refusal = 
Assertions.assertThrows(FlightRuntimeException.class,
+                () -> flight.validate("alice", "external"));
+        Assertions.assertEquals(FlightStatusCode.UNAUTHENTICATED, 
refusal.status().code());
+        Assertions.assertTrue(refusal.status().description().contains("secure 
transport"));
+        Mockito.verifyNoInteractions(sessions);
+    }
+
+    @Test
+    void 
testFlightUsesLocalPasswordBeforeConfiguredChainAndPreservesJitIdentity() 
throws Exception {
+        execute("CREATE USER 'alice' IDENTIFIED BY 'local-secret'");
+        java.util.Map<String, String> properties = new java.util.HashMap<>();
+        properties.put("type", "binding_test");
+        properties.put("enable_jit_user", "true");
+        integrations.createAuthenticationIntegration("jit", false, properties, 
"", "root");
+        FlightSessionsManager sessions = 
Mockito.mock(FlightSessionsManager.class);
+        FlightCredentialValidator flight = new FlightCredentialValidator(new 
AuthenticatorManager("default"), sessions);
+
+        String savedChain = Config.authentication_chain;
+        Config.authentication_chain = "jit";
+        try {
+            flight.validate("alice", "local-secret");
+            flight.validate("alice", "external");
+            flight.validate("new_user", "external");
+        } finally {
+            Config.authentication_chain = savedChain;
+        }
+
+        ArgumentCaptor<AuthenticateResponse> result = 
ArgumentCaptor.forClass(AuthenticateResponse.class);
+        Mockito.verify(sessions, 
Mockito.times(3)).openSession(result.capture(), Mockito.anyString());
+        java.util.List<AuthenticateResponse> responses = result.getAllValues();
+        Assertions.assertEquals(user("alice").getUserIdentity(), 
responses.get(0).getUserIdentity());
+        Assertions.assertNull(responses.get(0).getPrincipal());
+        Assertions.assertEquals(user("alice").getUserIdentity(), 
responses.get(1).getUserIdentity());
+        Assertions.assertEquals("external", 
responses.get(1).getPrincipal().getExternalPrincipal().orElseThrow());
+        Assertions.assertTrue(responses.get(2).isTemp());
+        Assertions.assertEquals("new_user", 
responses.get(2).getUserIdentity().getQualifiedUser());
+        Assertions.assertSame(context, ConnectContext.get());
     }
 
     @Test
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/mysql/ConnectionExceedTest.java 
b/fe/fe-core/src/test/java/org/apache/doris/mysql/ConnectionExceedTest.java
index dd50ff6a991..5366e0c40f5 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/mysql/ConnectionExceedTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/ConnectionExceedTest.java
@@ -18,11 +18,11 @@
 package org.apache.doris.mysql;
 
 import org.apache.doris.analysis.UserIdentity;
-import org.apache.doris.arrowflight.auth2.FlightAuthResult;
 import org.apache.doris.arrowflight.sessions.FlightSessionsInConnectPool;
 import org.apache.doris.catalog.Env;
 import org.apache.doris.common.ErrorCode;
 import org.apache.doris.datasource.InternalCatalog;
+import org.apache.doris.mysql.authenticate.AuthenticateResponse;
 import org.apache.doris.mysql.privilege.Auth;
 import org.apache.doris.mysql.protocol.MysqlProtocolAdapter;
 import org.apache.doris.qe.ConnectContext;
@@ -145,7 +145,7 @@ public class ConnectionExceedTest {
             mockedEnvStatic.when(Env::getCurrentEnv).thenReturn(mockEnv);
 
             UserIdentity userIdentity = 
UserIdentity.createAnalyzedUserIdentWithIp("test_user", "%");
-            FlightAuthResult authResult = FlightAuthResult.of("test_user", 
userIdentity, "127.0.0.1");
+            AuthenticateResponse authResult = new AuthenticateResponse(true, 
userIdentity);
 
             // Two Flight sessions fill the sub-quota, next to a MySQL 
connection of the same user: the
             // refusal has to tell the Flight usage from the pool's count.
@@ -156,13 +156,13 @@ public class ConnectionExceedTest {
             Assertions.assertEquals(-1, 
scheduler.getConnectPoolMgr().registerConnection(mysql));
             FlightSessionsInConnectPool manager = new 
FlightSessionsInConnectPool(scheduler);
             for (int i = 0; i < 2; i++) {
-                String token = manager.openSession(authResult);
+                String token = manager.openSession(authResult, "127.0.0.1");
                 
Assertions.assertSame(scheduler.getContextWithPeerIdentity(token), 
manager.getConnectContext(token));
             }
             Assertions.assertEquals(2, 
scheduler.getConnectPoolMgr().getFlightConnectionNum());
 
             FlightRuntimeException refused = 
Assertions.assertThrows(FlightRuntimeException.class,
-                    () -> manager.openSession(authResult));
+                    () -> manager.openSession(authResult, "127.0.0.1"));
             Assertions.assertEquals(FlightStatusCode.RESOURCE_EXHAUSTED, 
refused.status().code());
             Assertions.assertEquals(
                     "Reach limit of connections. Total: 1000, User: 100, 
Current: 3, Arrow Flight SQL: 2 (current: 2)",
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/AuthenticatorManagerTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/AuthenticatorManagerTest.java
index 6ece50e9cf9..ee2486a6708 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/AuthenticatorManagerTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/AuthenticatorManagerTest.java
@@ -19,8 +19,13 @@ package org.apache.doris.mysql.authenticate;
 
 import org.apache.doris.analysis.UserIdentity;
 import org.apache.doris.authentication.AuthenticationFailureType;
+import org.apache.doris.authentication.AuthenticationIntegrationMeta;
+import org.apache.doris.authentication.AuthenticationIntegrationMgr;
+import org.apache.doris.authentication.AuthenticationIntegrationRuntime;
 import org.apache.doris.authentication.BasicPrincipal;
 import org.apache.doris.authentication.CredentialType;
+import org.apache.doris.authentication.handler.AuthenticationPluginManager;
+import org.apache.doris.authentication.spi.AuthenticationPlugin;
 import org.apache.doris.catalog.Env;
 import org.apache.doris.common.AuthenticationException;
 import org.apache.doris.common.Config;
@@ -41,6 +46,7 @@ import 
org.apache.doris.mysql.authenticate.password.NativePasswordResolver;
 import org.apache.doris.mysql.authenticate.password.PasswordResolver;
 import 
org.apache.doris.mysql.authenticate.plugin.AuthenticationPluginAuthenticator;
 import org.apache.doris.mysql.privilege.Auth;
+import org.apache.doris.mysql.privilege.User;
 import org.apache.doris.qe.ConnectContext;
 import org.apache.doris.qe.QueryState;
 
@@ -57,6 +63,7 @@ import java.lang.reflect.Field;
 import java.nio.ByteBuffer;
 import java.nio.charset.StandardCharsets;
 import java.util.Collections;
+import java.util.Map;
 import java.util.Optional;
 import java.util.concurrent.atomic.AtomicReference;
 
@@ -93,6 +100,117 @@ class AuthenticatorManagerTest {
         resetAuthenticatorManagerState();
     }
 
+    @Test
+    void testSingleStepOidcRequiresSecureTransportBeforeCallingAuthenticator() 
throws Exception {
+        AuthenticatorManager manager = Mockito.spy(new 
AuthenticatorManager("default"));
+        Authenticator primary = Mockito.mock(Authenticator.class);
+        Mockito.when(primary.acceptsSingleStepRequest()).thenReturn(true);
+        Mockito.doReturn(primary).when(manager).chooseAuthenticator(USER_NAME, 
REMOTE_IP);
+        AuthenticateRequest request = AuthenticateRequest.builder()
+                .userName(USER_NAME)
+                .remoteHost(REMOTE_IP)
+                .clientType("arrow-flight-sql")
+                .credentialType(CredentialType.OIDC_ID_TOKEN)
+                .credential(new byte[] {1})
+                .build();
+
+        AuthenticateResponse result = manager.authenticate(request, false);
+
+        Assertions.assertFalse(result.isSuccess());
+        
Assertions.assertTrue(result.getFailureSummary().getClientVisibleMessage().contains("secure
 transport"));
+        Mockito.verify(primary, Mockito.never()).authenticate(Mockito.any());
+        Mockito.verify(manager, 
Mockito.never()).getAuthenticationChainAuthenticator();
+    }
+
+    @Test
+    void testBoundIamRequiresTlsByIntegrationType() throws Exception {
+        AuthenticationPlugin plugin = installIamIntegration();
+        User binding = Mockito.mock(User.class);
+        Mockito.when(binding.getAuthIntegration()).thenReturn("company_login");
+        Mockito.when(auth.getAuthenticationBinding(USER_NAME, 
REMOTE_IP)).thenReturn(binding);
+
+        AuthenticateResponse result = new 
AuthenticatorManager("default").authenticate(clearCredential(), false);
+
+        Assertions.assertFalse(result.isSuccess());
+        
Assertions.assertTrue(result.getFailureSummary().getClientVisibleMessage().contains("secure
 transport"));
+        Mockito.verify(plugin, Mockito.never()).authenticate(Mockito.any(), 
Mockito.any());
+    }
+
+    @Test
+    void testUnboundIamChainRequiresTlsForPasswordTypedCredential() throws 
Exception {
+        AuthenticationPlugin plugin = installIamIntegration();
+        Config.authentication_chain = "company_login";
+        AuthenticatorManager manager = Mockito.spy(new 
AuthenticatorManager("default"));
+        Authenticator primary = Mockito.mock(Authenticator.class);
+        Mockito.when(primary.acceptsSingleStepRequest()).thenReturn(true);
+        
Mockito.when(primary.authenticate(Mockito.any())).thenReturn(AuthenticateResponse.failedResponse);
+        Mockito.doReturn(primary).when(manager).chooseAuthenticator(USER_NAME, 
REMOTE_IP);
+
+        AuthenticateResponse result = manager.authenticate(clearCredential(), 
false);
+
+        Assertions.assertFalse(result.isSuccess());
+        
Assertions.assertTrue(result.getFailureSummary().getClientVisibleMessage().contains("secure
 transport"));
+        Mockito.verify(plugin).supports(Mockito.argThat(request ->
+                
CredentialType.CLEAR_TEXT_PASSWORD.equals(request.getCredentialType())));
+        Mockito.verify(plugin, Mockito.never()).authenticate(Mockito.any(), 
Mockito.any());
+    }
+
+    @Test
+    void testOrdinaryMysqlPasswordIsNotClassifiedByJwtShape() throws Exception 
{
+        AuthenticatorManager manager = Mockito.spy(new 
AuthenticatorManager("default"));
+        Authenticator primary = Mockito.mock(Authenticator.class);
+        PasswordResolver resolver = Mockito.mock(PasswordResolver.class);
+        Mockito.when(primary.getPasswordResolver()).thenReturn(resolver);
+        Mockito.doReturn(primary).when(manager).chooseAuthenticator(USER_NAME, 
REMOTE_IP);
+        
Mockito.when(resolver.resolveAuthenticateRequest(Mockito.eq(USER_NAME), 
Mockito.any(), Mockito.any(),
+                Mockito.any(), Mockito.any(), 
Mockito.any())).thenReturn(authenticateRequest(
+                        new ClearPassword("eyJsynthetic.password.shape")));
+        Mockito.when(primary.authenticate(Mockito.any())).thenReturn(new 
AuthenticateResponse(true,
+                UserIdentity.createAnalyzedUserIdentWithIp(USER_NAME, 
REMOTE_IP), false));
+        ConnectContext context = mockContext(new QueryState());
+
+        Assertions.assertTrue(manager.authenticate(context, USER_NAME, 
context.getMysqlChannel(),
+                Mockito.mock(MysqlSerializer.class), 
Mockito.mock(MysqlAuthPacket.class),
+                Mockito.mock(MysqlHandshakePacket.class)));
+        Mockito.verify(primary).authenticate(Mockito.any());
+    }
+
+    private AuthenticationPlugin installIamIntegration() throws Exception {
+        AuthenticationIntegrationMeta meta = new 
AuthenticationIntegrationMeta("company_login", "aws_iam",
+                Map.of(), "", USER_NAME, 1, USER_NAME, 1);
+        AuthenticationIntegrationMgr integrations = 
Mockito.mock(AuthenticationIntegrationMgr.class);
+        
Mockito.when(integrations.getAuthenticationIntegration("company_login")).thenReturn(meta);
+        
Mockito.when(env.getAuthenticationIntegrationMgr()).thenReturn(integrations);
+        AuthenticationPluginManager plugins = 
Mockito.mock(AuthenticationPluginManager.class);
+        AuthenticationPlugin plugin = Mockito.mock(AuthenticationPlugin.class);
+        Mockito.when(plugins.hasFactory("aws_iam")).thenReturn(true);
+        Mockito.when(plugins.getPlugin(Mockito.any())).thenReturn(plugin);
+        Mockito.when(plugin.supports(Mockito.any())).thenReturn(true);
+        Mockito.when(env.getAuthenticationIntegrationRuntime()).thenReturn(new 
AuthenticationIntegrationRuntime(plugins));
+        return plugin;
+    }
+
+    private static AuthenticateRequest clearCredential() {
+        return 
AuthenticateRequest.builder().userName(USER_NAME).remoteHost(REMOTE_IP).clientType("arrow-flight-sql")
+                .credentialType(CredentialType.CLEAR_TEXT_PASSWORD)
+                .credential(new byte[] {1}).build();
+    }
+
+    @Test
+    void testSingleStepDoesNotInvokeHandshakeOnlyAuthenticator() throws 
Exception {
+        AuthenticatorManager manager = Mockito.spy(new 
AuthenticatorManager("default"));
+        Authenticator legacy = Mockito.mock(Authenticator.class);
+        Mockito.doReturn(legacy).when(manager).chooseAuthenticator(USER_NAME, 
REMOTE_IP);
+
+        AuthenticateRequest request = authenticateRequest(new 
ClearPassword("secret")).orElseThrow();
+        AuthenticateResponse result = manager.authenticate(request, false);
+
+        Assertions.assertFalse(result.isSuccess());
+        
Assertions.assertTrue(result.getFailureSummary().getClientVisibleMessage().contains("unavailable"));
+        Mockito.verify(legacy, Mockito.never()).authenticate(Mockito.any());
+        Mockito.verify(legacy, Mockito.never()).getPasswordResolver();
+    }
+
     @Test
     void testBoundClearCredentialsRequireRealTlsBeforeResolver() throws 
Exception {
         AuthenticationIntegrationAuthenticator bound = 
Mockito.mock(AuthenticationIntegrationAuthenticator.class);
@@ -567,6 +685,7 @@ class AuthenticatorManagerTest {
 
         QueryState state = new QueryState();
         ConnectContext context = mockContext(state);
+        Mockito.when(context.getMysqlChannel().isSslMode()).thenReturn(true);
         MysqlChannel channel = context.getMysqlChannel();
         
Mockito.when(channel.fetchOnePacket()).thenReturn(clearTextResponse("oidc-token"));
 
@@ -610,7 +729,7 @@ class AuthenticatorManagerTest {
         ConnectContext context = mockContext(state);
         MysqlAuthPacket authPacket = Mockito.mock(MysqlAuthPacket.class);
         
Mockito.when(authPacket.getPluginName()).thenReturn(MysqlHandshakePacket.AUTH_PLUGIN_NAME);
-        
Mockito.when(authPacket.getCapability()).thenReturn(org.apache.doris.mysql.MysqlCapability.DEFAULT_CAPABILITY);
+        
Mockito.when(authPacket.getCapability()).thenReturn(org.apache.doris.mysql.MysqlCapability.SSL_CAPABILITY);
         
Mockito.when(authPacket.getAuthResponse()).thenReturn(OIDC_ID_TOKEN.getBytes(StandardCharsets.UTF_8));
 
         boolean result = manager.authenticate(context, USER_NAME, 
context.getMysqlChannel(),
@@ -748,6 +867,7 @@ class AuthenticatorManagerTest {
 
         QueryState state = new QueryState();
         ConnectContext context = mockContext(state);
+        Mockito.when(context.getMysqlChannel().isSslMode()).thenReturn(true);
         MysqlChannel channel = context.getMysqlChannel();
         Mockito.when(channel.fetchOnePacket())
                 .thenReturn(ByteBuffer.wrap(nativePasswordResponse))
@@ -811,6 +931,7 @@ class AuthenticatorManagerTest {
 
         QueryState state = new QueryState();
         ConnectContext context = mockContext(state);
+        Mockito.when(context.getMysqlChannel().isSslMode()).thenReturn(true);
         MysqlAuthPacket authPacket = Mockito.mock(MysqlAuthPacket.class);
         
Mockito.when(authPacket.getCapability()).thenReturn(org.apache.doris.mysql.MysqlCapability.SSL_CAPABILITY);
 
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/integration/AuthenticationIntegrationAuthenticatorTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/integration/AuthenticationIntegrationAuthenticatorTest.java
index f228182962a..2bad630d120 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/integration/AuthenticationIntegrationAuthenticatorTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/integration/AuthenticationIntegrationAuthenticatorTest.java
@@ -73,7 +73,7 @@ class AuthenticationIntegrationAuthenticatorTest {
     void testAuthenticateExistingUser() throws Exception {
         mgr.replayCreateAuthenticationIntegration(meta("corp_ldap", true));
         mgr.replayCreateAuthenticationIntegration(meta("backup_ldap", true));
-        Mockito.when(runtime.authenticate(Mockito.anyList(), Mockito.any()))
+        Mockito.when(runtime.authenticate(Mockito.anyList(), Mockito.any(), 
Mockito.anyBoolean()))
                 .thenReturn(AuthenticationOutcome.of(integration("corp_ldap", 
true), success()));
         Mockito.when(auth.getUserIdentityForExternalAuth("alice", "127.0.0.1"))
                 .thenReturn(Collections.singletonList(new 
UserIdentity("alice", "127.0.0.1")));
@@ -91,7 +91,7 @@ class AuthenticationIntegrationAuthenticatorTest {
         Assertions.assertEquals(expectedAuthenticatedRoles(), 
response.getAuthenticatedRoles());
 
         ArgumentCaptor<List<AuthenticationIntegrationMeta>> captor = 
ArgumentCaptor.forClass(List.class);
-        Mockito.verify(runtime).authenticate(captor.capture(), Mockito.any());
+        Mockito.verify(runtime).authenticate(captor.capture(), Mockito.any(), 
Mockito.eq(false));
         Assertions.assertEquals(2, captor.getValue().size());
         Assertions.assertEquals("corp_ldap", 
captor.getValue().get(0).getName());
         Assertions.assertEquals("backup_ldap", 
captor.getValue().get(1).getName());
@@ -101,7 +101,7 @@ class AuthenticationIntegrationAuthenticatorTest {
     void testAuthenticateJitUser() throws Exception {
         mgr.replayCreateAuthenticationIntegration(meta("corp_ldap", true));
         mgr.replayCreateAuthenticationIntegration(meta("backup_ldap", true));
-        Mockito.when(runtime.authenticate(Mockito.anyList(), Mockito.any()))
+        Mockito.when(runtime.authenticate(Mockito.anyList(), Mockito.any(), 
Mockito.anyBoolean()))
                 .thenReturn(AuthenticationOutcome.of(integration("corp_ldap", 
true), success()));
         Mockito.when(auth.getUserIdentityForExternalAuth("alice", "127.0.0.1"))
                 .thenReturn(Collections.emptyList());
@@ -123,7 +123,7 @@ class AuthenticationIntegrationAuthenticatorTest {
     void testAuthenticateFailsWhenJitDisabled() throws Exception {
         mgr.replayCreateAuthenticationIntegration(meta("corp_ldap", false));
         mgr.replayCreateAuthenticationIntegration(meta("backup_ldap", true));
-        Mockito.when(runtime.authenticate(Mockito.anyList(), Mockito.any()))
+        Mockito.when(runtime.authenticate(Mockito.anyList(), Mockito.any(), 
Mockito.anyBoolean()))
                 .thenReturn(AuthenticationOutcome.of(integration("corp_ldap", 
false), success()));
         Mockito.when(auth.getUserIdentityForExternalAuth("alice", "127.0.0.1"))
                 .thenReturn(Collections.emptyList());
@@ -136,6 +136,20 @@ class AuthenticationIntegrationAuthenticatorTest {
         Assertions.assertFalse(response.isSuccess());
     }
 
+    @Test
+    void testClearPasswordExchangeDependsOnAvailableIntegrations() throws 
Exception {
+        mgr.replayCreateAuthenticationIntegration(meta("corp_ldap", false));
+        
mgr.replayCreateAuthenticationIntegration(AuthenticationIntegrationMeta.fromCreateSql(
+                "corp_iam", Collections.singletonMap("type", "aws_iam"), null, 
CREATE_USER));
+        AuthenticationIntegrationAuthenticator mixedChain =
+                new 
AuthenticationIntegrationAuthenticator("corp_ldap,corp_iam", 
"authentication_chain");
+        AuthenticationIntegrationAuthenticator bearerOnly =
+                new AuthenticationIntegrationAuthenticator("corp_iam", 
"authentication_chain");
+
+        
Assertions.assertFalse(mixedChain.requiresTlsForClearPasswordExchange());
+        
Assertions.assertTrue(bearerOnly.requiresTlsForClearPasswordExchange());
+    }
+
     @Test
     void testCanDeal() {
         AuthenticationIntegrationAuthenticator authenticator =
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/plugin/AuthenticationPluginAuthenticatorTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/plugin/AuthenticationPluginAuthenticatorTest.java
index dd404d82a85..4d3853b46b7 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/plugin/AuthenticationPluginAuthenticatorTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/plugin/AuthenticationPluginAuthenticatorTest.java
@@ -97,7 +97,7 @@ class AuthenticationPluginAuthenticatorTest {
                 .remoteHost("127.0.0.1")
                 .credentialType("bearer")
                 .credential("token".getBytes(StandardCharsets.UTF_8))
-                .build());
+                .build().withSecureTransport(true));
 
         Assertions.assertTrue(response.isSuccess());
         Assertions.assertTrue(response.isTemp());
@@ -143,7 +143,7 @@ class AuthenticationPluginAuthenticatorTest {
         Assertions.assertEquals(CredentialType.OAUTH_TOKEN, 
request.getCredentialType());
         
Assertions.assertArrayEquals("token-from-client".getBytes(StandardCharsets.UTF_8),
 request.getCredential());
 
-        AuthenticateResponse response = authenticator.authenticate(request);
+        AuthenticateResponse response = 
authenticator.authenticate(request.withSecureTransport(true));
         Assertions.assertTrue(response.isSuccess());
 
         ArgumentCaptor<AuthenticationRequest> requestCaptor = 
ArgumentCaptor.forClass(AuthenticationRequest.class);
@@ -175,13 +175,34 @@ class AuthenticationPluginAuthenticatorTest {
                 .remoteHost("127.0.0.1")
                 .credentialType(CredentialType.OIDC_ID_TOKEN)
                 .credential("token".getBytes(StandardCharsets.UTF_8))
-                .build());
+                .build().withSecureTransport(true));
 
         Assertions.assertTrue(response.isSuccess());
         
Assertions.assertTrue(response.getCredentialExpiresAtMillis().isPresent());
         Assertions.assertEquals(expiresAtMillis, 
response.getCredentialExpiresAtMillis().getAsLong());
     }
 
+    @Test
+    void testPrimaryIamRejectsClearCredentialUnlessTransportIsSecure() throws 
Exception {
+        Mockito.when(pluginManager.hasFactory("aws_iam")).thenReturn(true);
+        Mockito.when(plugin.requiresClearPassword()).thenReturn(true);
+        AuthenticationPluginAuthenticator authenticator = new 
AuthenticationPluginAuthenticator(
+                "aws_iam", Map.of("enable_jit_user", "true"), pluginManager);
+        AuthenticateRequest request = 
AuthenticateRequest.builder().userName(USER_NAME).remoteHost(REMOTE_IP)
+                
.credentialType(CredentialType.CLEAR_TEXT_PASSWORD).credential(new byte[] 
{1}).build();
+
+        Assertions.assertTrue(authenticator.requiresSecureTransport());
+        AuthenticateResponse blocked = authenticator.authenticate(request);
+        Assertions.assertFalse(blocked.isSuccess());
+        
Assertions.assertTrue(blocked.getFailureSummary().getClientVisibleMessage().contains("secure
 transport"));
+        Mockito.verify(plugin, Mockito.never()).authenticate(Mockito.any(), 
Mockito.any());
+
+        Mockito.when(plugin.supports(Mockito.any())).thenReturn(true);
+        Mockito.when(plugin.authenticate(Mockito.any(), 
Mockito.any())).thenReturn(AuthenticationResult.success(
+                
BasicPrincipal.builder().name(USER_NAME).authenticator("aws_iam").build()));
+        
Assertions.assertTrue(authenticator.authenticate(request.withSecureTransport(true)).isSuccess());
+    }
+
     @Test
     void testEnsurePluginFactoryLoadedSupportsMultiplePluginRoots() throws 
Exception {
         org.apache.doris.common.Config.authentication_plugins_dir = 
"/tmp/auth-root-a, /tmp/auth-root-b";


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

Reply via email to