Skip to content

Commit 44dbda5

Browse files
fix(bigtable): pass unpatched credentials to Cloud Monitoring metrics exporter (#15163)
## Problem Since commit `b54cc8af5d1` (#2579), `BigtableClientContext.patchCredentials(...)` unconditionally wraps `ServiceAccountJwtAccessCredentials` (returned by `GoogleCredentialsProvider` when ADC uses a service account JSON key) in `JwtCredentialsWithAudience` locked to `settings.getJwtAudience()` (defaulting to `https://bigtable.googleapis.com/`). `JwtCredentialsWithAudience.getRequestMetadata(URI ignored, ...)` intentionally ignores the requested URI so Bigtable data calls always use the configured Bigtable JWT audience. However, `BigtableClientContext.create(...)` called `patchCredentials(builder)` before reading `builder.getCredentialsProvider().getCredentials()`, and then passed those already-patched Bigtable-audience-locked credentials into `MetricsImpl.createBuiltinOtel(...)` -> `BigtableCloudMonitoringExporter` (and `GoogleCloudMetricExporter`). When exporting client-side metrics to `monitoring.googleapis.com`, Cloud Monitoring rejects the Bigtable-audience JWT with `UNAUTHENTICATED`. ## Solution - Resolve unpatched `credentials` once from `builder.getCredentialsProvider().getCredentials()` before patching. - Update `patchCredentials(String audience, @nullable Credentials credentials)` to eagerly validate the audience URI and return patched `dataCredentials` (`JwtCredentialsWithAudience`) for `ServiceAccountJwtAccessCredentials` (or `credentials` unchanged otherwise). - Pass the **unpatched** `credentials` to `MetricsImpl.createBuiltinOtel(...)` (via a `@InternalApi("Visible for testing") @VisibleForTesting` `BuiltinOtelFactory` seam) so Cloud Monitoring requests emit JWTs whose `aud` matches the requested monitoring service URI. - Pass the **patched** `dataCredentials` to `FixedCredentialsProvider` (for `ClientContext`), `BigtableChannelPrimer`, and `ShimImpl`. - Deprecate the accidentally exposed 3-arg `BigtableClientContext.create(EnhancedBigtableStubSettings, Tagger, StatsRecorder)` test overload, expose the 4-arg `create(...)` overload with `@InternalApi("Visible for testing")` and `@VisibleForTesting`, and migrate OpenCensus test callers (`BigtableTracerCallableTest`, `MetricsTracerTest`) to the 4-arg overload. ## Testing - Added `BigtableClientContextTest` (JUnit 5) verifying: - `ServiceAccountJwtAccessCredentials` passed to `BuiltinOtelFactory` remain unpatched and emit a JWT with `aud = https://monitoring.googleapis.com/google.monitoring.v3.MetricService`, while data credentials are wrapped in `JwtCredentialsWithAudience` and emit `aud = https://bigtable.googleapis.com/` (and custom `jwtAudience` overrides apply only to data credentials). - Non-JWT credentials are shared without wrapping and `getCredentials()` is called once. - `NoCredentialsProvider` passes `null` credentials to both metrics and data contexts. - Invalid `jwtAudience` still eagerly throws `IllegalStateException`. - Updated `BigtableDataClientFactoryTest` to verify `credentialsProvider.getCredentials()` is now called once instead of twice. - Updated `BigtableTracerCallableTest` and `MetricsTracerTest` to use the annotated 4-arg `BigtableClientContext.create(...)` test overload. - Ran `mvn -f java-bigtable/pom.xml -pl proto-google-cloud-bigtable-v2,grpc-google-cloud-bigtable-v2,proto-google-cloud-bigtable-admin-v2,grpc-google-cloud-bigtable-admin-v2,google-cloud-bigtable test -Dtest=BigtableClientContextTest,BigtableDataClientFactoryTest,EnhancedBigtableStubTest,JwtCredentialsWithAudienceTests,BigtableTracerCallableTest,MetricsTracerTest -Dsurefire.failIfNoSpecifiedTests=false` (64 tests run, 0 failures, 0 errors; Checkstyle, Error Prone, and Animal Sniffer clean).
1 parent 12edf41 commit 44dbda5

5 files changed

Lines changed: 312 additions & 42 deletions

File tree

‎java-bigtable/google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/data/v2/stub/BigtableClientContext.java‎

Lines changed: 44 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
import com.google.api.core.ApiFunction;
1919
import com.google.api.core.InternalApi;
2020
import com.google.api.gax.core.BackgroundResource;
21-
import com.google.api.gax.core.CredentialsProvider;
2221
import com.google.api.gax.core.ExecutorProvider;
2322
import com.google.api.gax.core.FixedCredentialsProvider;
2423
import com.google.api.gax.core.FixedExecutorProvider;
@@ -42,6 +41,7 @@
4241
import com.google.cloud.bigtable.data.v2.stub.metrics.CustomOpenTelemetryMetricsProvider;
4342
import com.google.cloud.bigtable.gaxx.grpc.BigtableTransportChannelProvider;
4443
import com.google.cloud.bigtable.gaxx.grpc.ChannelPrimer;
44+
import com.google.common.annotations.VisibleForTesting;
4545
import io.grpc.ManagedChannelBuilder;
4646
import io.opencensus.stats.Stats;
4747
import io.opencensus.stats.StatsRecorder;
@@ -75,14 +75,46 @@ public class BigtableClientContext {
7575
private final ExecutorProvider backgroundExecutorProvider;
7676
private final Shim sessionShim;
7777

78+
@InternalApi("Visible for testing")
79+
@VisibleForTesting
80+
@FunctionalInterface
81+
public interface BuiltinOtelFactory {
82+
@Nullable
83+
OpenTelemetrySdk create(
84+
MetricRegistry metricRegistry,
85+
ClientInfo clientInfo,
86+
@Nullable Credentials defaultCredentials,
87+
@Nullable String metricsEndpoint,
88+
String universeDomain,
89+
ScheduledExecutorService executor)
90+
throws IOException;
91+
}
92+
7893
public static BigtableClientContext create(EnhancedBigtableStubSettings settings)
7994
throws IOException {
80-
return create(settings, Tags.getTagger(), Stats.getStatsRecorder());
95+
return create(
96+
settings, Tags.getTagger(), Stats.getStatsRecorder(), MetricsImpl::createBuiltinOtel);
8197
}
8298

99+
/**
100+
* @deprecated This method was only intended for internal testing and was accidentally exposed.
101+
* Use {@link #create(EnhancedBigtableStubSettings)} instead.
102+
*/
103+
@Deprecated
83104
public static BigtableClientContext create(
84105
EnhancedBigtableStubSettings settings, Tagger ocTagger, StatsRecorder ocRecorder)
85106
throws IOException {
107+
return create(settings, ocTagger, ocRecorder, MetricsImpl::createBuiltinOtel);
108+
}
109+
110+
@InternalApi("Visible for testing")
111+
@VisibleForTesting
112+
public static BigtableClientContext create(
113+
EnhancedBigtableStubSettings settings,
114+
Tagger ocTagger,
115+
StatsRecorder ocRecorder,
116+
BuiltinOtelFactory builtinOtelFactory)
117+
throws IOException {
86118
ClientInfo clientInfo =
87119
ClientInfo.builder()
88120
.setInstanceName(InstanceName.of(settings.getProjectId(), settings.getInstanceId()))
@@ -91,15 +123,13 @@ public static BigtableClientContext create(
91123

92124
EnhancedBigtableStubSettings.Builder builder = settings.toBuilder();
93125

94-
// Set up credentials
95-
patchCredentials(builder);
96-
97126
// Fix the credentials so that they can be shared
98127
@Nullable Credentials credentials = null;
99128
if (builder.getCredentialsProvider() != null) {
100129
credentials = builder.getCredentialsProvider().getCredentials();
101130
}
102-
builder.setCredentialsProvider(FixedCredentialsProvider.create(credentials));
131+
@Nullable Credentials dataCredentials = patchCredentials(builder.getJwtAudience(), credentials);
132+
builder.setCredentialsProvider(FixedCredentialsProvider.create(dataCredentials));
103133

104134
String universeDomain = settings.getUniverseDomain();
105135

@@ -122,7 +152,7 @@ public static BigtableClientContext create(
122152
try {
123153
if (settings.areInternalMetricsEnabled()) {
124154
builtinOtel =
125-
MetricsImpl.createBuiltinOtel(
155+
builtinOtelFactory.create(
126156
metricRegistry,
127157
clientInfo,
128158
credentials,
@@ -165,7 +195,7 @@ public static BigtableClientContext create(
165195
builder.getProjectId(),
166196
builder.getInstanceId(),
167197
builder.getAppProfileId(),
168-
credentials,
198+
dataCredentials,
169199
builder.getHeaderProvider().getHeaders());
170200
}
171201

@@ -202,7 +232,7 @@ public static BigtableClientContext create(
202232

203233
Shim shim =
204234
settings.isSessionsEnabled()
205-
? ShimImpl.create(clientInfo, credentials, metrics, backgroundExecutor, settings)
235+
? ShimImpl.create(clientInfo, dataCredentials, metrics, backgroundExecutor, settings)
206236
: new DisabledShim();
207237

208238
try {
@@ -307,34 +337,21 @@ public void close() throws Exception {
307337
}
308338
}
309339

310-
private static void patchCredentials(EnhancedBigtableStubSettings.Builder settings)
311-
throws IOException {
312-
String audience = settings.getJwtAudience();
313-
314-
URI audienceUri = null;
340+
@Nullable
341+
private static Credentials patchCredentials(String audience, @Nullable Credentials credentials) {
342+
URI audienceUri;
315343
try {
316344
audienceUri = new URI(audience);
317345
} catch (URISyntaxException e) {
318346
throw new IllegalStateException("invalid JWT audience", e);
319347
}
320348

321-
CredentialsProvider credentialsProvider = settings.getCredentialsProvider();
322-
if (credentialsProvider == null) {
323-
return;
324-
}
325-
326-
Credentials credentials = credentialsProvider.getCredentials();
327-
if (credentials == null) {
328-
return;
329-
}
330-
331349
if (!(credentials instanceof ServiceAccountJwtAccessCredentials)) {
332-
return;
350+
return credentials;
333351
}
334352

335353
ServiceAccountJwtAccessCredentials jwtCreds = (ServiceAccountJwtAccessCredentials) credentials;
336-
JwtCredentialsWithAudience patchedCreds = new JwtCredentialsWithAudience(jwtCreds, audienceUri);
337-
settings.setCredentialsProvider(FixedCredentialsProvider.create(patchedCreds));
354+
return new JwtCredentialsWithAudience(jwtCreds, audienceUri);
338355
}
339356

340357
private static void setupCookieHolder(

‎java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/BigtableDataClientFactoryTest.java‎

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -204,9 +204,7 @@ public void testNewClientsShareTransportChannel() throws Exception {
204204

205205
// Make sure that only 1 instance is created by each provider
206206
Mockito.verify(transportChannelProvider, Mockito.times(1)).getTransportChannel();
207-
// getCredentials was called twice, in patchCredentials and when creating the fixed
208-
// credentials in BigtableClientContext
209-
Mockito.verify(credentialsProvider, Mockito.times(2)).getCredentials();
207+
Mockito.verify(credentialsProvider, Mockito.times(1)).getCredentials();
210208
Mockito.verify(executorProvider, Mockito.times(1)).getExecutor();
211209
Mockito.verify(watchdogProvider, Mockito.times(1)).getWatchdog();
212210
}
@@ -296,9 +294,7 @@ public void testCreateWithRefreshingChannel() throws Exception {
296294
factory.createForInstance("other-project", "other-instance");
297295

298296
// Make sure that only 1 instance is created by each provider
299-
// getCredentials was called twice, in patchCredentials and when creating the fixed credentials
300-
// in BigtableClientContext
301-
Mockito.verify(credentialsProvider, Mockito.times(2)).getCredentials();
297+
Mockito.verify(credentialsProvider, Mockito.times(1)).getCredentials();
302298
Mockito.verify(executorProvider, Mockito.times(1)).getExecutor();
303299
Mockito.verify(watchdogProvider, Mockito.times(1)).getWatchdog();
304300
assertThat(warmedChannels).hasSize(poolSize + 1);
@@ -341,9 +337,7 @@ public void testCreateWithRefreshingChannelWithDirectAccessByDefault() throws Ex
341337
factory.createForInstance("other-project", "other-instance");
342338

343339
// Make sure that only 1 instance is created by each provider
344-
// getCredentials was called twice, in patchCredentials and when creating the fixed credentials
345-
// in BigtableClientContext
346-
Mockito.verify(credentialsProvider, Mockito.times(2)).getCredentials();
340+
Mockito.verify(credentialsProvider, Mockito.times(1)).getCredentials();
347341
Mockito.verify(executorProvider, Mockito.times(1)).getExecutor();
348342
Mockito.verify(watchdogProvider, Mockito.times(1)).getWatchdog();
349343
assertThat(warmedChannels).hasSize(poolSize + 1);
@@ -388,9 +382,7 @@ public void testCreateWithRefreshingChannelDisableDirectAccess() throws Exceptio
388382
factory.createForInstance("other-project", "other-instance");
389383

390384
// Make sure that only 1 instance is created by each provider
391-
// getCredentials was called twice, in patchCredentials and when creating the fixed credentials
392-
// in BigtableClientContext
393-
Mockito.verify(credentialsProvider, Mockito.times(2)).getCredentials();
385+
Mockito.verify(credentialsProvider, Mockito.times(1)).getCredentials();
394386
Mockito.verify(executorProvider, Mockito.times(1)).getExecutor();
395387
Mockito.verify(watchdogProvider, Mockito.times(1)).getWatchdog();
396388
assertThat(warmedChannels).hasSize(poolSize);

‎java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/internal/csm/opencensus/BigtableTracerCallableTest.java‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import com.google.cloud.bigtable.data.v2.BigtableDataSettings;
3636
import com.google.cloud.bigtable.data.v2.FakeServiceBuilder;
3737
import com.google.cloud.bigtable.data.v2.internal.NameUtil;
38+
import com.google.cloud.bigtable.data.v2.internal.csm.MetricsImpl;
3839
import com.google.cloud.bigtable.data.v2.models.BulkMutation;
3940
import com.google.cloud.bigtable.data.v2.models.ConditionalRowMutation;
4041
import com.google.cloud.bigtable.data.v2.models.Mutation;
@@ -135,7 +136,10 @@ public void sendHeaders(Metadata headers) {
135136
new EnhancedBigtableStub(
136137
settings.getStubSettings().getPerOpSettings(),
137138
BigtableClientContext.create(
138-
settings.getStubSettings(), Tags.getTagger(), localStats.getStatsRecorder()));
139+
settings.getStubSettings(),
140+
Tags.getTagger(),
141+
localStats.getStatsRecorder(),
142+
MetricsImpl::createBuiltinOtel));
139143

140144
// Create another server without injecting the server-timing header and another stub that
141145
// connects to it.
@@ -156,7 +160,8 @@ public void sendHeaders(Metadata headers) {
156160
BigtableClientContext.create(
157161
noHeaderSettings.getStubSettings(),
158162
Tags.getTagger(),
159-
localStats.getStatsRecorder()));
163+
localStats.getStatsRecorder(),
164+
MetricsImpl::createBuiltinOtel));
160165
}
161166

162167
@SuppressWarnings("deprecation")

‎java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/internal/csm/opencensus/MetricsTracerTest.java‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import com.google.bigtable.v2.ReadRowsResponse.CellChunk;
3535
import com.google.cloud.bigtable.data.v2.BigtableDataSettings;
3636
import com.google.cloud.bigtable.data.v2.FakeServiceBuilder;
37+
import com.google.cloud.bigtable.data.v2.internal.csm.MetricsImpl;
3738
import com.google.cloud.bigtable.data.v2.models.BulkMutation;
3839
import com.google.cloud.bigtable.data.v2.models.Query;
3940
import com.google.cloud.bigtable.data.v2.models.Row;
@@ -131,7 +132,10 @@ public void setUp() throws Exception {
131132

132133
BigtableClientContext bigtableClientContext =
133134
BigtableClientContext.create(
134-
settings.getStubSettings(), Tags.getTagger(), localStats.getStatsRecorder());
135+
settings.getStubSettings(),
136+
Tags.getTagger(),
137+
localStats.getStatsRecorder(),
138+
MetricsImpl::createBuiltinOtel);
135139

136140
stub =
137141
new EnhancedBigtableStub(

0 commit comments

Comments
 (0)