brucearctor opened a new issue, #71417:
URL: https://github.com/apache/doris/issues/71417

   ### Search before asking
   
   - [x] I had searched in the 
[issues](https://github.com/apache/doris/issues?q=is%3Aissue) and found no 
similar issues.
   
   ### Description
   
   - **Status:** Draft (Ready for `[email protected]` `[Discuss][DSIP]` & 
GitHub Tracking Issue)
   - **Target Components:**
     - **Phase 1:** 
`fe/fe-authentication/fe-authentication-plugins/fe-authentication-plugin-jwt` 
(MySQL wire protocol; zero or minimal `fe-core` diff)
     - **Phase 2:** `fe/fe-core` + `be/` + `gensrc/thrift` (FE HTTP/REST, 4-RPC 
Stream Load `Authorization: Bearer`, and Follower→Master `authenticatedRoles` 
forwarding)
     - **Phase 3:** `fe/fe-core` Arrow Flight SQL 
(`FlightBearerTokenAuthenticator`, `FlightAuthResult`, `FlightSessionsManager`)
   
   ---
   
   ## 1. Motivation
   
   Modern cloud-native and enterprise data platforms increasingly rely on 
short-lived OAuth 2.0 / OpenID Connect (OIDC) JSON Web Tokens (JWTs) issued by 
identity providers (Keycloak, Okta, Microsoft Entra ID, AWS Cognito, Kubernetes 
workload identities, GitHub Actions) instead of static database passwords.
   
   Apache Doris already contains almost all of the server-side authentication 
infrastructure (`fe/fe-authentication`) needed to deliver token-based 
authentication:
   
   - **Authentication SPI (`fe/fe-authentication/fe-authentication-spi`):** 
`AuthenticationPlugin` and `AuthenticationPluginFactory`, discovered via Java 
`ServiceLoader`. API surface is locked by `AuthenticationPluginSurfaceTest` and 
stamped via `Doris-Authentication-Plugin-Api-Version: 1.0` in 
`fe/fe-authentication/pom.xml`.
   - **SQL DDL & Cluster Metadata (`fe-core`):** 
`CreateAuthenticationIntegrationCommand`, 
`AlterAuthenticationIntegrationCommand`, `DropAuthenticationIntegrationCommand` 
(all gated on `PrivPredicate.ADMIN` and implementing `NeedAuditEncryption`), 
backed by `AuthenticationIntegrationMgr` and `AuthenticationIntegrationMeta`.
   - **MySQL Wire Protocol & TLS Enforcement (`fe-core`):**
     - `MysqlAuthPacketCredentialExtractor` extracts `eyJ...` JWTs from 
`authentication_openid_connect_client` into `CredentialType.OAUTH_TOKEN`.
     - `ClearPasswordResolver` handles standard MySQL `mysql_clear_password` 
exchanges (`MysqlClearTextPacket`).
     - `AuthenticatorManager.isOidcAuthenticationWithoutSsl` rejects 
`OAUTH_TOKEN`, `OIDC_ID_TOKEN`, `JWT_TOKEN`, and `eyJ...` cleartext passwords 
when TLS is absent (`ERR_SECURE_TRANSPORT_REQUIRED`).
     - `AuthenticatorManager.attachDelegatedCredential` records validated 
tokens and `credentialExpiresAtMillis` into `SessionContext` 
(`DelegatedCredential`) for downstream Iceberg/REST catalog propagation.
   - **Role Mapping (`fe-authentication-role-mapping`):** 
`UnifiedRoleMappingCelEngine` and `IntegrationPropertyRoleMappingEvaluator` 
evaluate `CREATE ROLE MAPPING ... ON AUTHENTICATION INTEGRATION ... RULE (USING 
CEL ... GRANT ROLE ...)` against `BasicPrincipal`.
   - **Managed Libraries (`fe/pom.xml`):** Both `com.nimbusds:nimbus-jose-jwt` 
(`10.0.2`, Apache-2.0) and `org.apache.httpcomponents.client5:httpclient5` 
(`5.6.4`, Apache-2.0) are already declared in `<dependencyManagement>`.
   
   However, `fe/fe-authentication/fe-authentication-plugins/pom.xml` currently 
ships only `fe-authentication-plugin-password` and 
`fe-authentication-plugin-ldap`. Users have no built-in JWT/OIDC validator 
plugin out of the box, and non-MySQL entrypoints (HTTP/REST, Stream Load, Arrow 
Flight SQL) only validate passwords or opaque session tokens.
   
   ### Goals
   
   1. **Zero-core-change Phase 1 plugin:** Ship an in-tree 
`fe-authentication-plugin-jwt` module implementing `AuthenticationPlugin` for 
MySQL protocol clients.
   2. **Online & Offline Key Verification:** Support both OIDC Discovery / 
remote JWKS endpoints (HTTPS) and air-gapped inline static PEM public keys / 
JWKS JSON.
   3. **Full Integration with Doris Auth Semantics:** Support `AS` identity 
bindings, optional `enable_jit_user`, CEL `CREATE ROLE MAPPING`, 
`authentication_chain` fallback, `ACCOUNT_LOCK`, and `DelegatedCredential` 
propagation.
   4. **Phased Multi-Protocol Parity:** Define clean, incremental extensions 
for FE HTTP/REST + Stream Load (`Authorization: Bearer`) and Follower→Master 
`authenticatedRoles` forwarding (Phase 2), and Arrow Flight SQL (Phase 3).
   
   ### Explicit Non-Goals
   
   - **Interactive SASL `OAUTHBEARER` / OAuth Device Flow inside the MySQL wire 
protocol:** Unlike PostgreSQL 18's `libpq` SASL `OAUTHBEARER` flow, the MySQL 
protocol has no standard SASL `OAUTHBEARER` challenge-response, and 
`AuthenticationIntegrationAuthenticator` does not support multi-step `CONTINUE` 
exchanges. Clients acquire JWTs out-of-band and present them at connect time.
   - **OAuth 2.0 opaque token introspection (RFC 7662) in v1:** Initial scope 
focuses on self-contained JWS JWTs; opaque introspection can be added later 
without breaking DDL.
   - **Widening `fe-authentication-spi`:** `AuthenticationPluginSurfaceTest` 
locks the SPI contract; this proposal requires no SPI signature changes.
   - **Dynamic remote code loading:** No URL-loaded validator JARs or scripts 
(`AGENTS.md` remote-artifact policy).
   
   ---
   
   ## 2. Related Research
   
   ### 2.1 Industry Comparison & Design Defaults
   
   | System | Auth Model & Key Source | Identity Mapping & Expiry | Key 
Takeaway for Doris |
   | :--- | :--- | :--- | :--- |
   | **PostgreSQL 18** | Pluggable `oauth_validator_libraries` (`.so`), 
`pg_hba.conf` `oauth issuer=... scope=...` | `pg_ident.conf` / 
`delegate_ident_mapping` (`sub`); validates `exp` at connect time | 
Connect-time `exp` check is standard for stateful SQL connections; SASL 
`OAUTHBEARER` has no MySQL wire equivalent. |
   | **Trino / StarRocks / ClickHouse** | Separate `jwt` authenticator 
(stateless JWS + JWKS/PEM) from `oidc`/`oauth2` (interactive browser flows) | 
Claim-based principal (`sub`, `preferred_username`); `iss`-based HTTP Bearer 
dispatch | Naming this plugin **`"jwt"`** cleanly separates stateless JWS 
verification from interactive `"oidc"` flows while supporting OIDC Discovery 
and `authentication_openid_connect_client`. |
   | **Snowflake** | SQL-managed `SECURITY INTEGRATION` (`EXTERNAL_OAUTH`) 
scoped per issuer | Exact external subject binding per user | Doris's `CREATE 
AUTHENTICATION INTEGRATION` + `AS` binding already provides cluster-wide SQL 
DDL replication superior to per-node config files. |
   
   ### 2.2 Locked-In Defaults
   
   1. **Plugin `type` identifier:** `"jwt"` (stateless JWS validation with OIDC 
Discovery + remote JWKS + offline static PEM/JWKS support; confirm alignment 
with any in-flight `"oidc"` convention during `[email protected]` 
`[Discuss][DSIP]`).
   2. **Phased delivery:** Land Phase 1 (`fe-authentication-plugin-jwt` for 
MySQL) first with zero/minimal `fe-core` diff; follow up with Phase 2 (FE 
HTTP/REST + Stream Load + Follower→Master role forwarding) and Phase 3 (Arrow 
Flight SQL) in separate PRs.
   3. **Default `externalPrincipal`:** Bare `sub` claim (configurable via 
`external_principal_claim`). Already safe against cross-IdP collision because 
`AuthenticatorManager.finishSuccessfulAuthentication` checks **both** 
`binding.getAuthIntegration()` and `binding.getAuthIdentity()`.
   4. **Session expiration:** Validate `exp` at connection establishment 
(matching PG18 and OLAP connection-pool ergonomics); forward 
`credentialExpiresAtMillis` to `SessionContext` `DelegatedCredential` for 
downstream catalog enforcement.
   5. **HTTP `Bearer` routing (Phase 2):** Peek at the unverified JWT's `iss` 
claim *strictly* to select matching `jwt` integration(s), then 
cryptographically verify signature, `iss`, `aud`, and `exp` against that 
integration's key source.
   
   ### 2.3 Ten Concrete Doris Codebase Constraints Found During Audit
   
   1. **Lazy Plugin Initialization vs. DDL Execution:** 
`AuthenticationIntegrationMgr.createAuthenticationIntegration` stores 
`AuthenticationIntegrationMeta` without calling `plugin.validate()` or 
`plugin.initialize()`. Initialization runs lazily on first 
`AuthenticationIntegrationRuntime.authenticate(...)` or `CREATE/ALTER USER ... 
IDENTIFIED WITH ... AS ...`.
   2. **Non-Null `username` on `AuthenticationRequest`:** 
`AuthenticationRequest` enforces `Objects.requireNonNull(builder.username, 
"username is required")` (`AuthenticationRequest.java:65`). MySQL connections 
always supply a username, whereas HTTP `Authorization: Bearer <jwt>` and Flight 
`Bearer` requests often do not. Protocol adapters in Phases 2–3 must pass `""` 
(empty string) rather than `null`, and the plugin must handle 
`username.isEmpty()` cleanly without breaking `fe-authentication-api`.
   3. **In-Tree Plugin Packaging Gap:** Neither `fe-authentication-plugin-ldap` 
nor `fe-authentication-plugin-password` is currently a runtime dependency of 
`fe-core` (`fe-authentication-plugin-password` is `<scope>test</scope>` in 
`fe-authentication-handler/pom.xml`). Packaging `fe-authentication-plugin-jwt` 
as built-in (`fe-core` dependency) vs. external bundle 
(`authentication_plugins_dir`) must be decided explicitly.
   4. **SSRF Checker Placement:** 
`org.apache.doris.cloud.security.SecurityChecker` lives in `fe-core`, which 
`fe-authentication-plugins` cannot depend on (`fe-authentication` sits below 
`fe-core` in the module DAG). Therefore, `fe-authentication-plugin-jwt` must 
implement its own self-contained zero-TOCTOU SSRF guard (`JwksUrlGuard` + 
`PinnedDnsResolver` on `httpclient5`).
   5. **Stream Load 2-Hop Redirect (`LoadAction.java` -> BE -> Thrift -> FE):** 
FE `/api/{db}/{table}/_stream_load` issues a 307 redirect to a BE HTTP server, 
which calls FE back over Thrift.
   6. **`FlightAuthResult` Identity Loss:** `FlightAuthResult` currently stores 
only `(userName, userIdentity, remoteIp)` — omitting `Principal`, granted CEL 
roles, and `DelegatedCredential`. Phase 3 must extend `FlightAuthResult` and 
`FlightSessionsManager.buildConnectContext` so Flight SQL sessions receive CEL 
roles and catalog credentials.
   7. **Follower→Master `authenticatedRoles` Forwarding Gap 
(`FEOpExecutor.java` & `ConnectProcessor.java`):**
      - `FEOpExecutor.buildStmtForwardParams` forwards `currentUserIdent` and 
`DelegatedCredential` (`delegatedCredentialToken`, `Type`, `SessionId`, 
`ExpiresAtMillis`) inside `TMasterOpRequest`, and 
`ConnectProcessor.restoreForwardedSessionContext` restores `SessionContext` — 
**but `ctx.getAuthenticatedRoles()` is NOT forwarded.**
      - **Impact:** Any JWT user (especially JIT or CEL-role-mapped via `CREATE 
ROLE MAPPING`) connected to a **Follower FE** fails privilege checks on 
Master-forwarded DDL/metadata statements because `Auth.getRolesByUserWithLdap` 
reads `ctx.getAuthenticatedRoles()`, which is empty on Master.
      - **Fix:** `FrontendService.thrift` explicitly reserves field IDs `34` 
and `35` on `TMasterOpRequest` for downstream `current_roles`/`is_su_user` 
(`FrontendService.thrift:431-434`), with recent additions at `1004`–`1010`. Add 
`optional list<string> authenticated_roles` and `optional bool is_temp_user` at 
**`1011+`** (per `gensrc/AGENTS.md` optional-field rules), populate in 
`FEOpExecutor.buildStmtForwardParams`, and restore in 
`ConnectProcessor.restoreForwardedSessionContext`. (FE↔FE Thrift is Zone-2 
internal RPC under `threat-model.md`, identical to `currentUserIdent` and 
`delegatedCredentialToken`.)
   8. **Stream Load Uses 4 Separate Thrift Auth RPCs + Cloud Mode 
(`FrontendService.thrift` & `StreamLoadHandler.java`):**
      - `TCertBasedAuth cert_based_auth` already exists as a precedent on **all 
4** Stream Load Thrift request structs in `FrontendService.thrift`:
        - `TLoadTxnBeginRequest` (field `16`)
        - `TStreamLoadPutRequest` (field `60`)
        - `TLoadTxnCommitRequest` (field `21`)
        - `TLoadTxnRollbackRequest` (field `12`)
      - In addition, `StreamLoadHandler.resolveCloudLoadUserIdentity` handles 
Stream Load auth in cloud mode.
      - **Impact:** Phase 2b must add `optional TBearerTokenAuth 
bearer_token_auth` across **all 4** Thrift request structs (next unused 
optional field IDs per `gensrc/AGENTS.md`) plus `FrontendServiceImpl` and 
`StreamLoadHandler` — otherwise `loadTxnBegin` / `loadTxnCommit` / 
`loadTxnRollback` would fail even if `streamLoadPut` succeeded.
   9. **Unbound TLS Check Consistency (`MysqlProto.java` & 
`AuthenticatorManager.java`):** `MysqlProto.java:132-196` already enforces TLS 
via `mysqlSslContext.sslExchange(channel)` and `channel.setSslMode(true)` 
whenever `CLIENT_SSL` is set in packet 1, so a client cannot spoof 
`CLIENT_SSL=1` to bypass TLS. Switching 
`AuthenticatorManager.isOidcAuthenticationWithoutSsl` 
(`AuthenticatorManager.java:429`) from 
`authPacket.getCapability().isClientUseSsl()` to `channel.isSslMode()` is still 
worthwhile for consistency with bound auth (`AuthenticatorManager.java:202`) 
and to avoid falsely rejecting valid TLS clients that omit `CLIENT_SSL` in 
their post-TLS `HandshakeResponse41` packet.
   10. **Follower FE `EditLog` Replay Stale-Cache Bug (`EditLog.java` & 
`AuthenticationIntegrationMgr.java`):** `EditLog.java:1106-1121` invokes 
`AuthenticationIntegrationMgr.replayCreateAuthenticationIntegration`, 
`replayAlterAuthenticationIntegration`, and 
`replayDropAuthenticationIntegration`, none of which notify 
`AuthenticationIntegrationRuntime` (`replayUpsertAuthenticationIntegration` at 
`AuthenticationIntegrationRuntime.java:154` currently has no callers). 
Consequently, rotating an offline `public_key`/`jwks_json` or changing 
`issuer`/`audience`/`jwks_uri` via `ALTER AUTHENTICATION INTEGRATION` updates 
Master FE while Follower FEs continue serving cached keys/config until restart 
(and leak plugin instances on `DROP`). Phase 1 should include the 3-line 
`fe-core` fix invoking `replayUpsertAuthenticationIntegration` / 
`removeAuthenticationIntegration` from `AuthenticationIntegrationMgr`'s replay 
methods.
   
   ---
   
   ## 3. Detailed Design
   
   ### 3.1 Module Layout, Packaging & Classloading Isolation
   
   ```text
   fe/fe-authentication/fe-authentication-plugins/
   ├── pom.xml                                  # Add 
<module>fe-authentication-plugin-jwt</module>
   ├── fe-authentication-plugin-ldap/
   ├── fe-authentication-plugin-password/
   └── fe-authentication-plugin-jwt/
       ├── pom.xml
       ├── README.md
       └── src/
           ├── main/
           │   ├── java/org/apache/doris/authentication/plugin/jwt/
           │   │   ├── JwtAuthenticationPluginFactory.java
           │   │   ├── JwtAuthenticationPlugin.java
           │   │   ├── JwtIntegrationConfig.java
           │   │   ├── JwtKeyProvider.java
           │   │   ├── StaticJwtKeyProvider.java
           │   │   ├── RemoteJwksKeyProvider.java
           │   │   ├── JwksUrlGuard.java
           │   │   ├── PinnedDnsResolver.java
           │   │   ├── JwtTokenValidator.java
           │   │   └── JwtClaimMapper.java
           │   └── resources/META-INF/services/
           │       └── 
org.apache.doris.authentication.spi.AuthenticationPluginFactory
           └── test/
               └── java/org/apache/doris/authentication/plugin/jwt/
                   └── ...
   ```
   
   - **Dependencies (`pom.xml`):**
     - `org.apache.doris:fe-authentication-api` (`<scope>provided</scope>`)
     - `org.apache.doris:fe-authentication-spi` (`<scope>provided</scope>`)
     - `com.nimbusds:nimbus-jose-jwt` (inherits `10.0.2` from `fe/pom.xml`, 
Apache-2.0)
     - `org.apache.httpcomponents.client5:httpclient5` (inherits `5.6.4` from 
`fe/pom.xml`, Apache-2.0)
     - `org.apache.logging.log4j:log4j-api` (`provided` / managed)
     - `com.google.guava:guava`
     - **Tests:** JUnit 5 + Nimbus JOSE key/JWT builders + JDK built-in 
`com.sun.net.httpserver.HttpServer` (zero new test-server dependencies).
   - **Manifest API Version:** Inherits `maven-jar-plugin` 
`<Doris-Authentication-Plugin-Api-Version>${authentication.plugin.api.version}</Doris-Authentication-Plugin-Api-Version>`
 (`1.0`) from `fe/fe-authentication/pom.xml`, satisfying 
`AuthenticationPluginManager.API_VERSION_GATE`.
   - **Distribution Mode:**
     - **Built-in (recommended for upstream):** Add 
`fe-authentication-plugin-jwt` as a runtime dependency of `fe-core` so 
`ServiceLoader.load(AuthenticationPluginFactory.class)` registers `"jwt"` out 
of the box with zero deployment steps.
     - **External Plugin Directory (`Config.authentication_plugins_dir`):** 
Placing `fe-authentication-plugin-jwt.jar` + `lib/` (`nimbus-jose-jwt-*.jar`, 
`httpclient5-*.jar`, `httpcore5-*.jar`) in `<authentication_plugins_dir>/jwt/` 
also works via `DirectoryPluginRuntimeManager` (`AUTH_PARENT_FIRST_PREFIXES = 
["org.apache.doris.authentication."]`).
   
   ### 3.2 MySQL Wire Protocol Mechanics & Pre-Decode Sizing Bounds
   
   Verified wire behavior in `fe/fe-core/src/main/java/org/apache/doris/mysql/`:
   
   1. **Length-Encoded vs. 1-Byte Auth Payload (`MysqlAuthPacket.java`, 
`MysqlCapability.java`):**
      - `MysqlCapability.DEFAULT_FLAGS` advertises 
`CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA` (`0x00200000`).
      - Drivers supporting this flag (Connector/J 8/9, MySQL 8/9 C client) 
using `authentication_openid_connect_client` send `authResponse` via 
`readLenEncodedString` — **supporting JWTs larger than 255 bytes without 
truncation**.
      - Older clients lacking `CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA` hit the 
1-byte `readInt1` 255-byte limit on initial handshake auth data; those clients 
must use the `mysql_clear_password` `AuthSwitchRequest` path 
(`MysqlClearTextPacket`, NUL-terminated UTF-8 string), which has no 255-byte 
cap.
   2. **Pre-Decode Token Size Cap (`MysqlChannel.MAX_PHYSICAL_PACKET_LENGTH`):**
      - `MysqlChannel` accepts physical packets up to `0xffffff` (16 MiB). 
Without an early size cap, an unauthenticated client could force multi-megabyte 
Base64URL/JSON allocations before signature verification.
      - `JwtIntegrationConfig` enforces **`max_token_bytes`** (default `16384` 
/ 16 KiB, configurable `[1024, 65536]`) **before** Base64URL decoding or Nimbus 
parsing.
   
   ### 3.3 Internal Class Architecture & Configuration Reference
   
   ```mermaid
   flowchart LR
       MySQL["MySQL / JDBC / OIDC Client"] -->|"TLS + JWT"| 
AM["AuthenticatorManager"]
       AM -->|"AuthenticationRequest"| AIR["AuthenticationIntegrationRuntime"]
       AIR -->|"ServiceLoader / PluginHandle"| Plugin["JwtAuthenticationPlugin"]
       Plugin --> Config["JwtIntegrationConfig"]
       Plugin --> Validator["JwtTokenValidator"]
       Validator --> KeyProv["JwtKeyProvider (Static / RemoteJwks)"]
       KeyProv --> Guard["JwksUrlGuard + PinnedDnsResolver (httpclient5)"]
       Validator --> Mapper["JwtClaimMapper"]
       Mapper -->|"BasicPrincipal + exp"| AIR
       AIR -->|"CEL Evaluation"| CEL["UnifiedRoleMappingCelEngine"]
       AIR -->|"AuthenticationOutcome"| AM
       AM -->|"AS Check + ACCOUNT_LOCK + DelegatedCredential"| 
Ctx["ConnectContext"]
   ```
   
   ```mermaid
   sequenceDiagram
       autonumber
       participant C as "MySQL Client (TLS)"
       participant AM as "AuthenticatorManager"
       participant AIR as "AuthenticationIntegrationRuntime"
       participant P as "JwtAuthenticationPlugin"
       participant KP as "RemoteJwksKeyProvider"
       participant IdP as "HTTPS OIDC / JWKS Endpoint"
   
       C->>AM: "Handshake / ClearPassword or OIDC Auth Packet"
       AM->>AM: "Verify TLS (channel.isSslMode / TLS check)"
       AM->>AIR: "authenticate(chain, AuthenticationRequest)"
       AIR->>P: "supports(request)"
       P-->>AIR: "true (JWT shape / token CredentialType)"
       AIR->>P: "authenticate(request, integration)"
       P->>KP: "resolveJwkSet(kid)"
       alt "Cache empty, TTL expired, or unknown kid with cooldown elapsed"
           KP->>KP: "Acquire single-flight refresh lock + resolve/pin DNS"
           KP->>IdP: "GET jwks_uri (HTTPS, no redirects, 3s timeout, <=1MiB)"
           IdP-->>KP: "200 OK (JWKS JSON)"
           KP-->>P: "Updated JWKSet"
       else "Unknown kid within cooldown"
           KP-->>P: "Cached JWKSet (rate-limited)"
       end
       P->>P: "10-step crypto + claim verification"
       P-->>AIR: "AuthenticationResult.success(BasicPrincipal, expMillis)"
       AIR->>AIR: "Evaluate CEL CREATE ROLE MAPPING"
       AIR-->>AM: "AuthenticationOutcome(principal, grantedRoles)"
       AM->>AM: "Verify AS binding, ACCOUNT_LOCK, attach DelegatedCredential"
       AM-->>C: "OK Packet"
   ```
   
   #### `JwtAuthenticationPluginFactory` & `JwtAuthenticationPlugin`
   - **`JwtAuthenticationPluginFactory`:** `name()` returns `"jwt"`; `create()` 
returns `new JwtAuthenticationPlugin()`.
   - **`supports(AuthenticationRequest request)`:**
     - Returns `true` for `CredentialType.JWT_TOKEN`, 
`CredentialType.OAUTH_TOKEN`, and `CredentialType.OIDC_ID_TOKEN`.
     - For `CredentialType.CLEAR_TEXT_PASSWORD`: returns `true` **only** when 
`request.getCredential()` is non-null, `<= max_token_bytes` (or global sanity 
bound), and matches compact JWS shape (`eyJ` prefix, exactly two `.` 
separators, all 3 Base64URL segments non-empty). Ordinary passwords return 
`false` so `authentication_chain` passes them to LDAP/Password integrations.
   - **`requiresClearPassword()`:** Returns `true`. Generic MySQL clients use 
`ClearPasswordResolver` (`mysql_clear_password` over TLS), while 
`authentication_openid_connect_client` short-circuits in 
`AuthPacketAwarePasswordResolver`.
   - **`normalizeBoundIdentity(String rawIdentity)`:** Returns `null` if 
`rawIdentity == null`; trims whitespace and throws 
`AuthenticationException(..., MISCONFIGURED)` if blank, matching login-time 
`JwtClaimMapper` normalization on `external_principal_claim`.
   - **`validate(integration)` / `initialize(integration)` / `close()`:** 
Parses `JwtIntegrationConfig` and static keys synchronously (`MISCONFIGURED` on 
invalid config/keys); defers remote OIDC/JWKS HTTP calls to `authenticate()`. 
`close()` releases resources cleanly.
   
   #### `JwtIntegrationConfig` (Properties & Bounds)
   
   | Property | Type / Values | Default | Notes / Validation |
   | :--- | :--- | :--- | :--- |
   | `issuer` | String | *(Required)* | Non-blank; exact match against `iss` 
claim. |
   | `audience` | Comma-separated Strings | *(Required)* | At least one 
non-blank value; token `aud` must intersect. |
   | `oidc_discovery_url` | HTTPS URL | — | Resolves `jwks_uri` from 
`.well-known/openid-configuration`. |
   | `jwks_uri` | HTTPS URL | — | Explicit JWKS endpoint (takes precedence over 
discovery `jwks_uri`). |
   | `public_key` | PEM String | — | Offline RSA / EC / EdDSA X.509 
SubjectPublicKeyInfo PEM. |
   | `jwks_json` | JSON String | — | Offline JWK Set JSON (replicated across 
all FEs via EditLog). |
   | `allowed_algorithms` | Comma-separated JWS algs | 
`RS256,RS384,RS512,ES256,ES384,ES512,EdDSA` | `none` unconditionally forbidden; 
`HS*` disallowed with asymmetric keys. |
   | `max_token_bytes` | Integer `[1024, 65536]` | `16384` | Rejects oversized 
tokens before Base64URL/JSON decoding. |
   | `clock_skew_seconds` | Integer `[0, 300]` | `60` | Applied to `exp` and 
`nbf`. |
   | `max_token_lifetime_seconds` | Integer `[0, 31536000]` | `0` (disabled) | 
Optional upper bound on `exp - iat` when `> 0`. |
   | `required_scopes` | Comma/space-separated | — | Every listed scope must 
appear in `scope`/`scp`. |
   | `required_typ` | String | — | Case-insensitive check on JWS `typ` header 
when set (e.g., `at+jwt`). |
   | `username_claim` | Dot-path String | `sub` | Populates 
`BasicPrincipal.name`. |
   | `external_principal_claim` | Dot-path String | `sub` | Populates 
`BasicPrincipal.externalPrincipal` for `AS` bindings. |
   | `groups_claim` | Dot-path String | `groups` | Populates 
`BasicPrincipal.externalGroups`. |
   | `roles_claim` | Dot-path String | `roles` | Populates 
`multiValueAttributes["roles"]` for CEL `has_role(...)`. |
   | `scope_claim` | Dot-path String | `scope` | Reads `scope` (and `scp` 
fallback) into `multiValueAttributes["scope"]`. |
   | `service_principal_claim` | `claim` or `claim=val` | — | Sets 
`BasicPrincipal.servicePrincipal` (`true` if claim exists / matches). |
   | `extra_attribute_claims` | Comma-separated dot-paths | — | Scalar claims 
copied into `BasicPrincipal.attributes` (arrays into `multiValueAttributes`). |
   | `require_username_match` | Boolean | `true` | Safe default preventing 
unbound impersonation. Skipped when `request.getUsername()` is empty 
(HTTP/Flight) or when `fe-core` sets `"doris.auth.bound_identity_enforced" = 
true` on `AS`-bound logins. |
   | `jwks_cache_ttl_seconds` | Integer `[30, 86400]` | `3600` | Freshness TTL 
for cached JWKS. |
   | `jwks_refresh_cooldown_seconds` | Integer `[5, 3600]` | `60` | Minimum 
interval between forced refreshes on unknown `kid`. |
   | `http_connect_timeout_ms` | Integer `[200, 30000]` | `3000` | Outbound 
HTTP connect timeout. |
   | `http_read_timeout_ms` | Integer `[200, 30000]` | `3000` | Outbound HTTP 
read timeout. |
   | `jwks_max_response_bytes` | Integer `[1024, 10485760]` | `1048576` | Max 
bytes read from discovery/JWKS response (1 MiB default). |
   | `allowed_jwks_hosts` | Comma-separated hostnames | — | Optional host 
allowlist enforced by `JwksUrlGuard`. |
   | `allow_private_network_jwks` | Boolean | `false` | When `false`, 
`JwksUrlGuard` blocks loopback, link-local (`169.254.0.0/16`), and private 
RFC1918/ULA CIDRs. |
   | `allow_http_jwks_insecure` | Boolean | `false` | Allows `http://` only 
when explicitly enabled for local/dev testing. |
   | `enable_jit_user` | Boolean | `false` | Handled by `fe-core` 
(`AuthenticationIntegrationAuthenticator`). |
   
   **Key-Source Mutual Exclusion & Multi-FE Replication:** Exactly one mode 
must be configured: **Remote** (`oidc_discovery_url` and/or `jwks_uri`) OR 
**Static** (`public_key` or `jwks_json` — at most one static source). Local 
filesystem key paths (`jwks_file`) are intentionally omitted from v1 so the 
plugin remains independent of `fe-common`/`Config`, all key config replicates 
automatically across HA FEs via `EditLog`, and path-traversal risk is zero.
   
   **`require_username_match` vs. `AS`-Bound Users:** Leaving 
`require_username_match = true` as the default prevents an attacker with a 
valid JWT (`preferred_username = bob`) from logging into an unbound local Doris 
account (`mysql -u alice`). For `AS`-bound users (`CREATE USER 'alice' 
IDENTIFIED WITH AUTHENTICATION INTEGRATION ... AS '<oid-or-sub>'`), 
`AuthenticationIntegrationAuthenticator.toIntegrationRequest` sets 
`"doris.auth.bound_identity_enforced" = true` in 
`AuthenticationRequest.properties` (zero SPI change) whenever `binding != null 
&& binding.getAuthIdentity() != null`, allowing the plugin to skip 
`username_claim == request.getUsername()` *only* when `fe-core` guarantees 
exact `AS` `externalPrincipal` matching. In a strict zero-`fe-core`-change 
deployment, `AS`-bound integrations where MySQL username differs from 
`username_claim` must explicitly set `"require_username_match" = "false"` and 
keep `"enable_jit_user" = "false"`.
   
   ### 3.4 Zero-TOCTOU DNS-Pinned HTTPS Fetcher, Cache State Machine & 
Verification Pipeline
   
   #### Zero-TOCTOU DNS-Pinned Fetcher (`JwksUrlGuard` + `PinnedDnsResolver` 
via `httpclient5`)
   Validating DNS before calling an HTTP client is vulnerable to **DNS 
