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..c89e9f9c0fb0 --- /dev/null +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/MetricsRecordingCredentials.java @@ -0,0 +1,329 @@ +/* + * 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 io.opentelemetry.context.Context; +import java.io.IOException; +import java.io.ObjectInputStream; +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.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 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); + } + + @Override + public boolean equals(@Nullable Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof MetricsRecordingCredentials)) { + return false; + } + MetricsRecordingCredentials other = (MetricsRecordingCredentials) obj; + return Objects.equals(delegate, other.delegate); + } + + @Override + public int hashCode() { + return Objects.hashCode(delegate); + } + + @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 GoogleCredentials createWithQuotaProject(String quotaProject) { + return rewrap(delegate.createWithQuotaProject(quotaProject)); + } + + @Override + public GoogleCredentials createDelegated(String user) { + return rewrap(delegate.createDelegated(user)); + } + + @Override + public GoogleCredentials createWithCustomRetryStrategy(boolean defaultRetriesEnabled) { + return rewrap(delegate.createWithCustomRetryStrategy(defaultRetriesEnabled)); + } + + @Override + public Map getCredentialInfo() { + return delegate.getCredentialInfo(); + } + + @Override + public Map> getRequestMetadata(@Nullable URI uri) throws IOException { + return runRecorded(() -> delegate.getRequestMetadata(uri)); + } + + @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(); + try { + 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) { + if (shouldRecordFailure(exception)) { + record( + m, + c, + otelContext, + startNanos, + StorageErrorTypeMapper.mapAuthErrorType(exception)); + } + callback.onFailure(exception); + } + }); + } catch (RuntimeException e) { + if (shouldRecordFailure(e)) { + record(m, c, otelContext, startNanos, StorageErrorTypeMapper.mapAuthErrorType(e)); + } + throw e; + } + } + + @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 { + runRecorded( + () -> { + action.run(); + return null; + }); + } + + private T runRecorded(IoSupplier supplier) throws IOException { + StorageClientMetrics m = this.metrics; + ApiClock c = this.clock; + if (m == null || c == null) { + return supplier.get(); + } + Context otelContext = Context.current(); + AccessToken before = delegate.getAccessToken(); + long startNanos = c.nanoTime(); + try { + T result = supplier.get(); + maybeRecordTokenChange(m, c, otelContext, startNanos, before); + return result; + } catch (IOException | RuntimeException e) { + if (shouldRecordFailure(e)) { + record(m, c, otelContext, startNanos, StorageErrorTypeMapper.mapAuthErrorType(e)); + } + throw e; + } + } + + // Static non-refreshable credentials (e.g., GoogleCredentials.create(null)) throw + // IllegalStateException on probes and must not emit spurious AUTHENTICATION_ERROR metrics. + // CancellationException extends IllegalStateException and must still be recorded. + private static boolean shouldRecordFailure(Throwable t) { + return !(t instanceof IllegalStateException) || t instanceof CancellationException; + } + + @FunctionalInterface + private interface IoSupplier { + T get() throws IOException; + } + + @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 640c7a030676..95acf1420c32 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 @@ -612,6 +612,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/main/java/com/google/cloud/storage/StorageErrorTypeMapper.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageErrorTypeMapper.java index 0ad67b984c87..67fbec7ff7a1 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageErrorTypeMapper.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageErrorTypeMapper.java @@ -25,6 +25,7 @@ import io.grpc.StatusException; import io.grpc.StatusRuntimeException; import java.io.IOException; +import java.io.InterruptedIOException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.concurrent.CancellationException; @@ -143,6 +144,29 @@ static String mapThrowable(@Nullable Throwable t) { return mapThrowable(t, 0); } + 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 STATUS_TIMEOUT; + } + if (current instanceof CancellationException + || current instanceof InterruptedException + || current instanceof InterruptedIOException) { + return STATUS_CANCELLED; + } + Throwable next = current.getCause(); + if (next == current) { + break; + } + current = next; + depth++; + } + return STATUS_AUTHENTICATION_ERROR; + } + static boolean hasSocketTimeoutCause(@Nullable Throwable t) { Throwable current = t; int depth = 0; 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..accefb1af9fa --- /dev/null +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/MetricsRecordingCredentialsTest.java @@ -0,0 +1,659 @@ +/* + * 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 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; +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.security.PrivateKey; +import java.util.ArrayList; +import java.util.Collection; +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.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +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); + // 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(); + Credentials scopedSa = + unscopedSa.createScoped( + Collections.singletonList("https://www.googleapis.com/auth/devstorage.read_only")); + assertThat(((ServiceAccountCredentials) scopedSa).createScopedRequired()).isFalse(); + + 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(scopedSa, debugMetrics, fakeClock)) + .isInstanceOf(MetricsRecordingCredentials.class); + 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); + assertThat( + wrapped.createScoped( + Collections.singletonList("scope"), Collections.singletonList("defaultScope"))) + .isSameInstanceAs(wrapped); + assertThat(wrapped.getCredentialInfo()).containsEntry("Credential Source", "test-source"); + + // Copy/factory methods that return a new delegate rewrap the new instance; equals/hashCode + // delegate to the wrapped credentials. + TestGoogleCredentials equalDelegate = new TestGoogleCredentials(); + Credentials sameWrappedAgain = + MetricsRecordingCredentials.wrap(delegate, debugMetrics, fakeClock); + Credentials equalWrapped = + MetricsRecordingCredentials.wrap(equalDelegate, debugMetrics, fakeClock); + TestGoogleCredentials distinctDelegate = new TestGoogleCredentials(); + distinctDelegate.credentialSource = "other-source"; + Credentials distinctWrapped = + MetricsRecordingCredentials.wrap(distinctDelegate, debugMetrics, fakeClock); + assertThat(wrapped).isEqualTo(sameWrappedAgain); + assertThat(wrapped.hashCode()).isEqualTo(sameWrappedAgain.hashCode()); + assertThat(wrapped).isEqualTo(equalWrapped); + assertThat(wrapped.hashCode()).isEqualTo(equalWrapped.hashCode()); + assertThat(wrapped).isNotEqualTo(distinctWrapped); + assertThat(wrapped).isNotEqualTo(delegate); + assertThat(wrapped).isNotEqualTo(null); + + delegate.returnNewCopyOnFactory = true; + GoogleCredentials scopedSingle = wrapped.createScoped(Collections.singletonList("scope-a")); + assertThat(scopedSingle).isInstanceOf(MetricsRecordingCredentials.class); + assertThat(scopedSingle).isNotSameInstanceAs(wrapped); + assertThat(scopedSingle.getCredentialInfo()).containsEntry("Tag", "createScoped1:scope-a"); + + GoogleCredentials scopedDual = + wrapped.createScoped( + Collections.singletonList("scope-b"), Collections.singletonList("default-c")); + assertThat(scopedDual).isInstanceOf(MetricsRecordingCredentials.class); + assertThat(scopedDual).isNotSameInstanceAs(wrapped); + assertThat(scopedDual.getCredentialInfo()).containsEntry("Tag", "createScoped2:scope-b"); + + GoogleCredentials withQuota = wrapped.createWithQuotaProject("new-quota"); + assertThat(withQuota).isInstanceOf(MetricsRecordingCredentials.class); + assertThat(withQuota).isNotSameInstanceAs(wrapped); + assertThat(withQuota.getQuotaProjectId()).isEqualTo("new-quota"); + + GoogleCredentials delegated = wrapped.createDelegated("impersonated@example.com"); + assertThat(delegated).isInstanceOf(MetricsRecordingCredentials.class); + assertThat(delegated).isNotSameInstanceAs(wrapped); + assertThat(delegated.getCredentialInfo()) + .containsEntry("Tag", "delegated:impersonated@example.com"); + + GoogleCredentials customRetry = wrapped.createWithCustomRetryStrategy(false); + assertThat(customRetry).isInstanceOf(MetricsRecordingCredentials.class); + assertThat(customRetry).isNotSameInstanceAs(wrapped); + assertThat(customRetry.getCredentialInfo()).containsEntry("Tag", "retry:false"); + + // 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); + + // RuntimeException handling: CancellationException is recorded; IllegalStateException (such as + // static GoogleCredentials.create(null) probes) is rethrown without recording an error. + TestGoogleCredentials runtimeCancelDelegate = new TestGoogleCredentials(); + runtimeCancelDelegate.runtimeFailureToThrow = new CancellationException("cancelled sync"); + GoogleCredentials runtimeCancelWrapped = + (GoogleCredentials) + MetricsRecordingCredentials.wrap(runtimeCancelDelegate, debugMetrics, fakeClock); + assertThrows( + CancellationException.class, () -> runtimeCancelWrapped.getRequestMetadata(STORAGE_URI)); + assertThat(findPointByError(STATUS_CANCELLED).getCount()).isEqualTo(2L); + + TestGoogleCredentials asyncCancelDelegate = new TestGoogleCredentials(); + asyncCancelDelegate.throwRuntimeOnAsync = new CancellationException("cancelled async"); + GoogleCredentials asyncCancelWrapped = + (GoogleCredentials) + MetricsRecordingCredentials.wrap(asyncCancelDelegate, debugMetrics, fakeClock); + assertThrows( + CancellationException.class, + () -> + asyncCancelWrapped.getRequestMetadata( + STORAGE_URI, + MoreExecutors.directExecutor(), + new RequestMetadataCallback() { + @Override + public void onSuccess(Map> metadata) {} + + @Override + public void onFailure(Throwable exception) {} + })); + assertThat(findPointByError(STATUS_CANCELLED).getCount()).isEqualTo(3L); + + GoogleCredentials staticCreds = GoogleCredentials.create(null); + GoogleCredentials staticWrapped = + (GoogleCredentials) MetricsRecordingCredentials.wrap(staticCreds, debugMetrics, fakeClock); + assertThrows(IllegalStateException.class, staticWrapped::refresh); + assertThrows(IllegalStateException.class, () -> staticWrapped.getRequestMetadata(STORAGE_URI)); + + TestGoogleCredentials asyncIllegalStateDelegate = new TestGoogleCredentials(); + asyncIllegalStateDelegate.throwRuntimeOnAsync = new IllegalStateException("non-refreshable"); + GoogleCredentials asyncIllegalStateWrapped = + (GoogleCredentials) + MetricsRecordingCredentials.wrap(asyncIllegalStateDelegate, debugMetrics, fakeClock); + assertThrows( + IllegalStateException.class, + () -> + asyncIllegalStateWrapped.getRequestMetadata( + STORAGE_URI, + MoreExecutors.directExecutor(), + new RequestMetadataCallback() { + @Override + public void onSuccess(Map> metadata) {} + + @Override + public void onFailure(Throwable exception) {} + })); + assertThat(findPointByError(STATUS_AUTHENTICATION_ERROR).getCount()).isEqualTo(1L); + } + + @Test + public void refreshIfExpired_onUninitializedOrExpiredCredential_recordsDurationWithOk() + throws Exception { + TestGoogleCredentials delegate = new TestGoogleCredentials(); + delegate.onRefresh = () -> clockNanos.addAndGet(150_000_000L); + GoogleCredentials wrapped = + (GoogleCredentials) MetricsRecordingCredentials.wrap(delegate, debugMetrics, fakeClock); + + wrapped.refreshIfExpired(); + + HistogramPointData okPoint = findPointByError(STATUS_OK); + assertThat(okPoint.getCount()).isEqualTo(1L); + assertThat(okPoint.getSum()).isWithin(0.0001).of(0.15); + } + + @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(); + String credentialSource = "test-source"; + String quotaProjectId = "quota-proj"; + @Nullable String tag; + transient boolean returnNewCopyOnFactory; + transient @Nullable Runnable onRefresh; + transient @Nullable IOException failureToThrow; + transient @Nullable RuntimeException runtimeFailureToThrow; + transient @Nullable RuntimeException throwRuntimeOnAsync; + + @Override + public AccessToken refreshAccessToken() throws IOException { + if (onRefresh != null) { + onRefresh.run(); + } + if (runtimeFailureToThrow != null) { + throw runtimeFailureToThrow; + } + if (failureToThrow != null) { + throw failureToThrow; + } + return new AccessToken( + "gtoken-" + counter.incrementAndGet(), + new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1))); + } + + @Override + public void getRequestMetadata( + @Nullable URI uri, Executor executor, RequestMetadataCallback callback) { + if (throwRuntimeOnAsync != null) { + throw throwRuntimeOnAsync; + } + super.getRequestMetadata(uri, executor, callback); + } + + @Override + public String getUniverseDomain() { + return "custom.universe.test"; + } + + @Override + public CredentialTypeForMetrics getMetricsCredentialType() { + return CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT; + } + + @Override + public String getQuotaProjectId() { + return quotaProjectId; + } + + @Override + public GoogleCredentials createScoped(Collection scopes) { + if (!returnNewCopyOnFactory) { + return this; + } + return copyWithTag("createScoped1:" + String.join(",", scopes)); + } + + @Override + public GoogleCredentials createScoped( + Collection scopes, Collection defaultScopes) { + if (!returnNewCopyOnFactory) { + return this; + } + return copyWithTag("createScoped2:" + String.join(",", scopes)); + } + + @Override + public GoogleCredentials createWithQuotaProject(String quotaProject) { + if (!returnNewCopyOnFactory) { + return this; + } + TestGoogleCredentials copy = copyWithTag("quota:" + quotaProject); + copy.quotaProjectId = quotaProject; + return copy; + } + + @Override + public GoogleCredentials createDelegated(String user) { + if (!returnNewCopyOnFactory) { + return this; + } + return copyWithTag("delegated:" + user); + } + + @Override + public GoogleCredentials createWithCustomRetryStrategy(boolean defaultRetriesEnabled) { + if (!returnNewCopyOnFactory) { + return this; + } + return copyWithTag("retry:" + defaultRetriesEnabled); + } + + @Override + public Map getCredentialInfo() { + Map info = new java.util.HashMap<>(); + info.put("Credential Source", credentialSource); + if (tag != null) { + info.put("Tag", tag); + } + return Collections.unmodifiableMap(info); + } + + @Override + public boolean equals(@Nullable Object obj) { + if (!(obj instanceof TestGoogleCredentials)) { + return false; + } + TestGoogleCredentials other = (TestGoogleCredentials) obj; + return java.util.Objects.equals(credentialSource, other.credentialSource) + && java.util.Objects.equals(quotaProjectId, other.quotaProjectId) + && java.util.Objects.equals(tag, other.tag); + } + + @Override + public int hashCode() { + return java.util.Objects.hash(credentialSource, quotaProjectId, tag); + } + + private TestGoogleCredentials copyWithTag(String newTag) { + TestGoogleCredentials copy = new TestGoogleCredentials(); + copy.credentialSource = credentialSource; + copy.quotaProjectId = quotaProjectId; + copy.tag = newTag; + return copy; + } + } + + 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]; + } + } +} diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageErrorTypeMapperTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageErrorTypeMapperTest.java index d28c1a520d16..dd73ae6a983e 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageErrorTypeMapperTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageErrorTypeMapperTest.java @@ -33,6 +33,7 @@ import io.grpc.StatusRuntimeException; import java.io.EOFException; import java.io.IOException; +import java.io.InterruptedIOException; import java.lang.reflect.Constructor; import java.net.ConnectException; import java.net.SocketException; @@ -763,6 +764,39 @@ public void hasSocketTimeoutCause_detectsAndBoundsDepth() { assertThat(StorageErrorTypeMapper.hasSocketTimeoutCause(cycleA)).isFalse(); } + @Test + public void mapAuthErrorType_mapsTimeoutsCancellationsAndGuardsCauseChain() { + assertThat(StorageErrorTypeMapper.mapAuthErrorType(new SocketTimeoutException("t"))) + .isEqualTo(StorageErrorTypeMapper.STATUS_TIMEOUT); + assertThat(StorageErrorTypeMapper.mapAuthErrorType(new TimeoutException("t"))) + .isEqualTo(StorageErrorTypeMapper.STATUS_TIMEOUT); + assertThat(StorageErrorTypeMapper.mapAuthErrorType(new InterruptedIOException("c"))) + .isEqualTo(StorageErrorTypeMapper.STATUS_CANCELLED); + assertThat(StorageErrorTypeMapper.mapAuthErrorType(new CancellationException("c"))) + .isEqualTo(StorageErrorTypeMapper.STATUS_CANCELLED); + assertThat( + StorageErrorTypeMapper.mapAuthErrorType( + new IOException("interrupted", new InterruptedException()))) + .isEqualTo(StorageErrorTypeMapper.STATUS_CANCELLED); + assertThat(StorageErrorTypeMapper.mapAuthErrorType(new IOException("invalid_grant"))) + .isEqualTo(StorageErrorTypeMapper.STATUS_AUTHENTICATION_ERROR); + assertThat(StorageErrorTypeMapper.mapAuthErrorType(null)) + .isEqualTo(StorageErrorTypeMapper.STATUS_AUTHENTICATION_ERROR); + + Throwable deep = new SocketTimeoutException("deep"); + for (int i = 0; i < 25; i++) { + deep = new IOException("wrap " + i, deep); + } + assertThat(StorageErrorTypeMapper.mapAuthErrorType(deep)) + .isEqualTo(StorageErrorTypeMapper.STATUS_AUTHENTICATION_ERROR); + + RuntimeException cycleA = new RuntimeException("a"); + RuntimeException cycleB = new RuntimeException("b", cycleA); + cycleA.initCause(cycleB); + assertThat(StorageErrorTypeMapper.mapAuthErrorType(cycleA)) + .isEqualTo(StorageErrorTypeMapper.STATUS_AUTHENTICATION_ERROR); + } + private static WatchdogTimeoutException createWatchdogTimeoutException() throws Exception { Constructor ctor = WatchdogTimeoutException.class.getDeclaredConstructor(String.class, boolean.class);