Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -254,10 +255,18 @@ private Tuple<StorageSettings, Opts<UserProject>> 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());
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
boolean foundQuotaProject = false;
if (credentials.hasRequestMetadata()) {
if (effectiveCredentials.hasRequestMetadata()) {
try {
Map<String, List<String>> requestMetadata = credentials.getRequestMetadata(uri);
Map<String, List<String>> requestMetadata = effectiveCredentials.getRequestMetadata(uri);
for (Entry<String, List<String>> e : requestMetadata.entrySet()) {
String key = e.getKey();
if ("x-goog-user-project".equals(Utils.headerNameToLowerCase(key.trim()))) {
Expand All @@ -282,9 +291,10 @@ private Tuple<StorageSettings, Opts<UserProject>> 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);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@ protected Set<String> getScopes() {
return SCOPES;
}

@Override
public Credentials getScopedCredentials() {
Credentials scopedCredentials = super.getScopedCredentials();
if (!isEnableOtelDebugMetrics()) {
return scopedCredentials;
}
return MetricsRecordingCredentials.wrap(
scopedCredentials, getStorageClientMetrics(), getClock());
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
}

@InternalApi
HttpRetryAlgorithmManager getRetryAlgorithmManager() {
return retryAlgorithmManager;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Can we also set fakeClock and trigger a refresh on httpDebugOptions.getScopedCredentials() here to verify the duration metric is recorded end-to-end?

.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 =

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: To verify that getScopedCredentials() does not initialize metrics when debug metrics are off, could we pass a MeterProvider that throws on meterBuilder here?

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")
Expand Down Expand Up @@ -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<String, List<String>> extraHeaders;

@Override
public AccessToken refreshAccessToken() throws IOException {
Expand All @@ -417,6 +561,11 @@ public AccessToken refreshAccessToken() throws IOException {
new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)));
}

@Override
protected Map<String, List<String>> getAdditionalHeaders() {
return extraHeaders != null ? extraHeaders : ImmutableMap.of();
}

@Override
public String getUniverseDomain() {
return "custom.universe.test";
Expand Down Expand Up @@ -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;
}
}
}
Loading