rebinding (TOCTOU)**. Moreover, JDK's `HttpsURLConnection` treats `"Host"` as a 
restricted header and silently ignores `setRequestProperty("Host", ...)` unless 
`-Dsun.net.http.allowRestrictedHeaders=true` is set—breaking virtual-hosted 
IdPs if an IP-literal URL is used. `RemoteJwksKeyProvider` avoids both pitfalls 
using Apache HttpClient 5 (`org.apache.httpcomponents.client5:httpclient5` 
`5.6.4`, already managed in `fe/pom.xml`):
   
   1. **URI Validation:** Require `https` (unless `allow_http_jwks_insecure = 
true`), reject `userinfo` (`https://user@host`), validate port, and check 
`allowed_jwks_hosts` if configured.
   2. **Single-Resolution `PinnedDnsResolver` 
(`org.apache.hc.client5.http.DnsResolver`):** 
`PoolingHttpClientConnectionManagerBuilder.create().setDnsResolver(pinnedDnsResolver)`
 delegates DNS resolution directly to `JwksUrlGuard`. Inside `resolve(host)`, 
call `InetAddress.getAllByName(host)` once, unwrap any IPv4-mapped IPv6 
addresses (`::ffff:0:0/96`) to IPv4, and reject loopback (`127.0.0.0/8`, 
`::1`), unspecified (`0.0.0.0/8`, `::`), multicast, link-local / cloud IMDS 
(`169.254.0.0/16`, `fe80::/10`), RFC1918 (`10.0.0.0/8`, `172.16.0.0/12`, 
`192.168.0.0/16`), CGNAT (`100.64.0.0/10`), and IPv6 ULA (`fc00::/7`) unless 
`allow_private_network_jwks = true`.
   3. **Pinned Connection + Real `Host` / SNI / TLS Verification:** 
