diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/GrpcStorageOptions.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/GrpcStorageOptions.java index 514fc77fb8f1..cdc0fc15aebf 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/GrpcStorageOptions.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/GrpcStorageOptions.java @@ -49,6 +49,7 @@ import com.google.api.gax.tracing.ApiTracerFactory; import com.google.api.pathtemplate.PathTemplate; import com.google.auth.Credentials; +import com.google.auth.oauth2.ComputeEngineCredentials; import com.google.cloud.NoCredentials; import com.google.cloud.ServiceFactory; import com.google.cloud.ServiceOptions; @@ -254,10 +255,18 @@ private Tuple> resolveSettingsAndOpts() throw if (credentials instanceof NoCredentials) { credentialsProvider = NoCredentialsProvider.create(); } else { + // Keep ComputeEngineCredentials unwrapped on gRPC so InstantiatingGrpcChannelProvider + // preserves DirectPath ALTS hard-bound tokens and EndpointContext skips unnecessary MDS + // universe domain lookups. + Credentials effectiveCredentials = + !isEnableOtelDebugMetrics() || credentials instanceof ComputeEngineCredentials + ? credentials + : MetricsRecordingCredentials.wrap( + credentials, getStorageClientMetrics(), getClock()); boolean foundQuotaProject = false; - if (credentials.hasRequestMetadata()) { + if (effectiveCredentials.hasRequestMetadata()) { try { - Map> requestMetadata = credentials.getRequestMetadata(uri); + Map> requestMetadata = effectiveCredentials.getRequestMetadata(uri); for (Entry> e : requestMetadata.entrySet()) { String key = e.getKey(); if ("x-goog-user-project".equals(Utils.headerNameToLowerCase(key.trim()))) { @@ -282,9 +291,10 @@ private Tuple> resolveSettingsAndOpts() throw if (foundQuotaProject) { // fix for https://github.com/googleapis/java-storage/issues/1736 credentialsProvider = - FixedCredentialsProvider.create(new QuotaProjectIdHidingCredentials(credentials)); + FixedCredentialsProvider.create( + new QuotaProjectIdHidingCredentials(effectiveCredentials)); } else { - credentialsProvider = FixedCredentialsProvider.create(credentials); + credentialsProvider = FixedCredentialsProvider.create(effectiveCredentials); } } diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/HttpStorageOptions.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/HttpStorageOptions.java index 8dff1c8185c1..97fc9ca2e7bd 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/HttpStorageOptions.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/HttpStorageOptions.java @@ -86,6 +86,16 @@ protected Set getScopes() { return SCOPES; } + @Override + public Credentials getScopedCredentials() { + Credentials scopedCredentials = super.getScopedCredentials(); + if (!isEnableOtelDebugMetrics()) { + return scopedCredentials; + } + return MetricsRecordingCredentials.wrap( + scopedCredentials, getStorageClientMetrics(), getClock()); + } + @InternalApi HttpRetryAlgorithmManager getRetryAlgorithmManager() { return retryAlgorithmManager; 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 1dc3a9665d78..81530b9e2780 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 @@ -31,17 +31,22 @@ import static org.junit.Assert.assertThrows; import com.google.api.core.ApiClock; +import com.google.api.gax.rpc.internal.QuotaProjectIdHidingCredentials; import com.google.auth.CredentialTypeForMetrics; import com.google.auth.Credentials; import com.google.auth.RequestMetadataCallback; +import com.google.auth.ServiceAccountSigner; import com.google.auth.http.HttpTransportFactory; import com.google.auth.oauth2.AccessToken; +import com.google.auth.oauth2.ComputeEngineCredentials; 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.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.MoreExecutors; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.sdk.metrics.SdkMeterProvider; @@ -370,6 +375,144 @@ public void onFailure(Throwable exception) { assertThat(findPointByError(STATUS_AUTHENTICATION_ERROR).getCount()).isEqualTo(1L); } + @Test + public void httpStorageOptions_wiresScopedCredentialsWithoutMutating() throws Exception { + SigningTestCredentials signingCreds = new SigningTestCredentials(); + HttpStorageOptions httpDebugOptions = + StorageOptions.http() + .setProjectId("test-project") + .setCredentials(signingCreds) + .setEnableOtelMetrics(true) + .setEnableOtelDebugMetrics(true) + .setMeterProvider(provider) + .build(); + HttpStorageOptions httpDebugOptionsCopy = httpDebugOptions.toBuilder().build(); + + // getCredentials() stays untouched (ServiceAccountSigner, equals, hashCode, Serializable). + assertThat(httpDebugOptions.getCredentials()).isSameInstanceAs(signingCreds); + assertThat(httpDebugOptions.getCredentials()).isInstanceOf(ServiceAccountSigner.class); + assertThat(httpDebugOptions).isEqualTo(httpDebugOptionsCopy); + assertThat(httpDebugOptions.hashCode()).isEqualTo(httpDebugOptionsCopy.hashCode()); + assertThat(httpDebugOptions.getScopedCredentials()) + .isInstanceOf(MetricsRecordingCredentials.class); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ObjectOutputStream oos = new ObjectOutputStream(baos)) { + oos.writeObject(httpDebugOptions); + } + try (ObjectInputStream ois = + new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) { + HttpStorageOptions deserializedOptions = (HttpStorageOptions) ois.readObject(); + assertThat(deserializedOptions.getCredentials()).isInstanceOf(ServiceAccountSigner.class); + } + + // HTTP safely wraps ComputeEngineCredentials when debug metrics are enabled. + ComputeEngineCredentials computeCreds = ComputeEngineCredentials.create(); + HttpStorageOptions httpComputeOptions = + StorageOptions.http() + .setProjectId("test-project") + .setCredentials(computeCreds) + .setEnableOtelMetrics(true) + .setEnableOtelDebugMetrics(true) + .setMeterProvider(provider) + .build(); + assertThat(httpComputeOptions.getScopedCredentials()) + .isInstanceOf(MetricsRecordingCredentials.class); + + // Toggling debug off via toBuilder() yields unwrapped credentials without leaking a wrapper. + HttpStorageOptions httpStdOptions = + httpDebugOptions.toBuilder().setEnableOtelDebugMetrics(false).build(); + assertThat(httpStdOptions.getScopedCredentials()).isSameInstanceAs(signingCreds); + } + + @Test + public void grpcStorageOptions_wiresCredentialsWithoutMutating() throws Exception { + // 1) GoogleCredentials.create(null) is wrapped by MetricsRecordingCredentials and throws + // IllegalStateException during the quota-project probe; must not emit a spurious error. + GrpcStorageOptions nullTokenOptions = + StorageOptions.grpc() + .setProjectId("test-project") + .setCredentials(GoogleCredentials.create(/* accessToken= */ null)) + .setClock(fakeClock) + .setEnableOtelMetrics(true) + .setEnableOtelDebugMetrics(true) + .setMeterProvider(provider) + .build(); + assertThat(nullTokenOptions.getStorageSettings().getCredentialsProvider().getCredentials()) + .isInstanceOf(MetricsRecordingCredentials.class); + assertThat(findRefreshMetric()).isNull(); + + // 2) With x-goog-user-project: probe records refresh, preserves getCredentials(), and wraps + // QuotaProjectIdHidingCredentials around MetricsRecordingCredentials. + TestGoogleCredentials grpcCreds = new TestGoogleCredentials(); + grpcCreds.extraHeaders = ImmutableMap.of("x-goog-user-project", ImmutableList.of("quota-proj")); + grpcCreds.onRefresh = () -> clockNanos.addAndGet(150_000_000L); + GrpcStorageOptions grpcDebugOptions = + StorageOptions.grpc() + .setProjectId("test-project") + .setCredentials(grpcCreds) + .setClock(fakeClock) + .setEnableOtelMetrics(true) + .setEnableOtelDebugMetrics(true) + .setMeterProvider(provider) + .build(); + assertThat(grpcDebugOptions.getCredentials()).isSameInstanceAs(grpcCreds); + Credentials providerCreds = + grpcDebugOptions.getStorageSettings().getCredentialsProvider().getCredentials(); + assertThat(providerCreds).isInstanceOf(QuotaProjectIdHidingCredentials.class); + assertThat(providerCreds.getRequestMetadata(STORAGE_URI)) + .doesNotContainKey("x-goog-user-project"); + HistogramPointData okPoint = findPointByError(STATUS_OK); + assertThat(okPoint.getCount()).isEqualTo(1L); + assertThat(okPoint.getSum()).isWithin(0.0001).of(0.15); + providerCreds.refresh(); + assertThat(findPointByError(STATUS_OK).getCount()).isEqualTo(2L); + + // 3) Without x-goog-user-project: direct MetricsRecordingCredentials when debug enabled, and + // unwrapped passthrough when debug toggled off via toBuilder(). + TestGoogleCredentials noQuotaCreds = new TestGoogleCredentials(); + GrpcStorageOptions grpcNoQuotaDebug = + StorageOptions.grpc() + .setProjectId("test-project") + .setCredentials(noQuotaCreds) + .setClock(fakeClock) + .setEnableOtelMetrics(true) + .setEnableOtelDebugMetrics(true) + .setMeterProvider(provider) + .build(); + assertThat(grpcNoQuotaDebug.getStorageSettings().getCredentialsProvider().getCredentials()) + .isInstanceOf(MetricsRecordingCredentials.class); + GrpcStorageOptions grpcNoQuotaStd = + grpcNoQuotaDebug.toBuilder().setEnableOtelDebugMetrics(false).build(); + assertThat(grpcNoQuotaStd.getStorageSettings().getCredentialsProvider().getCredentials()) + .isSameInstanceAs(noQuotaCreds); + + // 4) gRPC keeps ComputeEngineCredentials unwrapped for DirectPath ALTS hard-bound tokens. + // Construct a real instance with a fresh AccessToken instead of a Mockito mock because + // JSpecify @NullMarked on google-auth-library classes triggers ArrayStoreException under + // ByteBuddy on JDK 8. + ComputeEngineCredentials.Builder computeBuilder = + ComputeEngineCredentials.newBuilder() + .setUniverseDomain("googleapis.com") + .setHttpTransportFactory( + () -> { + throw new UnsupportedOperationException("unused"); + }); + computeBuilder.setAccessToken( + new AccessToken( + "compute-token", new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)))); + ComputeEngineCredentials computeCreds = computeBuilder.build(); + GrpcStorageOptions grpcComputeOptions = + StorageOptions.grpc() + .setProjectId("test-project") + .setCredentials(computeCreds) + .setEnableOtelMetrics(true) + .setEnableOtelDebugMetrics(true) + .setMeterProvider(provider) + .build(); + assertThat(grpcComputeOptions.getStorageSettings().getCredentialsProvider().getCredentials()) + .isSameInstanceAs(computeCreds); + } + private StorageClientMetrics createMetrics(boolean debug) { return StorageOptions.http() .setProjectId("test-project") @@ -398,11 +541,12 @@ private HistogramPointData findPointByError(String errorType) { .orElseThrow(() -> new AssertionError("Missing point for error.type=" + errorType)); } - private static final class TestGoogleCredentials extends GoogleCredentials { + private static class TestGoogleCredentials extends GoogleCredentials { private static final long serialVersionUID = 1L; private final AtomicInteger counter = new AtomicInteger(); transient @Nullable Runnable onRefresh; transient @Nullable IOException failureToThrow; + transient @Nullable Map> extraHeaders; @Override public AccessToken refreshAccessToken() throws IOException { @@ -417,6 +561,11 @@ public AccessToken refreshAccessToken() throws IOException { new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1))); } + @Override + protected Map> getAdditionalHeaders() { + return extraHeaders != null ? extraHeaders : ImmutableMap.of(); + } + @Override public String getUniverseDomain() { return "custom.universe.test"; @@ -451,4 +600,19 @@ public byte[] getEncoded() { return new byte[0]; } } + + private static final class SigningTestCredentials extends TestGoogleCredentials + implements ServiceAccountSigner { + private static final long serialVersionUID = 1L; + + @Override + public String getAccount() { + return "sa@test-project.iam.gserviceaccount.com"; + } + + @Override + public byte[] sign(byte[] toSign) { + return toSign; + } + } }