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 @@ -88,6 +88,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 @@ -40,7 +40,6 @@
import com.google.api.gax.rpc.NotFoundException;
import com.google.api.gax.rpc.ResponseObserver;
import com.google.api.gax.rpc.ServerStreamingCallable;
import com.google.api.gax.rpc.StreamController;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.NoCredentials;
import com.google.cloud.WriteChannel;
Expand Down Expand Up @@ -789,8 +788,7 @@ public void call(
ReadObjectRequest request,
ResponseObserver<ReadObjectResponse> responseObserver,
ApiCallContext context) {
StreamController controller = Mockito.mock(StreamController.class);
responseObserver.onStart(controller);
responseObserver.onStart(TestUtils.nullStreamController());
responseObserver.onResponse(
ReadObjectResponse.newBuilder()
.setChecksummedData(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,25 @@
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.api.metrics.MeterProvider;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
import io.opentelemetry.sdk.metrics.data.HistogramPointData;
import io.opentelemetry.sdk.metrics.data.MetricData;
Expand All @@ -54,6 +60,7 @@
import java.io.InterruptedIOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.security.PrivateKey;
Expand Down Expand Up @@ -92,18 +99,7 @@ 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;
}
};
fakeClock = new SerializableFakeClock(clockNanos);
debugMetrics = createMetrics(/* debug= */ true);
}

Expand Down Expand Up @@ -480,6 +476,157 @@ public void onFailure(Throwable exception) {
assertThat(findPointByError(STATUS_AUTHENTICATION_ERROR).getCount()).isEqualTo(1L);
}

@Test
public void httpStorageOptions_wiresScopedCredentialsWithoutMutating() throws Exception {
SigningTestCredentials signingCreds = new SigningTestCredentials();
signingCreds.onRefresh = () -> clockNanos.addAndGet(150_000_000L);
HttpStorageOptions httpDebugOptions =
StorageOptions.http()
.setProjectId("test-project")
.setCredentials(signingCreds)
.setClock(fakeClock)
.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());
Credentials scopedDebugCreds = httpDebugOptions.getScopedCredentials();
assertThat(scopedDebugCreds).isInstanceOf(MetricsRecordingCredentials.class);
scopedDebugCreds.refresh();
HistogramPointData okPoint = findPointByError(STATUS_OK);
assertThat(okPoint.getCount()).isEqualTo(1L);
assertThat(okPoint.getSum()).isWithin(0.0001).of(0.15);
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 initializing metrics.
MeterProvider throwingMeterProvider =
name -> {
throw new AssertionError("metrics should not be initialized");
};
HttpStorageOptions httpStdOptions =
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
httpDebugOptions.toBuilder()
.setEnableOtelDebugMetrics(false)
.setMeterProvider(throwingMeterProvider)
.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 @@ -508,7 +655,7 @@ 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();
String credentialSource = "test-source";
Expand All @@ -517,6 +664,7 @@ private static final class TestGoogleCredentials extends GoogleCredentials {
transient boolean returnNewCopyOnFactory;
transient @Nullable Runnable onRefresh;
transient @Nullable IOException failureToThrow;
transient @Nullable Map<String, List<String>> extraHeaders;
transient @Nullable RuntimeException runtimeFailureToThrow;
transient @Nullable RuntimeException throwRuntimeOnAsync;

Expand All @@ -536,6 +684,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 void getRequestMetadata(
@Nullable URI uri, Executor executor, RequestMetadataCallback callback) {
Expand Down Expand Up @@ -656,4 +809,38 @@ public byte[] getEncoded() {
return new byte[0];
}
}

private static final class SerializableFakeClock implements ApiClock, Serializable {
private static final long serialVersionUID = 1L;
private final AtomicLong nanos;

SerializableFakeClock(AtomicLong nanos) {
this.nanos = nanos;
}

@Override
public long nanoTime() {
return nanos.get();
}

@Override
public long millisTime() {
return nanos.get() / 1_000_000L;
}
}

private static final class SigningTestCredentials extends TestGoogleCredentials
implements ServiceAccountSigner {
private static final long serialVersionUID = 1L;

@Override
public String getAccount() {
return "[email protected]";
}

@Override
public byte[] sign(byte[] toSign) {
return toSign;
}
}
}
Loading