`httpclient5` opens the socket directly to the returned `InetAddress[]` while 
preserving the original hostname for the HTTP `Host` header, TLS SNI, and 
standard X.509 hostname verification.
   4. **Hardening Flags:** Build `CloseableHttpClient` with 
`.disableRedirectHandling()`, explicit connect and response timeouts 
(`http_connect_timeout_ms`, `http_read_timeout_ms`), and a `BoundedInputStream` 
capped at `jwks_max_response_bytes` (1 MiB default).
   
   #### `RemoteJwksKeyProvider` Cache & Single-Flight State Machine
   
   ```mermaid
   stateDiagram-v2
       [*] --> Empty
       Empty --> Refreshing: "authenticate() acquires single-flight lock"
       Refreshing --> Fresh: "200 OK + valid JWKSet (record fetchedAt + 
lastAttempt)"
       Refreshing --> Failed: "IO/HTTP/parse error (record lastAttempt, throw 
SOURCE_UNAVAILABLE)"
       Failed --> Refreshing: "Next request after cooldown elapsed"
       Fresh --> Fresh: "Cache hit (age < TTL and kid found)"
       Fresh --> Refreshing: "TTL expired OR (unknown kid AND now - lastAttempt 
>= cooldown)"
       Fresh --> Fresh: "Unknown kid within cooldown -> return cached set 
(BAD_CREDENTIAL)"
   ```
   
   - Hot-path reads use a lock-free `AtomicReference<CachedJwkSet>` 
(`volatile`).
   - `lastRefreshAttemptMillis` is updated on **both success and failure**, 
preventing thundering herds during IdP outages or `kid`-flood DoS attacks.
   - Expired JWKS past `jwks_cache_ttl_seconds` are **not** served silently if 
refresh fails; throwing `SOURCE_UNAVAILABLE` ensures revoked keys do not linger 
indefinitely and lets `authentication_chain` fall back.
   
   #### 10-Step Cryptographic & Claim Verification Pipeline 
(`JwtTokenValidator`)
   
   1. **Size & Shape Guard:** Reject `credential.length > max_token_bytes`, 
non-UTF-8/control chars, JWE (5-segment), or malformed JWS (!= 3 dot-separated 
Base64URL segments, or empty signature).
   2. **Header Inspection:** Parse `JWSHeader`; unconditionally reject 
`alg=none`, reject `alg` not in `allowed_algorithms`, reject non-empty `crit` 
headers (RFC 7515 §4.1.11), **ignore/reject embedded key headers (`jku`, `x5u`, 
`jwk`, `x5c`)**, and verify `typ` if `required_typ` is set.
   3. **Key Selection:** Fetch candidate `JWK`s filtered by `kid` (if present), 
`use` (`sig` or unset; reject `enc`), `key_ops` (`verify` if set), compatible 
`kty`/curve, and forbid `HS*` against asymmetric keys (max 16 keys tried if 
`kid` omitted).
   4. **Signature Verification:** Verify via Nimbus (`RSASSAVerifier` / 
`ECDSAVerifier` / `Ed25519Verifier`). On missing `kid`, trigger at most one 
cooldown-gated JWKS refresh and retry once.
   5. **Claims Parse:** Extract `JWTClaimsSet` only after signature 
verification succeeds.
   6. **Issuer (`iss`):** Exact string equality against `config.issuer`.
   7. **Audience (`aud`):** Non-empty intersection with `config.audience`.
   8. **Temporal Bounds (`exp`, `nbf`, `iat`):** Require `exp` (`now - 
clockSkew < exp`); if `nbf` present require `now + clockSkew >= nbf`; if 
`max_token_lifetime_seconds > 0` require `iat` present and `(exp - iat) <= 
maxLifetime`.
   9. **Scopes:** Verify every entry in `required_scopes` exists in parsed 
`scope` (space-delimited) or `scp` (array/string).
   10. **Claim Extraction & Sanitization (`JwtClaimMapper`):** Resolve dot-path 
claims safely, reject NUL/control chars or length > 256 on 
`name`/`externalPrincipal`, enforce `require_username_match` when 
`request.getUsername()` is non-empty, and build `BasicPrincipal` + 
`AuthenticationResult.success(principal, expEpochMillis)`.
   
   ### 3.5 Lifecycle, Failure Classification & CEL Role-Mapping Contract
   
   | Lifecycle Phase | Actions Allowed | Error Handling |
   | :--- | :--- | :--- |
   | `validate()` / `initialize()` | Config bounds, `JwksUrlGuard` syntax, 
