Skip to content

[Java] Add external-IdP token federation - #1105

Merged
anilmenon14 merged 1 commit into
mainfrom
feature/java-federated-token-auth
Nov 23, 2026
Merged

anilmenon14 merged 1 commit into
mainfrom
feature/java-federated-token-auth

Conversation

@anilmenon14

@anilmenon14 anilmenon14 commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Adds first-class external-IdP token federation (for example Microsoft Entra ID) to the Java SDK. This brings Java in line with the Rust and Python SDKs (#740 / #760). This is the Java half of #1069. Go (cgo) follows in a separate PR that touches a disjoint set of files (rust/ffi/ + go/).

WHY: Customers whose workloads already carry an IdP identity (Entra ID managed identity, workload identity, and so on) should not have to provision and rotate a Databricks OAuth client secret just to use Zerobus. The Rust core already performs the RFC 8693 token exchange, caching and proactive refresh. Java only needs a way to hand it an IdP token.

WHAT:

  • New public API (com.databricks.zerobus):

    • IdpTokenSupplier: a @FunctionalInterface with String getToken() throws Exception.
    • FederatedToken.accountLevel(supplier): account-level federation, no service principal.
    • FederatedToken.workloadIdentity(supplier, spClientId): workload identity federation as the given Databricks service principal.
    • StreamBuilder.federatedAuth(FederatedToken): an alternative to oauth() and headersProvider(). It replaces any auth set earlier.
    FederatedToken auth = FederatedToken.workloadIdentity(() -> fetchEntraIdToken(), spClientId);
    ZerobusJsonStream stream = sdk.streamBuilder()
        .table("catalog.schema.table")
        .federatedAuth(auth)
        .json()
        .build()
        .join();
  • Token caching: each FederatedToken gets a random cache identity (java:<uuid>) when it is constructed. It is passed to IdpTokenSupplier::with_identity in the Rust core. Exchanged tokens are cached per table. For account-level federation the cache is per instance: streams created from the same instance share one exchanged token, and different instances never share one. For workload identity federation the core keys the cache by the service principal's client ID, so instances with the same client ID share a token. The identity is never derived from an object address.

  • Wiring: a package-private FederatedAuthHeadersProvider carries the FederatedToken through the existing headers-provider slot, which means:

    • Every stream type (Proto, JSON, Avro, Arrow, legacy) and recreateStream() work without new plumbing.
    • ZerobusSdk detects the carrier and dispatches to the new natives.
    • Its getHeaders() throws, because the native SDK owns auth for these streams.
  • JNI (rust/jni):

    • New nativeCreateStreamWithFederatedAuth and nativeCreateArrowStreamWithFederatedAuth entry points.
    • New federated_auth.rs, which bridges the Java supplier (a GlobalRef, called on spawn_blocking) into the Rust IdpTokenSupplier.
    • Error mapping:
      • A Java exception is a retryable TokenFetchError.
      • NonRetriableException and any Error are non-retryable.
      • A null or empty return is rejected as non-retryable, so an empty subject_token is never sent.
    • A hung getToken() can't be cancelled, so the bridge holds a lock for the whole call, as JavaHeadersProvider does. A stuck call then holds one thread per stream, and retries or refreshes wait for it instead of starting new calls.
    • The existing headers-provider natives now share the new create_stream and create_arrow_stream helpers. Their behaviour and error messages are unchanged.
  • Native ABI bumped from 1 to 2 (NATIVE_ABI_VERSION and EXPECTED_NATIVE_ABI), because the Java side calls new native symbols.

  • Docs: Javadoc, a README Authentication section and API reference entries, a new examples/json/FederatedAuthExample.java (Entra ID client-credentials grant, both modes), and NEXT_CHANGELOG.md.

Release note for maintainers: because the ABI changed, a jni/v* native release containing this change must ship before a Java release can pick it up.

How is this tested?

  • Unit tests:
    • FederatedTokenTest: factories, validation, unique cache identities, builder replacement and messages, and the carrier.
    • StreamBuilderTest: a federated JSON build routes the token through the provider slot, and a later oauth() or headersProvider() call drops the federated token.
  • End-to-end through the public API and JNI (FederatedExchangeTest): the SDK's Unity Catalog URL points at a new loopback mock token endpoint (MockTokenServer, on the JDK's built-in HttpServer), which records every exchange request and replies from a script. The gRPC endpoint is a refused port with recovery off: the SDK exchanges the token before it connects, so every stream creation reaches the token endpoint and then fails to connect. The tests check:
    • The exchange request, in both modes:
      • It is POST /oidc/v1/token, form-encoded, with no Authorization header.
      • subject_token is byte-identical to the supplier's token (a realistic ~1.5 KB JWT).
      • grant_type and subject_token_type are the token-exchange values.
      • client_id is sent only for workload identity federation.
    • Caching:
      • Streams created from one FederatedToken share one exchanged token: the supplier is called once and the token endpoint hit once.
      • Two account-level tokens never share an exchanged token.
      • Workload identity tokens with the same client_id share one, and different client_ids don't.
      • Exchanged tokens are per table.
      • 8 concurrent creates on one token still make only one supplier call and one exchange.
    • recreateStream: recreating a federated stream goes through the federated path with the same token, and reuses its exchanged token.
    • Supplier errors:
      • An exception is retryable, isn't cached (the next create calls the supplier again), and its message never contains the IdP token.
      • A NonRetriableException stays permanent.
      • A null or empty token is rejected as permanent and never sent.
      • A thrown Error is contained, and the SDK stays usable afterwards, with no pending JNI exception.
      • A hung getToken() is called once even when the stream retries, and the token works again once the call returns.
    • Refresh: when the exchanged token is due for refresh, the SDK calls the supplier again and exchanges the new token, not a cached one.
    • Exchange failures: HTTP 401/400 from the token endpoint is permanent and carries the server's reason; 500 is retryable.
    • Arrow streams: the Arrow entry point sends the same exact subject_token and correct client_id in both modes, and shares the token across streams.
    • JNI reference release: after the streams are gone, the JNI global reference to the supplier is released, so the supplier is garbage-collected.
  • Each test can fail: I broke the code locally in each of these ways, confirmed that the matching test failed, and reverted:
    • A fresh cache identity per stream, or a constant one.
    • client_id dropped for workload identity, on the JSON/Proto path or on the Arrow path.
    • The token truncated by one character.
    • The supplier's result remembered for each FederatedToken.
    • recreateStream dropping the federated token.
    • Supplier exceptions mapped to non-retryable in the JNI bridge.
    • The JNI reference to the supplier leaked.
    • The lock around getToken() removed (the supplier was then called 3 times instead of once).
  • What the tests found: a supplier returning an empty string sent an empty subject_token to the token endpoint. The JNI bridge now rejects it, as the C FFI does in [Go] Add external-IdP token federation #1106.
  • Native tests (FederatedTokenNativeTest, using the test-helpers feature):
    • The supplier callback preserves retryability for retryable, non-retryable, Error and null results.
    • The supplier error surfaces through FederatedTokenProvider.
    • Real JSON and Arrow federatedAuth stream builds reach the Java supplier over JNI, which proves the signatures and routing.
  • Results:
    • Full Java suite: 142 run, 0 failures (the 37 live integration tests are skipped).
    • cargo fmt --check.
    • cargo clippy -p zerobus-jni --all-features --all-targets -D warnings.
    • cargo test -p zerobus-jni --all-features.
    • google-java-format 1.15.0 clean.
  • Live end-to-end (Azure Databricks workspace, Entra ID app registration): both account-level and workload identity federation ingested records with flush() acknowledged.
  • 70-minute soak per mode, run in parallel. Each soak used one ZerobusSdk and one FederatedToken:
    • Workload: every 5 minutes, a fresh stream ingested 200 records, and a long-lived stream ingested 5 more.
    • Recreate: the long-lived stream was recreated with sdk.recreateStream() at 35 minutes.
    • Token exchanges: the IdP supplier ran exactly twice per mode, a cold mint at t=0 and a proactive refresh at t=55 min (300 s before expiry). Every other stream creation, including the recreated stream, hit the cache.
    • Outcome: both modes PASSed with 14/14 fresh batches and 14/14 long-lived batches, 0 failures, recreate ok, 2,870 records each, and no errors in the logs. The long-lived stream stayed open across the token refresh.

