GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||
GeezerVison is showing github.com — feat(spanner): Support dynamic TLS certificate and key rotation for Spanner Omni by sagnghos · Pull Request #14456 · googleapis/google-cloud-java Conversation
|
|
/gemini review |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
This pull request introduces dynamic certificate and key reloading for Spanner Omni instances by adding DynamicKeyManager and DynamicTrustManager to automatically reload client certificates, private keys, and server root CA certificates from disk when modified. It also updates configuration classes, connection properties, and connection pools to support these new options, alongside comprehensive unit tests. The review feedback highlights a critical issue in both new managers where using ThreadPoolExecutor.DiscardPolicy silently discards rejected tasks, permanently blocking future reloads because the isReloading flag is never reset. To resolve this, it is recommended to use ThreadPoolExecutor.AbortPolicy so that RejectedExecutionException is correctly thrown and handled.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
9ad0f6d to
77f2b1a
Compare
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Thank you for working on this! This PR directly targets the issue described in b/562755231 ("PGAdapter: Rotated certificates are not picked up until restart"). Dynamically reloading mTLS client key material and server root CA certificates in Spanner Omni without requiring application or process restarts is a significant improvement.
The overall approach of using custom X509ExtendedKeyManager and X509ExtendedTrustManager implementations integrated into Netty's SslContext is the right design.
There are two critical issues in the current implementation, along with a few minor observations, that should be addressed before merging:
In both DynamicKeyManager.java and DynamicTrustManager.java:
void checkAndReload() { ... if (checkIntervalNs == 0) { try { doReloadCheck(now); } finally { isReloading.set(false); } } else { try { ASYNC_RELOAD_EXECUTOR.execute(() -> { try { doReloadCheck(System.nanoTime()); } finally { isReloading.set(false); } }); } catch (RejectedExecutionException e) { isReloading.set(false); } } }
In production, checkIntervalMs defaults to 5000L (checkIntervalNs > 0). When a handshake occurs:
checkAndReload() is called from chooseEngineClientAlias() or checkServerTrusted().now - lastCheckedNs >= checkIntervalNs and queues doReloadCheck() onto ASYNC_RELOAD_EXECUTOR.checkAndReload() returns immediately, before the background thread has read or parsed the updated files on disk.DynamicKeyManager: it returns currentMaterial.alias (the old certificate/key). If the previous certificate is already expired, the client presents expired credentials and the server rejects the handshake.DynamicTrustManager: Netty calls checkServerTrusted(), which validates the server's certificate against currentMaterial.delegate (the old CA). If the server is presenting a certificate signed by the newly rotated CA, this throws a CertificateException and immediately terminates the TLS handshake.Note: Unit tests did not catch this because all rotation tests instantiate the managers with checkIntervalMs = 0L, which takes the synchronous execution path.
Suggestions:
File.lastModified() and File.length() takes microseconds (< 5 µs). If timestamps and lengths have not changed, it returns immediately without any disk read or cryptographic parsing.ScheduledExecutorService) that checks and reloads the files periodically every 5–30s independently of handshakes. That way, currentMaterial is already fresh before any handshake arrives, avoiding both event-loop I/O and handshake failures.DynamicKeyManager.getCertificateChain(String alias)In DynamicKeyManager.java:
@Override public X509Certificate[] getCertificateChain(String alias) { KeyMaterial mat = (alias != null) ? materials.get(alias) : this.currentMaterial; return mat != null ? mat.certificateChain.clone() : new X509Certificate[0]; }
The standard specification for X509KeyManager.getCertificateChain(String alias) states:
"Returns: the certificate chain associated with the given alias, or
nullif the alias can't be found."
Returning new X509Certificate[0] instead of null causes standard JSSE and TLS engine implementations that do:
X509Certificate[] certs = keyManager.getCertificateChain(alias); if (certs != null) { PublicKey pubKey = certs[0].getPublicKey(); }
to fail with an ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0.
Suggestion:
Return null when mat == null (or when mat.certificateChain is empty):
@Override public X509Certificate[] getCertificateChain(String alias) { KeyMaterial mat = (alias != null) ? materials.get(alias) : this.currentMaterial; return (mat != null && mat.certificateChain != null && mat.certificateChain.length > 0) ? mat.certificateChain.clone() : null; }
SpannerOptions.toBuilder().build() configurator chaining:
In SpannerOptions.java, each call to toBuilder().build() wraps the existing channelConfigurator with an additional lambda layer that re-applies sslContext. Consider ensuring that repeated toBuilder().build() calls do not accumulate redundant configurator layers.
Documentation on CA certificate rotation:
In SpannerOptions.Builder, DynamicTrustManager is initialized only when hasCaCert is true (builder.caCertificate is set). If a user only sets useClientCert(...) without setCaCertificate(...), the server root still relies on the static JVM trust store. Please highlight in the PGAdapter documentation that to enable dynamic CA rotation, users must explicitly supply the CA certificate path (e.g., via -r "caCertificate=/path/to/ca.crt;..." or setCaCertificate(...)).
Test coverage for non-zero check interval:
Adding a test for DynamicKeyManager and DynamicTrustManager where checkIntervalMs > 0 and verifying that rotation works seamlessly would prevent regressions.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
…panner Omni
Add support for zero-downtime dynamic reloading of client certificates/keys (mTLS)
and server root CA certificates in Spanner Omni without requiring application or connection pool restarts.
Changes:
- DynamicKeyManager (com.google.cloud.spanner.omni): An X509ExtendedKeyManager that
monitors certificate/key file modification times and lengths on disk. Uses non-blocking
tryLock() and atomic versioned alias mapping to reload rotated client certificates and
RSA/EC private keys during active TLS handshakes without blocking Netty event loop threads.
- DynamicTrustManager (com.google.cloud.spanner.omni): An X509ExtendedTrustManager that
dynamically reloads rotated server root CA certificates into an in-memory keystore/trust
manager upon file changes.
- SpannerOptions & Connection API:
- Added Builder.setCaCertificate(String) and getCaCertificate() across SpannerOptions,
ConnectionProperties, ConnectionOptions, and SpannerPool.
- Updated Builder.useClientCert(String, String) to use dynamic key management.
- Preserved raw certificate paths in SpannerOptions and built transient Netty SslContext
in prepareBuilder to prevent transport leaks.
- SpannerOmniHelper: Added support for spanner.ca_cert_path and updated mTLS setup detection.
- Tests: Added comprehensive unit tests covering dynamic certificate/key rotation, CA rotation,
multi-CA bundles, fallback on corruption/mismatch, throttling, and options configuration.
Fixes b/562755231
c197d47 to
9efa817
Compare
…ation - Preserve instanceType, usePlainText, and host in SpannerOptions and its Builder copy constructor so options.toBuilder().build() retains Spanner Omni settings. - Sample file timestamps and lengths before Files.readAllBytes() to prevent TOCTOU races during file rotation. - Use lock.lock() with double-checked locking in DynamicKeyManager and DynamicTrustManager to prevent handshake failure race conditions during concurrent requests. - Improve binary DER vs headerless Base64 key detection by checking for multi-byte sequence length tags. - Eliminate background thread pool executors to prevent thread and resource leaks. - Return null instead of empty array in DynamicKeyManager.getCertificateChain for unknown aliases according to JSSE specification. - Use unwrappable OmniSslChannelConfigurator in SpannerOptions to avoid nested lambda wrapping on repeated toBuilder().build() calls without modifying GapicSpannerRpc. - Unwrap OmniSslChannelConfigurator even when omniSslContext is null. - Fix SpannerPool to validate clientCertificate and clientCertificateKey independently so IllegalArgumentException is properly surfaced. - Add comprehensive unit tests covering concurrent handshakes during rotation, headerless Base64 keys, SpannerOptions toBuilder() preservation, and SpannerPool error handling.
9efa817 to
f0a17f3
Compare
| * @param clientCertificate The path to the client certificate file. | ||
| * @return this builder | ||
| */ | ||
| public Builder setClientCertificate(String clientCertificate) { |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Where is this used?
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Removed
Sorry, something went wrong.
There was an error while loading. Please reload this page.
…ions.Builder In the Spanner Connection API and JDBC driver, connection properties (including clientCertificate, clientKey, and caCertificate) are configured via the connection URI string. Removing the dedicated builder setters from ConnectionOptions.Builder keeps the builder API surface minimal while preserving URI property parsing and the getters used by SpannerPool.
There was an error while loading. Please reload this page.
🤖 I have created a release *beep* *boop* --- <details><summary>1.92.0</summary> ## [1.92.0](v1.91.0...v1.92.0) (2026-09-23) ### Features * **bigquery-jdbc:** add `EnableTimestampPicos` connection property and its plumbing ([#14284](#14284)) ([b4aa5ac](b4aa5ac)) * **bigquery-jdbc:** implement picosecond temporal math and formatting engine ([#14286](#14286)) ([2a9612a](2a9612a)) * **bigquery-jdbc:** support picosecond in REST JSON path and nested types ([#14334](#14334)) ([15ffe4a](15ffe4a)) * **bigquery-jdbc:** support picosecond in `PreparedStatement` parameters and batching ([#14373](#14373)) ([c1aac66](c1aac66)) * **bigquery-jdbc:** support picosecond timestamp in `ResultSetMetaData` and `DatabaseMetaData` ([#14358](#14358)) ([43acdd3](43acdd3)) * **bigquery-jdbc:** support picosecond timestamps in Arrow Storage Read API and nested types ([#14332](#14332)) ([b5d9aca](b5d9aca)) * **bigquery-jdbc:** support qualified project delimiter in `DefaultDataset` property ([#14240](#14240)) ([6e8d6c8](6e8d6c8)) * **bigquery:** accelerate row-based query() with Arrow wire format ([#14405](#14405)) ([8d12a8f](8d12a8f)) * **bigquery:** add ArrowDeserializer helper utility ([#13943](#13943)) ([d9a298b](d9a298b)) * **bigquery:** add ArrowQueryPageFetcher for Arrow query result pagination ([#14404](#14404)) ([615409f](615409f)) * **bigquery:** add ArrowQueryResult and ArrowQueryResultImpl for Arrow result streaming ([#13944](#13944)) ([a62fdf8](a62fdf8)) * **bigquery:** add Storage Read API slow-path fallback for row-based query() ([#14409](#14409)) ([26e568a](26e568a)) * **bigquery:** add zero-copy queryArrow API for Arrow VectorSchemaRoot streaming ([#14402](#14402)) ([b44ffe8](b44ffe8)) * **bigquery:** make BigQuery AutoCloseable with default no-op close method ([#14434](#14434)) ([00bf3de](00bf3de)) * **firestore:** add support for BSON types ([#13189](#13189)) ([8a123d9](8a123d9)) * **gax:** add ApiCallContext and request-level settings overloads to ResumableUploadCallable ([#14251](#14251)) ([e8cbd42](e8cbd42)) * **gax:** add globalTimeout settings field to ResumableUploadCallSettings ([#14253](#14253)) ([438cda6](438cda6)) * **gax:** add resumable upload error classification and retry algorithm ([#14419](#14419)) ([b70396d](b70396d)) * **gax:** add ResumableUploadCallable creation to Callables and HttpJsonCallableFactory ([#14242](#14242)) ([7de24de](7de24de)) * **gax:** implement baseline Callable and Future for resumable uploads ([#14241](#14241)) ([5a54db9](5a54db9)) * **generator:** add model flag and allowlist parser for resumable upload RPCs ([#14317](#14317)) ([acc1856](acc1856)) * **generator:** emit resumable upload client surface ([#14319](#14319)) ([a9fed00](a9fed00)) * **generator:** emit resumable upload settings and HttpJson upload stub ([#14321](#14321)) ([c122474](c122474)) * **generator:** enable resumable upload generation for showcase ([#14325](#14325)) ([f9ebd79](f9ebd79)) * **generator:** switch resumable upload specialized stubs to package private ([#14471](#14471)) ([0d4e875](0d4e875)) * **generator:** wire transport stub delegation to resumable upload stubs ([#14322](#14322)) ([cc4b980](cc4b980)) * **google/cloud/backupdr/v1beta:** add backupdr ([#14410](#14410)) ([a4a47da](a4a47da)) * **google/cloud/networkservices/v1beta1:** add networkservices ([#14407](#14407)) ([21c4955](21c4955)) * **pubsub:** add publish telemetry headers for publish attempt observability ([#14338](#14338)) ([c167ab8](c167ab8)) * **pubsub:** implement publish hedging to reduce tail latency ([#13735](#13735)) ([b302615](b302615)) * **spanner:** Support dynamic TLS certificate and key rotation for Spanner Omni ([#14456](#14456)) ([ffc745c](ffc745c)) * **storage/control:** add delete folder recursive sample ([#13642](#13642)) ([f4b1b46](f4b1b46)) * **storage/control:** add delete folder recursive sample ([#14397](#14397)) ([2c01d55](2c01d55)) ### Bug Fixes * **auth:** restore transportFactory upon deserialization in InternalAwsSecurityCredentialsSupplier ([#14340](#14340)) ([beea42f](beea42f)) * **bigquery-jdbc:** ensure row ordering in PCNT IT ([#14330](#14330)) ([a16f048](a16f048)) * **bigquery-jdbc:** fix htapi fallback due to permission logic ([#14418](#14418)) ([21e6dc8](21e6dc8)) * **bigquery-jdbc:** fix Timestamp assertions ([#14290](#14290)) ([533ba14](533ba14)) * **bigquery-jdbc:** handle null parameters in Storage Write API bulk inserts ([#14270](#14270)) ([dd2c41a](dd2c41a)), refs [#14066](#14066) * **bigquery-jdbc:** handle SQL NULLs in ResultSet primitive getters ([#14383](#14383)) ([8e464fe](8e464fe)), refs [#14371](#14371) * **bigquery:** default Arrow pagination stream location to US instead of global ([#14458](#14458)) ([2775eb1](2775eb1)) * **bigquery:** preserve page token and paginate correctly in Arrow query when maxResults is set ([#14469](#14469)) ([f5601f4](f5601f4)) * **bigquery:** use first page row count for Arrow query pagination offset ([#14466](#14466)) ([9d10dd0](9d10dd0)) * **bigtable:** don't notify config listeners while holding the manager lock ([#14294](#14294)) ([4426ccd](4426ccd)) * **bigtable:** fall back to classic path when per-RPC CallCredentials are set on session path ([#14477](#14477)) ([57bacb0](57bacb0)) * **bigtable:** fix abnormal session closures and scale-up in session pool ([#14431](#14431)) ([6361ecd](6361ecd)) * **biqguery:** fix undeclared QueryParameter wiring in QueryStatistics ([#14401](#14401)) ([64cf1d3](64cf1d3)) * **bom:** restore google-cloud-spanner-jdbc to libraries-bom ([#14362](#14362)) ([bc7be5e](bc7be5e)), refs [#14347](#14347) * **spanner:** honor maxAttempts and totalTimeout in streaming resume loop ([#14370](#14370)) ([305f47d](305f47d)) * **spanner:** only set snapshot isolation read timestamp for SI or optimistic txns in CloudClientExecutor ([#14346](#14346)) ([54c0d0f](54c0d0f)) * **spanner:** prevent statement cancellation race in AbstractBaseUnitOfWork ([#14283](#14283)) ([d9a8eef](d9a8eef)) * **spanner:** re-enable ITInstanceAdminTest on cloud-devel and cloud-staging ([#14281](#14281)) ([89a8268](89a8268)) ### Performance Improvements * **spanner:** stop re-parsing the request id on every RPC ([#14353](#14353)) ([46108f4](46108f4)) ### Documentation * Add a Http/Json Post-Quantum Cryptography Guide ([#13963](#13963)) ([fcc65b0](fcc65b0)) * **bigquery:** add QueryArrow code sample and document JDK 17+ JVM requirements ([#14437](#14437)) ([bd363f6](bd363f6)) </details> --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --------- Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com>
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
There was an error while loading. Please reload this page.