static PEM/JWKS parse. **Zero network I/O.** | Throw 
`AuthenticationException(..., MISCONFIGURED)` |
   | `authenticate()` — token/crypto/claim error | Bad signature, unknown 
`kid`, expired `exp`, wrong `iss`/`aud`, `alg=none`, missing scope, username 
mismatch | Return `AuthenticationResult.failure(new 
AuthenticationException(..., BAD_CREDENTIAL))` |
   | `authenticate()` — IdP / JWKS I/O error | DNS/TCP/TLS failure, HTTP != 
200, oversized/bad JWKS JSON, timeout | Throw `AuthenticationException(..., 
SOURCE_UNAVAILABLE)` (`shouldContinueInChain() == true`) |
   | `ALTER / DROP AUTHENTICATION INTEGRATION` | Master updates runtime 
directly; Follower `EditLog` replay invokes 
`replayUpsertAuthenticationIntegration` / `removeAuthenticationIntegration` -> 
next auth calls `reloadPlugin` -> `old.close()` -> new `validate()` + 
`initialize()` | Clean cache eviction across all FEs, zero stale keys or leaked 
connections |
   
   | `BasicPrincipal` Field | Source JWT Claim(s) | Available CEL Functions 
(`UnifiedRoleMappingCelEngine`) |
   | :--- | :--- | :--- |
   | `name` | `username_claim` (default `sub`) | `name()` |
   | `externalPrincipal` | `external_principal_claim` (default `sub`) | 
`external_principal()` |
   | `servicePrincipal` | `service_principal_claim` rule | 
`is_service_principal()` |
   | `externalGroups` | `groups_claim` (array or delimited string) | 
`has_group(g)`, `has_any_group(...)` |
   | `multiValueAttributes["roles"]` | `roles_claim` (array or delimited 
string) | `has_role(r)`, `has_any_role(...)` |
   | `multiValueAttributes["scope"]` | `scope_claim` (`scope` string or `scp` 
array) | `has_scope(s)`, `has_any_scope(...)` |
   | `attributes` / `multiValueAttributes[k]` | `extra_attribute_claims` | 
`attr(k)`, `has_attr_value(k, v)`, `has_any_attr_value(k, ...)` |
   
   #### Verified SQL Recipes
   
   ```sql
   -- Recipe A: Keycloak (nested realm_access.roles + groups + department 
attribute)
   CREATE AUTHENTICATION INTEGRATION keycloak_prod
   PROPERTIES (
       "type" = "jwt",
       "issuer" = "https://sso.corp.internal/realms/analytics";,
       "oidc_discovery_url" = 
"https://sso.corp.internal/realms/analytics/.well-known/openid-configuration";,
       "audience" = "doris-sql",
       "username_claim" = "preferred_username",
       "external_principal_claim" = "sub",
       "groups_claim" = "groups",
       "roles_claim" = "realm_access.roles",
       "extra_attribute_claims" = "department"
   );
   
   CREATE ROLE MAPPING keycloak_roles ON AUTHENTICATION INTEGRATION 
keycloak_prod
   RULE (USING CEL 'has_role("doris-admin") && has_group("/data-platform")' 
GRANT ROLE admin_ro),
   RULE (USING CEL 'has_scope("doris:query") && attr("department") == 
"finance"' GRANT ROLE finance_reader);
   
   -- Recipe B: Microsoft Entra ID / Okta with AS binding
   -- (In Entra ID, preferred_username is typically UPN/email while Doris 
username is 'alice';
   --  "doris.auth.bound_identity_enforced" = true allows AS-bound login 
without username equality,
   --  or set "require_username_match" = "false" + "enable_jit_user" = "false" 
in zero-core-change mode.)
   CREATE AUTHENTICATION INTEGRATION entra_prod
   PROPERTIES (
       "type" = "jwt",
       "issuer" = "https://login.microsoftonline.com/<tenant-id>/v2.0",
       "jwks_uri" = 
"https://login.microsoftonline.com/<tenant-id>/discovery/v2.0/keys",
       "audience" = "api://doris-prod",
       "username_claim" = "preferred_username",
       "external_principal_claim" = "oid",
       "groups_claim" = "groups",
       "roles_claim" = "roles",
       "enable_jit_user" = "false"
   );
   
   CREATE USER 'alice'@'%'
   IDENTIFIED WITH AUTHENTICATION INTEGRATION entra_prod
   AS '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d';
   
   -- Recipe C: Offline GitHub Actions / K8s Workload Identity (zero outbound 
HTTP)
   CREATE AUTHENTICATION INTEGRATION ci_offline
   PROPERTIES (
       "type" = "jwt",
       "issuer" = "https://ci.corp.internal";,
       "audience" = "doris-etl",
       "public_key" = "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC 
KEY-----",
       "service_principal_claim" = "job_workflow_ref",
       "extra_attribute_claims" = "repository,ref"
   );
   ```
   
   ### 3.6 Phase 2: FE HTTP / REST, 4-RPC Stream Load & Follower→Master 
Forwarding
   
   1. **FE HTTP / REST (`BaseController`, `RestBaseController`, 
`AuthInterceptor`):**
      - `BaseController.parseAuthInfo` detects `Authorization: Bearer <token>` 
(case-insensitive) while preserving `Basic` unchanged; never logs header values.
      - Enforces HTTPS (`request.isSecure()` or `Config.enable_https`).
      - Passes `username = ""` and `clientType = "http"`, peeks at unverified 
`iss` strictly to select matching `jwt` integration(s) (constrained by optional 
`Config.http_bearer_authentication_chain`), and validates via 
`AuthenticationIntegrationRuntime.authenticate(...)`.
      - Adds a reverse lookup in `Auth` for `(integrationName, 
externalPrincipal) -> User` for `AS`-bound accounts (falling back to 
`getUserIdentityForExternalAuth` and `enable_jit_user`), enforces 
`ACCOUNT_LOCK`, applies `authenticatedRoles` and `DelegatedCredential` to 
`ConnectContext`, and never writes JWTs into `PALO_SESSION_ID` cookies.
   2. **Stream Load 2-Hop & 4-RPC Thrift Flow (`LoadAction`, 
`StreamLoadHandler`, `FrontendService.thrift`):**
      - Mirrors `TCertBasedAuth cert_based_auth` by adding `struct 
TBearerTokenAuth { 1: optional string bearer_token; 2: optional bool 
transport_tls; }` and `optional TBearerTokenAuth bearer_token_auth` to **all 
4** Stream Load Thrift request structs (`TLoadTxnBeginRequest`, 
`TStreamLoadPutRequest`, `TLoadTxnCommitRequest`, `TLoadTxnRollbackRequest`) 
per `gensrc/AGENTS.md`.
      - BE extracts `Authorization: Bearer <token>` and populates 
`bearer_token_auth` on all 4 RPCs; FE (`FrontendServiceImpl` + 
`StreamLoadHandler.resolveCloudLoadUserIdentity`) validates via 
`AuthenticationIntegrationRuntime`.
   
   ```mermaid
   sequenceDiagram
       autonumber
       participant Client as "HTTP Client (curl / Flink / Spark)"
       participant FE as "FE LoadAction (HTTP)"
       participant BE as "BE HTTP Server"
       participant Thrift as "FE FrontendServiceImpl (Thrift)"
   
       Client->>FE: "PUT /api/db/tbl/_stream_load (HTTPS + Authorization: 
Bearer <jwt>)"
       FE->>FE: "Validate Bearer via AuthenticationIntegrationRuntime"
       FE-->>Client: "307 Temporary Redirect -> BE"
       Client->>BE: "PUT /api/db/tbl/_stream_load (Authorization: Bearer <jwt>)"
       BE->>Thrift: "loadTxnBegin / streamLoadPut / loadTxnCommit / 
loadTxnRollback (with bearer_token_auth)"
       Thrift->>Thrift: "Validate bearer_token_auth via 
AuthenticationIntegrationRuntime + StreamLoadHandler"
       Thrift-->>BE: "Result (UserIdentity + fragment plan)"
       BE-->>Client: "200 OK / Stream Load Result"
   ```
   
   3. **Follower→Master `authenticatedRoles` Forwarding (`TMasterOpRequest`):**
      - Add `optional list<string> authenticated_roles` and `optional bool 
is_temp_user` at **`1011+`** on `TMasterOpRequest` (leaving reserved fields 
`34`/`35` untouched per `FrontendService.thrift:431-434`), populate in 
`FEOpExecutor.buildStmtForwardParams`, and restore in 
`ConnectProcessor.restoreForwardedSessionContext` alongside 
`DelegatedCredential`.
   
   ### 3.7 Phase 3: Arrow Flight SQL
   
   1. **Unambiguous Token Multiplexing (`FlightBearerTokenAuthenticator`):** 
Doris Flight session tokens (`FlightSessionsInConnectPool.newToken()`) are 
130-bit Base32 `[0-9a-v]+` (zero dots). Compact JWS JWTs have 3 dot-separated 
segments (`eyJ...`). When a JWT Bearer token arrives over gRPC TLS with no 
matching active session, validate via `AuthenticationIntegrationRuntime`, open 
a Flight session, and return the opaque Doris Flight session token in outgoing 
headers.
   2. **Preserve Full Identity (`FlightAuthResult` & 
`FlightSessionsManager`):** Carry optional `Principal`, `Set<String> 
authenticatedRoles`, and `DelegatedCredential` on `FlightAuthResult` and apply 
to `ConnectContext`.
   3. **Log Hygiene:** Log only `TokenMasker.tokenId(token)` in `fe-core` 
Flight session code — never raw JWTs.
   
   ### 3.8 Security, Observability & Client Interoperability
   
   - **Threat Model (`AGENTS.md` & `threat-model.md` Family Row 4):** 
