Repository navigation
[Java] Add external-IdP token federation - #1105
Conversation
d4cdbcd to
9e3750a
Compare
| * .join(); | ||
| * }</pre> | ||
| * | ||
| * <p>Instances are immutable. Each instance has its own token cache entry: streams created with the |
There was a problem hiding this comment.
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.There was a problem hiding this comment.
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.
| 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)) |
There was a problem hiding this comment.
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.There was a problem hiding this comment.
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.
|
|
||
| ### Internal Changes | ||
|
|
||
| - Bumped the native JNI ABI version to 2 for the new federated stream-creation |
There was a problem hiding this comment.
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.
NativeLoadertriesjava.library.pathfirst and doesn't fall back to the bundled library on a mismatch. Anyone with an olderlibzerobus_jnithere gets a load failure after upgrading.- The laptop-built macOS dylibs that
release-java.ymlcan import throughmacos-binaries-releasealso 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.There was a problem hiding this comment.
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"); |
There was a problem hiding this comment.
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");
}There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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);
}| 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. |
There was a problem hiding this comment.
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.9e3750a to
d4b1ca3
Compare
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>
d4b1ca3 to
5f252de
Compare
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@FunctionalInterfacewithString 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 tooauth()andheadersProvider(). It replaces any auth set earlier.Token caching: each
FederatedTokengets a random cache identity (java:<uuid>) when it is constructed. It is passed toIdpTokenSupplier::with_identityin 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
FederatedAuthHeadersProvidercarries theFederatedTokenthrough the existing headers-provider slot, which means:recreateStream()work without new plumbing.ZerobusSdkdetects the carrier and dispatches to the new natives.getHeaders()throws, because the native SDK owns auth for these streams.JNI (
rust/jni):nativeCreateStreamWithFederatedAuthandnativeCreateArrowStreamWithFederatedAuthentry points.federated_auth.rs, which bridges the Java supplier (aGlobalRef, called onspawn_blocking) into the RustIdpTokenSupplier.TokenFetchError.NonRetriableExceptionand anyErrorare non-retryable.nullor empty return is rejected as non-retryable, so an emptysubject_tokenis never sent.getToken()can't be cancelled, so the bridge holds a lock for the whole call, asJavaHeadersProviderdoes. A stuck call then holds one thread per stream, and retries or refreshes wait for it instead of starting new calls.create_streamandcreate_arrow_streamhelpers. Their behaviour and error messages are unchanged.Native ABI bumped from 1 to 2 (
NATIVE_ABI_VERSIONandEXPECTED_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), andNEXT_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?
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 lateroauth()orheadersProvider()call drops the federated token.FederatedExchangeTest): the SDK's Unity Catalog URL points at a new loopback mock token endpoint (MockTokenServer, on the JDK's built-inHttpServer), 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:POST /oidc/v1/token, form-encoded, with noAuthorizationheader.subject_tokenis byte-identical to the supplier's token (a realistic ~1.5 KB JWT).grant_typeandsubject_token_typeare the token-exchange values.client_idis sent only for workload identity federation.FederatedTokenshare one exchanged token: the supplier is called once and the token endpoint hit once.client_idshare one, and differentclient_ids don't.recreateStream: recreating a federated stream goes through the federated path with the same token, and reuses its exchanged token.NonRetriableExceptionstays permanent.nullor empty token is rejected as permanent and never sent.Erroris contained, and the SDK stays usable afterwards, with no pending JNI exception.getToken()is called once even when the stream retries, and the token works again once the call returns.subject_tokenand correctclient_idin both modes, and shares the token across streams.client_iddropped for workload identity, on the JSON/Proto path or on the Arrow path.FederatedToken.recreateStreamdropping the federated token.getToken()removed (the supplier was then called 3 times instead of once).subject_tokento the token endpoint. The JNI bridge now rejects it, as the C FFI does in [Go] Add external-IdP token federation #1106.FederatedTokenNativeTest, using thetest-helpersfeature):Errorandnullresults.FederatedTokenProvider.federatedAuthstream builds reach the Java supplier over JNI, which proves the signatures and routing.cargo fmt --check.cargo clippy -p zerobus-jni --all-features --all-targets -D warnings.cargo test -p zerobus-jni --all-features.flush()acknowledged.ZerobusSdkand oneFederatedToken:sdk.recreateStream()at 35 minutes.