* .join();
* }</pre>
*
* <p>Instances are immutable. Each instance has its own token cache entry: streams created with the

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is only true for account-level federation. The core keys workload identity by client ID (headers_provider.rs:500). So two workloadIdentity(...) instances with the same client ID share one exchanged token, and the second supplier never runs. workloadIdentityIsKeyedByClientId asserts exactly this. Tokens are also cached per table in both modes (tokensArePerTable).

Could we reword this, along with README.md:826 and README.md:1729? That would also match the Python SDK's docs.

 * <p>Instances are immutable. Exchanged tokens are cached per table. For account-level federation
 * the cache is per {@code FederatedToken} instance. For workload identity federation it is per
 * service principal client ID, so two instances with the same client ID share a token.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, you're right. That's only true for account-level federation. I've reworded the Javadoc and both README spots as you suggested, so they now say tokens are cached per table, and per instance or per client ID depending on the mode. I also fixed the PR description and the same wording in the Go PR (#1106, 78985e0). Fixed in 5f252de.

Comment thread rust/jni/src/federated_auth.rs Outdated
let call: IdpTokenCallback = Arc::new(move || {
let supplier_ref = supplier_ref.clone();
Box::pin(async move {
tokio::task::spawn_blocking(move || get_token_blocking(supplier_ref))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A spawn_blocking task can't be cancelled, so a hung getToken() keeps its thread indefinitely.

  • When a proactive refresh times out, the core serves the cached token. A later refresh then starts another call while the first one is still stuck.
  • A cold mint has no timeout at all, so build() never completes.

JavaHeadersProvider caps this by moving its callback_lock guard into the blocking closure. The supplier bridge has no such cap.

Could we at least document it in the README, as the Python SDK does?

- The SDK can't interrupt `getToken()`, and the recovery timeout does not bound it. Set connect
  and read timeouts on the IdP request so a hung call can't stall stream creation.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. I went a step further than the docs. The bridge now holds a lock for the whole getToken() call, the same way JavaHeadersProvider does with callback_lock. A stuck call then holds one thread per stream, and retries or later refreshes wait for the lock and time out instead of starting more calls. The new test hungSupplierIsNotCalledAgainByRetries checks this: without the lock, a hung supplier was called 3 times with 2 retries; with it, once.

I also added your README note on setting connect and read timeouts.

One small correction: a cold mint is bounded. Each attempt runs under recovery_timeout_ms, so build() does fail with "Stream creation timed out". The real cost was the thread left behind by each attempt, which the lock now caps.

The C FFI had the same gap, so #1106 gets the same lock, test and docs (78985e0). Fixed in 5f252de.

Comment thread java/NEXT_CHANGELOG.md

### Internal Changes

- Bumped the native JNI ABI version to 2 for the new federated stream-creation

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the first ABI bump, so it's the first time a mismatched library will fail to load. That failure hits OAuth users too.

  • NativeLoader tries java.library.path first and doesn't fall back to the bundled library on a mismatch. Anyone with an older libzerobus_jni there gets a load failure after upgrading.
  • The laptop-built macOS dylibs that release-java.yml can import through macos-binaries-release also need rebuilding from this source.

Could we add a user-facing line, since "Internal Changes" is easy to skip? For example:

- This version requires a `libzerobus_jni` built from the same release, even if you don't use
  federated auth. If you load the library from `java.library.path`, rebuild it before upgrading.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, that's easy to miss. I added your user-facing line under Major Changes, and it also explains why: the SDK tries java.library.path first and doesn't fall back to the bundled library. The Internal Changes entry now tells maintainers to release a jni/v* build first, and to rebuild any laptop-built macOS dylibs imported through macos-binaries-release. Fixed in 5f252de.


@Override
public Map<String, String> getHeaders() {
throw new IllegalStateException("Federated authentication is handled by the native SDK");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The JNI headers-provider bridge treats IllegalStateException as retryable. This code is unreachable today. But if a future create path misses the instanceof dispatch, the stream would retry auth until the recovery timeout instead of failing at once. Could we throw NonRetriableException, and update carrierIsNeverUsedAsAHeadersProvider to match?

  @Override
  public Map<String, String> getHeaders() throws NonRetriableException {
    throw new NonRetriableException("Federated authentication is handled by the native SDK");
  }

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense. It now throws NonRetriableException, with a short Javadoc saying why. carrierIsNeverUsedAsAHeadersProvider now expects NonRetriableException and checks the message. Fixed in 5f252de.


int status = conn.getResponseCode();
String response = readAll(status < 400 ? conn.getInputStream() : conn.getErrorStream());
if (status != 200) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A 400 or 401 from Entra ID (wrong tenant, client ID or secret) won't fix itself. IllegalStateException is retryable, though, so the SDK keeps retrying until the recovery timeout. Since examples get copied, could we make 4xx other than 429 permanent?

if (status != 200) {
    String message = "Entra ID token request failed: HTTP " + status;
    if (status >= 400 && status < 500 && status != 429) {
        throw new NonRetriableException(message);
    }
    throw new IllegalStateException(message);
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, examples get copied. A 4xx other than 429 now throws NonRetriableException, using your snippet. The Go example had the same pattern, so #1106 makes those errors permanent too (78985e0). Fixed in 5f252de.

Comment thread java/README.md Outdated
refresh), not on every request. It runs on an SDK thread, so it may call the identity provider
over the network, but a slow supplier delays stream creation and recovery.
- **Errors:** an exception from `getToken()` is treated as retryable. Throw
`NonRetriableException` for a permanent failure. Returning `null` is a non-retryable error.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The bridge also rejects an empty string, and an Error is non-retryable too. The getToken Javadoc already says both. Could the README match?

- **Errors:** an exception from `getToken()` is treated as retryable. Throw
  `NonRetriableException` for a permanent failure. Returning `null` or an empty string, or
  throwing an `Error`, is also a non-retryable error.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. The README now says an empty string or a thrown Error is also non-retryable, matching the Javadoc. I made the Go README say the same about an empty token in #1106 (78985e0). Fixed in 5f252de.

@anilmenon14
anilmenon14 force-pushed the feature/java-federated-token-auth branch from 9e3750a to d4b1ca3 Compare November 21, 2026 16:08
Add first-class external-IdP (e.g. Microsoft Entra ID) token federation
to the Java SDK, matching the Rust and Python SDKs (#740). The native
SDK exchanges the IdP token for a Zerobus-scoped Databricks token
(RFC 8693), caches it, and refreshes it before expiry.

- New public API: IdpTokenSupplier and FederatedToken
  (accountLevel / workloadIdentity), plus StreamBuilder.federatedAuth().
- Each FederatedToken carries a random cache identity, so streams that
  share an instance share one exchanged token.
- The token rides the existing headers-provider slot via a package-private
  carrier, so all stream types and recreateStream() work unchanged.
- JNI: new nativeCreate{,Arrow}StreamWithFederatedAuth entry points that
  bridge the Java supplier into the Rust IdpTokenSupplier. Java exceptions
  are retryable, except NonRetriableException and Error. A null or empty
  token is rejected, so an empty subject_token is never sent.
- Bump the native ABI version from 1 to 2.
- Tests run federation through the public API and JNI against a mock
  token endpoint that records every exchange request.

Refs #1069

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Anil Menon <anil.menon@databricks.com>

@teodordelibasic-db teodordelibasic-db left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@anilmenon14
anilmenon14 added this pull request to the merge queue Nov 23, 2026
Merged via the queue into main with commit 7c1e966 Nov 23, 2026
52 checks passed
@anilmenon14
anilmenon14 deleted the feature/java-federated-token-auth branch November 23, 2026 16:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants