From a82161f2f639d11a7ff7c1fd6ab9af37bdf7d27d Mon Sep 17 00:00:00 2001 From: Nidhi Nandwani Date: Thu, 19 Nov 2026 17:42:25 +0000 Subject: [PATCH 1/3] feat(storage): add MetricsRecordingCredentials decorator for credential_refresh.duration Add Debug-tier StorageClientMetrics.recordCredentialRefreshDuration (exact 4-key clientAttributes + error.type, unit "s") and package-private MetricsRecordingCredentials extending GoogleCredentials to preserve PRIVACY_AND_INTEGRITY and QuotaProjectIdProvider, skip incompatible credential types (NoCredentials, non-GoogleCredentials, GdchCredentials, unscoped ServiceAccountCredentials, AppEngineCredentials), deduplicate concurrent coalesced refreshes with a backward-clobber-safe CAS loop, and handle Java serialization safely. [Generated-by: AI] --- .../storage/MetricsRecordingCredentials.java | 300 +++++++++++++ .../cloud/storage/StorageClientMetrics.java | 9 + .../MetricsRecordingCredentialsTest.java | 415 ++++++++++++++++++ .../storage/StorageClientMetricsTest.java | 51 +++ 4 files changed, 775 insertions(+) create mode 100644 java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/MetricsRecordingCredentials.java create mode 100644 java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/MetricsRecordingCredentialsTest.java diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/MetricsRecordingCredentials.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/MetricsRecordingCredentials.java new file mode 100644 index 000000000000..ab2f724a75c0 --- /dev/null +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/MetricsRecordingCredentials.java @@ -0,0 +1,300 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.storage; + +import static java.util.Objects.requireNonNull; + +import com.google.api.core.ApiClock; +import com.google.auth.CredentialTypeForMetrics; +import com.google.auth.Credentials; +import com.google.auth.RequestMetadataCallback; +import com.google.auth.oauth2.AccessToken; +import com.google.auth.oauth2.GdchCredentials; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.auth.oauth2.ServiceAccountCredentials; +import com.google.common.annotations.VisibleForTesting; +import io.opentelemetry.context.Context; +import java.io.IOException; +import java.io.InterruptedIOException; +import java.io.ObjectInputStream; +import java.net.SocketTimeoutException; +import java.net.URI; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CancellationException; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; + +/** + * Package-private {@link GoogleCredentials} decorator that records {@code + * gcp.storage.client.auth.credential_refresh.duration} for blocking token acquisitions and + * refreshes while preserving {@code instanceof GoogleCredentials} (for gRPC {@code + * PRIVACY_AND_INTEGRITY}) and {@code QuotaProjectIdProvider}. Cached and non-blocking {@code STALE} + * async lookups are skipped; concurrent coalesced successful refreshes are deduplicated while + * failures are recorded per waiter. + */ +@NullMarked +final class MetricsRecordingCredentials extends GoogleCredentials { + + private static final long serialVersionUID = 1L; + private static final int MAX_CAUSE_DEPTH = 20; + private static final String APP_ENGINE_CREDENTIALS_CLASS = + "com.google.auth.appengine.AppEngineCredentials"; + private static final String LEGACY_APP_ENGINE_CREDENTIALS_CLASS = + "com.google.auth.oauth2.AppEngineCredentials"; + + private final GoogleCredentials delegate; + private final transient @Nullable StorageClientMetrics metrics; + private final transient @Nullable ApiClock clock; + private transient AtomicReference<@Nullable AccessToken> lastObservedToken; + + private MetricsRecordingCredentials( + GoogleCredentials delegate, StorageClientMetrics metrics, ApiClock clock) { + this.delegate = requireNonNull(delegate, "delegate cannot be null"); + this.metrics = requireNonNull(metrics, "metrics cannot be null"); + this.clock = requireNonNull(clock, "clock cannot be null"); + this.lastObservedToken = new AtomicReference<>(delegate.getAccessToken()); + } + + static @Nullable Credentials wrap( + @Nullable Credentials credentials, @Nullable StorageClientMetrics metrics, ApiClock clock) { + if (!(credentials instanceof GoogleCredentials) + || credentials instanceof GdchCredentials + || (credentials instanceof ServiceAccountCredentials + && ((ServiceAccountCredentials) credentials).createScopedRequired()) + || credentials instanceof MetricsRecordingCredentials + || metrics == null + || metrics.getCredentialRefreshDuration() == null) { + return credentials; + } + String className = credentials.getClass().getName(); + if (APP_ENGINE_CREDENTIALS_CLASS.equals(className) + || LEGACY_APP_ENGINE_CREDENTIALS_CLASS.equals(className)) { + return credentials; + } + return new MetricsRecordingCredentials((GoogleCredentials) credentials, metrics, clock); + } + + @VisibleForTesting + static String mapAuthErrorType(@Nullable Throwable t) { + Throwable current = t; + int depth = 0; + while (current != null && depth < MAX_CAUSE_DEPTH) { + // Check SocketTimeoutException before InterruptedIOException since it is a subclass. + if (current instanceof SocketTimeoutException || current instanceof TimeoutException) { + return StorageErrorTypeMapper.STATUS_TIMEOUT; + } + if (current instanceof CancellationException + || current instanceof InterruptedException + || current instanceof InterruptedIOException) { + return StorageErrorTypeMapper.STATUS_CANCELLED; + } + Throwable next = current.getCause(); + if (next == current) { + break; + } + current = next; + depth++; + } + return StorageErrorTypeMapper.STATUS_AUTHENTICATION_ERROR; + } + + @Override + public String getAuthenticationType() { + return delegate.getAuthenticationType(); + } + + @Override + public String getUniverseDomain() throws IOException { + return delegate.getUniverseDomain(); + } + + @Override + public CredentialTypeForMetrics getMetricsCredentialType() { + return delegate.getMetricsCredentialType(); + } + + @Override + public boolean hasRequestMetadata() { + return delegate.hasRequestMetadata(); + } + + @Override + public boolean hasRequestMetadataOnly() { + return delegate.hasRequestMetadataOnly(); + } + + @Override + public @Nullable String getQuotaProjectId() { + return delegate.getQuotaProjectId(); + } + + @Override + public @Nullable String getProjectId() { + return delegate.getProjectId(); + } + + @Override + public boolean createScopedRequired() { + return delegate.createScopedRequired(); + } + + @Override + public GoogleCredentials createScoped(Collection scopes) { + return rewrap(delegate.createScoped(scopes)); + } + + @Override + public GoogleCredentials createScoped( + Collection scopes, Collection defaultScopes) { + return rewrap(delegate.createScoped(scopes, defaultScopes)); + } + + @Override + public Map> getRequestMetadata(@Nullable URI uri) throws IOException { + StorageClientMetrics m = this.metrics; + ApiClock c = this.clock; + if (m == null || c == null) { + return delegate.getRequestMetadata(uri); + } + Context otelContext = Context.current(); + AccessToken before = delegate.getAccessToken(); + long startNanos = c.nanoTime(); + try { + Map> metadata = delegate.getRequestMetadata(uri); + maybeRecordTokenChange(m, c, otelContext, startNanos, before); + return metadata; + } catch (IOException e) { + record(m, c, otelContext, startNanos, mapAuthErrorType(e)); + throw e; + } + } + + @Override + public void getRequestMetadata( + @Nullable URI uri, Executor executor, RequestMetadataCallback callback) { + StorageClientMetrics m = this.metrics; + ApiClock c = this.clock; + if (m == null || c == null) { + delegate.getRequestMetadata(uri, executor, callback); + return; + } + Context otelContext = Context.current(); + AccessToken before = delegate.getAccessToken(); + long startNanos = c.nanoTime(); + delegate.getRequestMetadata( + uri, + executor, + new RequestMetadataCallback() { + @Override + public void onSuccess(Map> metadata) { + maybeRecordTokenChange(m, c, otelContext, startNanos, before); + callback.onSuccess(metadata); + } + + @Override + public void onFailure(Throwable exception) { + record(m, c, otelContext, startNanos, mapAuthErrorType(exception)); + callback.onFailure(exception); + } + }); + } + + @Override + public void refresh() throws IOException { + runRecorded(delegate::refresh); + } + + @Override + public void refreshIfExpired() throws IOException { + runRecorded(delegate::refreshIfExpired); + } + + private void runRecorded(IoAction action) throws IOException { + StorageClientMetrics m = this.metrics; + ApiClock c = this.clock; + if (m == null || c == null) { + action.run(); + return; + } + Context otelContext = Context.current(); + AccessToken before = delegate.getAccessToken(); + long startNanos = c.nanoTime(); + try { + action.run(); + maybeRecordTokenChange(m, c, otelContext, startNanos, before); + } catch (IOException e) { + record(m, c, otelContext, startNanos, mapAuthErrorType(e)); + throw e; + } + } + + @FunctionalInterface + private interface IoAction { + void run() throws IOException; + } + + private GoogleCredentials rewrap(GoogleCredentials scoped) { + if (scoped == delegate) { + return this; + } + StorageClientMetrics m = this.metrics; + ApiClock c = this.clock; + if (m == null || c == null) { + return scoped; + } + return (GoogleCredentials) requireNonNull(wrap(scoped, m, c)); + } + + private void maybeRecordTokenChange( + StorageClientMetrics m, + ApiClock c, + Context otelContext, + long startNanos, + @Nullable AccessToken before) { + AccessToken after = delegate.getAccessToken(); + if (after == null || Objects.equals(before, after)) { + return; + } + while (true) { + AccessToken prev = lastObservedToken.get(); + if (Objects.equals(prev, after) || !Objects.equals(delegate.getAccessToken(), after)) { + return; + } + if (lastObservedToken.compareAndSet(prev, after)) { + record(m, c, otelContext, startNanos, StorageErrorTypeMapper.STATUS_OK); + return; + } + } + } + + private static void record( + StorageClientMetrics m, ApiClock c, Context otelContext, long startNanos, String errorType) { + double durationSeconds = (c.nanoTime() - startNanos) / 1_000_000_000.0; + m.recordCredentialRefreshDuration(otelContext, durationSeconds, errorType); + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + this.lastObservedToken = new AtomicReference<>(delegate.getAccessToken()); + } +} diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java index 58ba7cae981a..6fd280fdc54e 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java @@ -603,6 +603,15 @@ void recordStallDuration( stallDuration.record(durationSeconds, attributes, otelContext); } + void recordCredentialRefreshDuration( + Context otelContext, double durationSeconds, String errorType) { + if (credentialRefreshDuration == null) { + return; + } + Attributes attributes = clientAttributes.toBuilder().put(KEY_ERROR_TYPE, errorType).build(); + credentialRefreshDuration.record(durationSeconds, attributes, otelContext); + } + @Nullable static StorageMetricsContext createContext( @Nullable StorageClientMetrics metrics, String operationName) { diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/MetricsRecordingCredentialsTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/MetricsRecordingCredentialsTest.java new file mode 100644 index 000000000000..194a33b5c31b --- /dev/null +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/MetricsRecordingCredentialsTest.java @@ -0,0 +1,415 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.storage; + +import static com.google.cloud.storage.StorageClientMetrics.ARTIFACT_STORAGE; +import static com.google.cloud.storage.StorageClientMetrics.KEY_ERROR_TYPE; +import static com.google.cloud.storage.StorageClientMetrics.KEY_GCP_CLIENT_ARTIFACT; +import static com.google.cloud.storage.StorageClientMetrics.KEY_GCP_CLIENT_SERVICE; +import static com.google.cloud.storage.StorageClientMetrics.KEY_GCP_CLIENT_VERSION; +import static com.google.cloud.storage.StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_AUTH_CREDENTIAL_REFRESH_DURATION; +import static com.google.cloud.storage.StorageClientMetrics.SERVICE_STORAGE; +import static com.google.cloud.storage.StorageErrorTypeMapper.STATUS_AUTHENTICATION_ERROR; +import static com.google.cloud.storage.StorageErrorTypeMapper.STATUS_CANCELLED; +import static com.google.cloud.storage.StorageErrorTypeMapper.STATUS_OK; +import static com.google.cloud.storage.StorageErrorTypeMapper.STATUS_TIMEOUT; +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.api.core.ApiClock; +import com.google.auth.CredentialTypeForMetrics; +import com.google.auth.Credentials; +import com.google.auth.RequestMetadataCallback; +import com.google.auth.oauth2.AccessToken; +import com.google.auth.oauth2.GdchCredentials; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.auth.oauth2.OAuth2Credentials; +import com.google.auth.oauth2.QuotaProjectIdProvider; +import com.google.auth.oauth2.ServiceAccountCredentials; +import com.google.cloud.NoCredentials; +import com.google.common.util.concurrent.MoreExecutors; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.data.HistogramPointData; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InterruptedIOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.net.SocketTimeoutException; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import org.jspecify.annotations.Nullable; +import org.junit.Before; +import org.junit.Test; + +public final class MetricsRecordingCredentialsTest { + + private static final URI STORAGE_URI = URI.create("https://storage.googleapis.com"); + + private InMemoryMetricReader reader; + private SdkMeterProvider provider; + private StorageClientMetrics debugMetrics; + private AtomicLong clockNanos; + private ApiClock fakeClock; + + @Before + public void setUp() { + reader = InMemoryMetricReader.create(); + provider = SdkMeterProvider.builder().registerMetricReader(reader).build(); + clockNanos = new AtomicLong(1_000_000_000L); + fakeClock = + new ApiClock() { + @Override + public long nanoTime() { + return clockNanos.get(); + } + + @Override + public long millisTime() { + return clockNanos.get() / 1_000_000L; + } + }; + debugMetrics = createMetrics(/* debug= */ true); + } + + @Test + public void wrap_guardsDelegationAndDeserialization() throws Exception { + TestGoogleCredentials delegate = new TestGoogleCredentials(); + Credentials nonGoogle = OAuth2Credentials.create(null); + GdchCredentials gdch = mock(GdchCredentials.class); + ServiceAccountCredentials unscopedSa = mock(ServiceAccountCredentials.class); + when(unscopedSa.createScopedRequired()).thenReturn(true); + + assertThat(MetricsRecordingCredentials.wrap(null, debugMetrics, fakeClock)).isNull(); + assertThat( + MetricsRecordingCredentials.wrap(NoCredentials.getInstance(), debugMetrics, fakeClock)) + .isSameInstanceAs(NoCredentials.getInstance()); + assertThat(MetricsRecordingCredentials.wrap(nonGoogle, debugMetrics, fakeClock)) + .isSameInstanceAs(nonGoogle); + assertThat(MetricsRecordingCredentials.wrap(gdch, debugMetrics, fakeClock)) + .isSameInstanceAs(gdch); + assertThat(MetricsRecordingCredentials.wrap(unscopedSa, debugMetrics, fakeClock)) + .isSameInstanceAs(unscopedSa); + assertThat(MetricsRecordingCredentials.wrap(delegate, null, fakeClock)) + .isSameInstanceAs(delegate); + assertThat( + MetricsRecordingCredentials.wrap( + delegate, createMetrics(/* debug= */ false), fakeClock)) + .isSameInstanceAs(delegate); + + GoogleCredentials wrapped = + (GoogleCredentials) MetricsRecordingCredentials.wrap(delegate, debugMetrics, fakeClock); + assertThat(wrapped).isInstanceOf(MetricsRecordingCredentials.class); + assertThat(wrapped).isInstanceOf(QuotaProjectIdProvider.class); + assertThat(MetricsRecordingCredentials.wrap(wrapped, debugMetrics, fakeClock)) + .isSameInstanceAs(wrapped); + assertThat(wrapped.getAuthenticationType()).isEqualTo("OAuth2"); + assertThat(wrapped.getUniverseDomain()).isEqualTo("custom.universe.test"); + assertThat(wrapped.getMetricsCredentialType()) + .isEqualTo(CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT); + assertThat(wrapped.getQuotaProjectId()).isEqualTo("quota-proj"); + assertThat(wrapped.hasRequestMetadata()).isTrue(); + assertThat(wrapped.hasRequestMetadataOnly()).isTrue(); + assertThat(wrapped.createScopedRequired()).isFalse(); + assertThat(wrapped.createScoped(Collections.singletonList("scope"))).isSameInstanceAs(wrapped); + + // Deserialized wrapper has null transient metrics/clock and passes through without NPE. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ObjectOutputStream oos = new ObjectOutputStream(baos)) { + oos.writeObject(wrapped); + } + try (ObjectInputStream ois = + new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) { + GoogleCredentials deserialized = (GoogleCredentials) ois.readObject(); + assertThat(deserialized.getRequestMetadata(STORAGE_URI)).containsKey("Authorization"); + AtomicInteger asyncSuccess = new AtomicInteger(); + deserialized.getRequestMetadata( + STORAGE_URI, + MoreExecutors.directExecutor(), + new RequestMetadataCallback() { + @Override + public void onSuccess(Map> metadata) { + asyncSuccess.incrementAndGet(); + } + + @Override + public void onFailure(Throwable exception) { + throw new AssertionError(exception); + } + }); + assertThat(asyncSuccess.get()).isEqualTo(1); + deserialized.refresh(); + deserialized.refreshIfExpired(); + } + assertThat(findRefreshMetric()).isNull(); + } + + @Test + public void syncAndForcedRefresh_recordsOnlyActualRefreshesAndMapsErrors() throws Exception { + TestGoogleCredentials delegate = new TestGoogleCredentials(); + delegate.onRefresh = () -> clockNanos.addAndGet(200_000_000L); + GoogleCredentials wrapped = + (GoogleCredentials) MetricsRecordingCredentials.wrap(delegate, debugMetrics, fakeClock); + + // Initial fetch refreshes (0.2s, OK); cached getRequestMetadata & refreshIfExpired skip. + assertThat(wrapped.getRequestMetadata(STORAGE_URI)).containsKey("Authorization"); + clockNanos.addAndGet(50_000_000L); + assertThat(wrapped.getRequestMetadata(STORAGE_URI)).containsKey("Authorization"); + wrapped.refreshIfExpired(); + // Explicit refresh() records once (0.2s, OK); following getRequestMetadata does not double. + wrapped.refresh(); + assertThat(wrapped.getRequestMetadata(STORAGE_URI)).containsKey("Authorization"); + + HistogramPointData okPoint = findPointByError(STATUS_OK); + assertThat(okPoint.getCount()).isEqualTo(2L); + assertThat(okPoint.getSum()).isWithin(0.0001).of(0.4); + assertThat(okPoint.getAttributes()) + .isEqualTo( + Attributes.builder() + .put(KEY_GCP_CLIENT_SERVICE, SERVICE_STORAGE) + .put(KEY_GCP_CLIENT_VERSION, StorageOptions.version()) + .put(KEY_GCP_CLIENT_ARTIFACT, ARTIFACT_STORAGE) + .put(KEY_ERROR_TYPE, STATUS_OK) + .build()); + + // Sync getRequestMetadata() and refresh() failures map TIMEOUT, CANCELLED, and AUTH_ERROR. + TestGoogleCredentials syncFail = new TestGoogleCredentials(); + syncFail.failureToThrow = new SocketTimeoutException("token endpoint timed out"); + assertThrows( + IOException.class, + () -> + MetricsRecordingCredentials.wrap(syncFail, debugMetrics, fakeClock) + .getRequestMetadata(STORAGE_URI)); + assertThat(findPointByError(STATUS_TIMEOUT).getCount()).isEqualTo(1L); + + delegate.failureToThrow = new InterruptedIOException("cancelled"); + assertThrows(IOException.class, wrapped::refresh); + assertThat(findPointByError(STATUS_CANCELLED).getCount()).isEqualTo(1L); + + delegate.failureToThrow = new IOException("invalid_grant"); + assertThrows(IOException.class, wrapped::refresh); + assertThat(findPointByError(STATUS_AUTHENTICATION_ERROR).getCount()).isEqualTo(1L); + + // mapAuthErrorType edge cases: TimeoutException, CancellationException, wrapped interrupt, + // depth bound, and cyclic cause chain. + assertThat(MetricsRecordingCredentials.mapAuthErrorType(new TimeoutException("t"))) + .isEqualTo(STATUS_TIMEOUT); + assertThat(MetricsRecordingCredentials.mapAuthErrorType(new CancellationException("c"))) + .isEqualTo(STATUS_CANCELLED); + assertThat( + MetricsRecordingCredentials.mapAuthErrorType( + new IOException("interrupted", new InterruptedException()))) + .isEqualTo(STATUS_CANCELLED); + Throwable deep = new SocketTimeoutException("deep"); + for (int i = 0; i < 25; i++) { + deep = new IOException("wrap " + i, deep); + } + assertThat(MetricsRecordingCredentials.mapAuthErrorType(deep)) + .isEqualTo(STATUS_AUTHENTICATION_ERROR); + RuntimeException cycleA = new RuntimeException("a"); + RuntimeException cycleB = new RuntimeException("b", cycleA); + cycleA.initCause(cycleB); + assertThat(MetricsRecordingCredentials.mapAuthErrorType(cycleA)) + .isEqualTo(STATUS_AUTHENTICATION_ERROR); + } + + @Test + public void asyncAndConcurrentRefresh_deduplicatesCoalescedRefreshesDeterministically() + throws Exception { + // 1) Deterministic capturing Executor: two async calls coalesce onto 1 RefreshTask. + TestGoogleCredentials delegate = new TestGoogleCredentials(); + Credentials wrapped = MetricsRecordingCredentials.wrap(delegate, debugMetrics, fakeClock); + List pendingTasks = new ArrayList<>(); + AtomicInteger completions = new AtomicInteger(); + AtomicReference callbackError = new AtomicReference<>(); + RequestMetadataCallback cb = + new RequestMetadataCallback() { + @Override + public void onSuccess(Map> metadata) { + completions.incrementAndGet(); + } + + @Override + public void onFailure(Throwable exception) { + callbackError.set(exception); + } + }; + + wrapped.getRequestMetadata(STORAGE_URI, pendingTasks::add, cb); + wrapped.getRequestMetadata(STORAGE_URI, pendingTasks::add, cb); + assertThat(pendingTasks).hasSize(1); + clockNanos.addAndGet(300_000_000L); + pendingTasks.get(0).run(); + assertThat(completions.get()).isEqualTo(2); + assertThat(callbackError.get()).isNull(); + + HistogramPointData okPoint = findPointByError(STATUS_OK); + assertThat(okPoint.getCount()).isEqualTo(1L); + assertThat(okPoint.getSum()).isWithin(0.0001).of(0.3); + + // Cached async call completes immediately without queuing or recording. + pendingTasks.clear(); + wrapped.getRequestMetadata(STORAGE_URI, pendingTasks::add, cb); + assertThat(pendingTasks).isEmpty(); + assertThat(completions.get()).isEqualTo(3); + assertThat(findPointByError(STATUS_OK).getCount()).isEqualTo(1L); + + // 2) Concurrent refresh() + async getRequestMetadata() on fresh EXPIRED creds records once. + TestGoogleCredentials coalescedDelegate = new TestGoogleCredentials(); + Credentials coalescedWrapped = + MetricsRecordingCredentials.wrap(coalescedDelegate, debugMetrics, fakeClock); + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + coalescedDelegate.onRefresh = + () -> { + entered.countDown(); + try { + release.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + clockNanos.addAndGet(100_000_000L); + }; + AtomicInteger coalescedCompletions = new AtomicInteger(); + RequestMetadataCallback coalescedCb = + new RequestMetadataCallback() { + @Override + public void onSuccess(Map> metadata) { + coalescedCompletions.incrementAndGet(); + } + + @Override + public void onFailure(Throwable exception) { + callbackError.set(exception); + } + }; + ExecutorService pool = Executors.newSingleThreadExecutor(); + try { + Future refreshFuture = + pool.submit( + () -> { + try { + coalescedWrapped.refresh(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }); + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + coalescedWrapped.getRequestMetadata(STORAGE_URI, pendingTasks::add, coalescedCb); + assertThat(pendingTasks).isEmpty(); + assertThat(coalescedCompletions.get()).isEqualTo(0); + release.countDown(); + refreshFuture.get(5, TimeUnit.SECONDS); + } finally { + pool.shutdownNow(); + } + assertThat(coalescedCompletions.get()).isEqualTo(1); + assertThat(callbackError.get()).isNull(); + assertThat(findPointByError(STATUS_OK).getCount()).isEqualTo(2L); + + // 3) Async failure records AUTHENTICATION_ERROR. + TestGoogleCredentials failing = new TestGoogleCredentials(); + failing.failureToThrow = new IOException("async auth error"); + MetricsRecordingCredentials.wrap(failing, debugMetrics, fakeClock) + .getRequestMetadata(STORAGE_URI, MoreExecutors.directExecutor(), cb); + assertThat(callbackError.get()).isInstanceOf(IOException.class); + assertThat(findPointByError(STATUS_AUTHENTICATION_ERROR).getCount()).isEqualTo(1L); + } + + private StorageClientMetrics createMetrics(boolean debug) { + return StorageOptions.http() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEnableOtelMetrics(true) + .setEnableOtelDebugMetrics(debug) + .setMeterProvider(provider) + .build() + .getStorageClientMetrics(); + } + + private @Nullable MetricData findRefreshMetric() { + return reader.collectAllMetrics().stream() + .filter(m -> m.getName().equals(METRIC_GCP_STORAGE_CLIENT_AUTH_CREDENTIAL_REFRESH_DURATION)) + .findFirst() + .orElse(null); + } + + private HistogramPointData findPointByError(String errorType) { + MetricData metric = findRefreshMetric(); + assertThat(metric).isNotNull(); + assertThat(metric.getUnit()).isEqualTo("s"); + return metric.getHistogramData().getPoints().stream() + .filter(p -> errorType.equals(p.getAttributes().get(KEY_ERROR_TYPE))) + .findFirst() + .orElseThrow(() -> new AssertionError("Missing point for error.type=" + errorType)); + } + + private static final class TestGoogleCredentials extends GoogleCredentials { + private static final long serialVersionUID = 1L; + private final AtomicInteger counter = new AtomicInteger(); + transient @Nullable Runnable onRefresh; + transient @Nullable IOException failureToThrow; + + @Override + public AccessToken refreshAccessToken() throws IOException { + if (onRefresh != null) { + onRefresh.run(); + } + if (failureToThrow != null) { + throw failureToThrow; + } + return new AccessToken( + "gtoken-" + counter.incrementAndGet(), + new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1))); + } + + @Override + public String getUniverseDomain() { + return "custom.universe.test"; + } + + @Override + public CredentialTypeForMetrics getMetricsCredentialType() { + return CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT; + } + + @Override + public String getQuotaProjectId() { + return "quota-proj"; + } + } +} diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java index e04dca92327c..30db6d7c42e9 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java @@ -775,6 +775,57 @@ public void recordStallDuration_recordsExactEightAttributesAndSkipsWhenDebugDisa .build()); } + @Test + public void recordCredentialRefreshDuration_recordsExactFourAttributesAndSkipsWhenDisabled() { + SdkMeterProvider provider = SdkMeterProvider.builder().registerMetricReader(reader).build(); + StorageClientMetrics standardMetrics = + StorageOptions.grpc() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEnableOtelMetrics(true) + .setMeterProvider(provider) + .build() + .getStorageClientMetrics(); + standardMetrics.recordCredentialRefreshDuration( + Context.current(), 0.25, StorageErrorTypeMapper.STATUS_OK); + assertThat( + findMetric( + StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_AUTH_CREDENTIAL_REFRESH_DURATION)) + .isNull(); + + StorageClientMetrics debugMetrics = + StorageOptions.grpc() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEnableOtelMetrics(true) + .setEnableOtelDebugMetrics(true) + .setMeterProvider(provider) + .build() + .getStorageClientMetrics(); + debugMetrics.recordCredentialRefreshDuration( + Context.current(), 0.25, StorageErrorTypeMapper.STATUS_OK); + + MetricData metricData = + findMetric(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_AUTH_CREDENTIAL_REFRESH_DURATION); + assertThat(metricData).isNotNull(); + assertThat(metricData.getUnit()).isEqualTo("s"); + assertThat(metricData.getHistogramData().getPoints()).hasSize(1); + HistogramPointData point = metricData.getHistogramData().getPoints().iterator().next(); + assertThat(point.getSum()).isWithin(0.0001).of(0.25); + assertThat(point.getAttributes()) + .isEqualTo( + Attributes.builder() + .put( + StorageClientMetrics.KEY_GCP_CLIENT_SERVICE, + StorageClientMetrics.SERVICE_STORAGE) + .put(StorageClientMetrics.KEY_GCP_CLIENT_VERSION, StorageOptions.version()) + .put( + StorageClientMetrics.KEY_GCP_CLIENT_ARTIFACT, + StorageClientMetrics.ARTIFACT_STORAGE) + .put(StorageClientMetrics.KEY_ERROR_TYPE, StorageErrorTypeMapper.STATUS_OK) + .build()); + } + static final class TestMetricReader implements MetricReader { private final MetricReader delegate = InMemoryMetricReader.create(); final AtomicBoolean shutdownCalled = new AtomicBoolean(false); From 26a80d40c8b9f3921f51d473fa0a8c2e5e02ce3a Mon Sep 17 00:00:00 2001 From: Nidhi Nandwani Date: Wed, 25 Nov 2026 11:16:36 +0000 Subject: [PATCH 2/3] test(storage): avoid Mockito mocks of @NullMarked credentials on Java 8 Construct real GdchCredentials and ServiceAccountCredentials instances via their builders in MetricsRecordingCredentialsTest instead of Mockito mocks. In google-auth-library 1.58.0, both classes carry JSpecify @NullMarked (whose @Target includes ElementType.MODULE), which causes ByteBuddy's annotation inspection to throw ArrayStoreException on JDK 8. [Generated-by: AI] --- .../MetricsRecordingCredentialsTest.java | 49 +++++++++++++++++-- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/MetricsRecordingCredentialsTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/MetricsRecordingCredentialsTest.java index 194a33b5c31b..1dc3a9665d78 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/MetricsRecordingCredentialsTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/MetricsRecordingCredentialsTest.java @@ -29,13 +29,12 @@ import static com.google.cloud.storage.StorageErrorTypeMapper.STATUS_TIMEOUT; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import com.google.api.core.ApiClock; import com.google.auth.CredentialTypeForMetrics; import com.google.auth.Credentials; import com.google.auth.RequestMetadataCallback; +import com.google.auth.http.HttpTransportFactory; import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.GdchCredentials; import com.google.auth.oauth2.GoogleCredentials; @@ -57,6 +56,7 @@ import java.io.ObjectOutputStream; import java.net.SocketTimeoutException; import java.net.URI; +import java.security.PrivateKey; import java.util.ArrayList; import java.util.Collections; import java.util.Date; @@ -110,9 +110,29 @@ public long millisTime() { public void wrap_guardsDelegationAndDeserialization() throws Exception { TestGoogleCredentials delegate = new TestGoogleCredentials(); Credentials nonGoogle = OAuth2Credentials.create(null); - GdchCredentials gdch = mock(GdchCredentials.class); - ServiceAccountCredentials unscopedSa = mock(ServiceAccountCredentials.class); - when(unscopedSa.createScopedRequired()).thenReturn(true); + // Construct real instances instead of Mockito mocks because JSpecify @NullMarked on + // google-auth-library classes triggers ArrayStoreException under ByteBuddy on JDK 8. + PrivateKey dummyPrivateKey = new DummyPrivateKey(); + HttpTransportFactory unusedTransportFactory = + () -> { + throw new UnsupportedOperationException("unused"); + }; + GdchCredentials gdch = + GdchCredentials.newBuilder() + .setProjectId("test-project") + .setPrivateKeyId("test-key-id") + .setPrivateKey(dummyPrivateKey) + .setServiceIdentityName("test-identity") + .setTokenServerUri(URI.create("https://sts.example.com/token")) + .setHttpTransportFactory(unusedTransportFactory) + .build(); + ServiceAccountCredentials unscopedSa = + ServiceAccountCredentials.newBuilder() + .setClientEmail("test@test-project.iam.gserviceaccount.com") + .setPrivateKey(dummyPrivateKey) + .setHttpTransportFactory(unusedTransportFactory) + .build(); + assertThat(unscopedSa.createScopedRequired()).isTrue(); assertThat(MetricsRecordingCredentials.wrap(null, debugMetrics, fakeClock)).isNull(); assertThat( @@ -412,4 +432,23 @@ public String getQuotaProjectId() { return "quota-proj"; } } + + private static final class DummyPrivateKey implements PrivateKey { + private static final long serialVersionUID = 1L; + + @Override + public String getAlgorithm() { + return "RSA"; + } + + @Override + public String getFormat() { + return "PKCS#8"; + } + + @Override + public byte[] getEncoded() { + return new byte[0]; + } + } } From accd725dea1e25f1fd786467ef99308280302192 Mon Sep 17 00:00:00 2001 From: Nidhi Nandwani Date: Thu, 26 Nov 2026 05:31:22 +0000 Subject: [PATCH 3/3] test(storage): drop duplicated credential_refresh exact-attribute unit test MetricsRecordingCredentialsTest already asserts the exact four attribute keys (no server.address or rpc.system.name) and the unit end to end. [Generated-by: AI] --- .../storage/StorageClientMetricsTest.java | 51 ------------------- 1 file changed, 51 deletions(-) diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java index eb9b4eb8e5a2..88bd2dbdf504 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java @@ -463,57 +463,6 @@ public void recordNetworkIo_skipsNonPositiveOrDisabled() { .isEqualTo(StorageClientMetrics.NETWORK_IO_DIRECTION_TRANSMIT); } - @Test - public void recordCredentialRefreshDuration_recordsExactFourAttributesAndSkipsWhenDisabled() { - SdkMeterProvider provider = SdkMeterProvider.builder().registerMetricReader(reader).build(); - StorageClientMetrics standardMetrics = - StorageOptions.grpc() - .setProjectId("test-project") - .setCredentials(NoCredentials.getInstance()) - .setEnableOtelMetrics(true) - .setMeterProvider(provider) - .build() - .getStorageClientMetrics(); - standardMetrics.recordCredentialRefreshDuration( - Context.current(), 0.25, StorageErrorTypeMapper.STATUS_OK); - assertThat( - findMetric( - StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_AUTH_CREDENTIAL_REFRESH_DURATION)) - .isNull(); - - StorageClientMetrics debugMetrics = - StorageOptions.grpc() - .setProjectId("test-project") - .setCredentials(NoCredentials.getInstance()) - .setEnableOtelMetrics(true) - .setEnableOtelDebugMetrics(true) - .setMeterProvider(provider) - .build() - .getStorageClientMetrics(); - debugMetrics.recordCredentialRefreshDuration( - Context.current(), 0.25, StorageErrorTypeMapper.STATUS_OK); - - MetricData metricData = - findMetric(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_AUTH_CREDENTIAL_REFRESH_DURATION); - assertThat(metricData).isNotNull(); - assertThat(metricData.getUnit()).isEqualTo("s"); - assertThat(metricData.getHistogramData().getPoints()).hasSize(1); - HistogramPointData point = metricData.getHistogramData().getPoints().iterator().next(); - assertThat(point.getSum()).isWithin(0.0001).of(0.25); - assertThat(point.getAttributes()) - .isEqualTo( - Attributes.builder() - .put( - StorageClientMetrics.KEY_GCP_CLIENT_SERVICE, - StorageClientMetrics.SERVICE_STORAGE) - .put(StorageClientMetrics.KEY_GCP_CLIENT_VERSION, StorageOptions.version()) - .put( - StorageClientMetrics.KEY_GCP_CLIENT_ARTIFACT, - StorageClientMetrics.ARTIFACT_STORAGE) - .put(StorageClientMetrics.KEY_ERROR_TYPE, StorageErrorTypeMapper.STATUS_OK) - .build()); - } - static final class TestMetricReader implements MetricReader { private final MetricReader delegate = InMemoryMetricReader.create(); final AtomicBoolean shutdownCalled = new AtomicBoolean(false);