Admin-only DDL (`PrivPredicate.ADMIN`, `NeedAuditEncryption`); `JwksUrlGuard` + 
`PinnedDnsResolver` (`httpclient5`) eliminates DNS-rebinding SSRF (`https://`, 
real `Host`/SNI verification, redirects disabled, 3s timeouts, 1 MiB cap, 
blocks loopback/IMDS/RFC1918); offline static key mode needs zero network 
egress; `alg=none`, `crit`, embedded JWK/JKU/X5U/X5C, and `HS*` key confusion 
rejected; `max_token_bytes` (16 KiB) + `jwks_refresh_cooldown_seconds` (60s) 
prevent DoS; `root`/`admin` excluded and `ACCOUNT_LOCK` enforced post-auth. 
Tighten `AuthenticatorManager.isOidcAuthenticationWithoutSsl` 
(`AuthenticatorManager.java:429`) to check `channel.isSslMode()` (matching 
bound auth and avoiding false rejections of TLS clients that omit `CLIENT_SSL` 
in post-TLS `HandshakeResponse41`).
   - **Observability & Log Boundary:** `MetricRepo` and `TokenMasker` live in 
`fe-core` (not `fe-authentication-api`/`spi`). Generic Prometheus auth 
integration metrics 
(`doris_fe_auth_integration_attempts_total{integration,type,result}`, latency 
histogram) belong in `fe-core`'s `AuthenticationIntegrationRuntime`, while 
`fe-authentication-plugin-jwt` logs only `integrationName`, `kid`, and failure 
category (never token values).
   
   | Client / Driver | Wire Auth Path | Max Token Size | Pool / Refresh 
Guidance |
   | :--- | :--- | :--- | :--- |
   | **`mysql` CLI (8/9)** | `--ssl-mode=REQUIRED --enable-cleartext-plugin -u 
alice -p$JWT` | Packet limit (capped at 16 KiB) | Re-fetch token per session |
   | **MySQL `authentication_openid_connect_client`** | Initial 
`MysqlAuthPacket` (`OAUTH_TOKEN`) | >255B via 
`CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA` | Driver OIDC token callback |
   | **JDBC / Python / Go drivers** | TLS + `mysql_clear_password` | >255B 
supported | Pool `maxLifetime < token TTL` |
   | **HTTP / Stream Load** *(Phase 2)* | HTTPS + `Authorization: Bearer $JWT` 
| HTTP header limit (8–16 KiB) | Refresh token per batch/job |
   | **Arrow Flight SQL** *(Phase 3)* | gRPC TLS + `Authorization: Bearer $JWT` 
| gRPC header limit | Exchanged once for Flight session token |
   
   ### 3.9 Compatibility, Upgrade, Rollback & Verification Matrix
   
   - **Phase 1:** Zero FE metadata version bump, zero Thrift/Protobuf changes; 
rolling back keeps journal replay intact and marks `"jwt"` integrations 
`BROKEN`.
   - **Phase 2:** Optional Thrift fields on `TMasterOpRequest` and the 4 Stream 
Load structs follow `gensrc/AGENTS.md`.
   
   | Layer | Verification Scope | Command / Runner |
   | :--- | :--- | :--- |
   | **Plugin Unit Tests** | RS256/ES256/EdDSA, `exp`/`nbf`/skew, 
`iss`/`aud`/`typ`/`scope`, `alg=none`/key-confusion/embedded-JWK rejection, 
`max_token_bytes`, `kid` rotation + cooldown, `PinnedDnsResolver` 
(`httpclient5`) loopback/IMDS block, offline PEM/JWKS, `require_username_match` 
vs `doris.auth.bound_identity_enforced`, `BAD_CREDENTIAL` vs 
`SOURCE_UNAVAILABLE` vs `MISCONFIGURED` | JUnit 5 + Nimbus + JDK `HttpServer` |
   | **FE Unit Tests** | `AuthenticationIntegrationRuntime`, 
`AuthenticationIntegrationMgr` Follower `EditLog` replay invalidation, CEL 
`CREATE ROLE MAPPING`, `AuthenticatorManager` TLS enforcement, `AS` binding, 
`enable_jit_user`, `authentication_chain`, `ACCOUNT_LOCK`, 
`DelegatedCredential` | `./run-fe-ut.sh` |
   | **Regression Suite** | DDL + end-to-end MySQL TLS login against local mock 
JWKS server | `./run-regression-test.sh` |
   | **Build, Style & License** | Checkstyle 
(`fe/check/checkstyle/checkstyle.xml`), ASF headers (`.licenserc.yaml`), SPI 
check (`AuthenticationPluginSurfaceTest`) | `./build.sh --fe`, `mvn validate` |
   | **Documentation** | `fe-authentication-plugin-jwt/README.md` + 
`apache/doris-website` doc PR | Companion docs PR |
   
   ---
   
   ## 4. Scheduling
   
   | Milestone | Scope | Key Deliverables |
   | :--- | :--- | :--- |
   | **M0: Community Consensus** | `[email protected]` `[Discuss][DSIP]` + 
GitHub Issue | Confirm `"jwt"` vs `"oidc"` naming, built-in vs external 
packaging, assign DSIP number & publish on Confluence |
   | **M1: Phase 1 (MySQL Plugin)** | `fe-authentication-plugin-jwt` + minimal 
`fe-core` HA fix + tests + README | `JwtAuthenticationPlugin`, `JwksUrlGuard` + 
`PinnedDnsResolver`, `JwtTokenValidator`, `JwtClaimMapper`, 
`AuthenticationIntegrationMgr` Follower `EditLog` replay invalidation, unit + 
FE + regression tests, Checkstyle/RAT pass |
   | **M2: Phase 2a (HTTP + Multi-FE)** | `fe-core` + `TMasterOpRequest` | 
`BaseController` / `RestBaseController` `Bearer` auth, `Auth` `(integration, 
externalPrincipal)` reverse lookup, `authenticatedRoles` Follower→Master 
forwarding |
   | **M3: Phase 2b (Stream Load)** | `gensrc/thrift` + `be/` + `fe-core` | 
`TBearerTokenAuth` across all 4 Stream Load RPCs + `StreamLoadHandler` + BE 
header extraction + cloud/non-cloud tests |
   | **M4: Phase 3 (Arrow Flight SQL) & Docs** | `fe-core` Flight + 
`apache/doris-website` | `FlightBearerTokenAuthenticator` JWT multiplexing, 
`FlightAuthResult` role/credential propagation, user documentation PR |
   
   ### Open Questions for `[email protected]`
   
   1. Should the plugin register as `type = "jwt"`, `"oidc"`, or support 
`"oidc"` as an alias (given existing `"oidc"` error-filtering references in 
`AuthenticatorManager` and `AuthenticationIntegrationAuthenticator`)?
   2. Should `fe-authentication-plugin-jwt` be packaged as a built-in runtime 
dependency of `fe-core` (for out-of-the-box `ServiceLoader` discovery) or 
distributed under `authentication_plugins_dir`?
   3. Confirm breaking multi-protocol work into M1 (MySQL plugin), M2 (HTTP + 
multi-FE forwarding), M3 (Stream Load), and M4 (Arrow Flight SQL).
   
   ### Are you willing to submit PR?
   
   - [x] Yes I am willing to submit a PR!
   
   ### Code of Conduct
   
   - [x] I agree to follow this project's [Code of 
Conduct](https://www.apache.org/foundation/policies/conduct)
   


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

To unsubscribe, e-mail: [email protected]

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


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

Reply via email to