Skip to content
4 changes: 4 additions & 0 deletions java-storage/google-cloud-storage/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@
<groupId>com.google.api</groupId>
<artifactId>gax-grpc</artifactId>
</dependency>
<dependency>
<groupId>com.google.api</groupId>
<artifactId>gax-httpjson</artifactId>
</dependency>
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-credentials</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -854,9 +854,10 @@ public GrpcStorageOptions.Builder setMetricInterval(Duration metricInterval) {
@Override
public GrpcStorageOptions build() {
GrpcStorageOptions options = new GrpcStorageOptions(this, defaults());
String resolvedUniverseDomain = options.getResolvedUniverseDomain();
// TODO: Remove when https://github.com/googleapis/sdk-platform-java/issues/2911 is resolved
if (options.getUniverseDomain() != null) {
this.setHost("https://storage." + options.getUniverseDomain());
this.setHost("https://storage." + resolvedUniverseDomain);
return new GrpcStorageOptions(this, defaults());
}
return options;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@
@TransportCompatibility(Transport.HTTP)
// non-final because of mocking frameworks
public class HttpStorageOptions extends StorageOptions {
/** The {@code ServiceOptions} default host, which maps to the storage host. */
private static final String SERVICE_OPTIONS_DEFAULT_HOST = "https://www.googleapis.com";

private static final long serialVersionUID = -5302637952911052045L;
private static final String API_SHORT_NAME = "Storage";
Expand Down Expand Up @@ -112,9 +114,7 @@ public HttpStorageOptions.Builder toBuilder() {

@Override
boolean usesDefaultHost() {
String universeDomain =
MoreObjects.firstNonNull(getUniverseDomain(), Credentials.GOOGLE_DEFAULT_UNIVERSE);
return getHost().equals("https://storage." + universeDomain + "/");
return getHost().equals("https://storage." + getResolvedUniverseDomain() + "/");
}

@Override
Expand Down Expand Up @@ -313,21 +313,18 @@ public HttpStorageOptions.Builder setApiTracerFactory(ApiTracerFactory apiTracer

@Override
public HttpStorageOptions build() {
if (!isHostManuallySet()) {
// Resolve the default host from the current universe domain on every build.
setResolvedHostInternal(null);
}
HttpStorageOptions options = new HttpStorageOptions(this, defaults());

// todo: In the future, this step will be done automatically, and the getResolvedApiaryHost
// helper method will
// be removed. When that happens, delete the following block.
// https://github.com/googleapis/google-api-java-client-services/issues/19286
if (options.getHost() != null) {
setResolvedHostInternal(options.getResolvedApiaryHost("storage"));
return new HttpStorageOptions(this, defaults());
String universeDomain =
MoreObjects.firstNonNull(
resolveBuilderUniverseDomain(), Credentials.GOOGLE_DEFAULT_UNIVERSE);
if (isHostManuallySet()) {
HttpStorageOptions options = new HttpStorageOptions(this, defaults());
// The ServiceOptions default host maps to the storage host for the universe domain.
if (!SERVICE_OPTIONS_DEFAULT_HOST.equals(options.getHost())) {
return options;
}
}
return options;
setResolvedHostInternal("https://storage." + universeDomain + "/");
return new HttpStorageOptions(this, defaults());
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ static StorageClientMetrics fromOptions(StorageOptions options) {
OpenTelemetryBootstrappingUtils.createDefaultClientMeterProvider(
options.getHost(),
options.getProjectId(),
options.getUniverseDomain(),
options.getConfiguredUniverseDomain(),
options.getCredentials(),
options.getMetricInterval(),
options instanceof GrpcStorageOptions ? "grpc" : "json");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,20 @@

import com.google.api.client.util.Data;
import com.google.api.core.ApiFuture;
import com.google.api.gax.httpjson.HttpJsonStatusCode;
import com.google.api.gax.paging.Page;
import com.google.api.gax.retrying.BasicResultRetryAlgorithm;
import com.google.api.gax.retrying.ResultRetryAlgorithm;
import com.google.api.gax.rpc.EndpointContext;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.UnauthenticatedException;
import com.google.api.services.storage.model.BucketAccessControl;
import com.google.api.services.storage.model.ObjectAccessControl;
import com.google.api.services.storage.model.StorageObject;
import com.google.auth.Credentials;
import com.google.auth.ServiceAccountSigner;
import com.google.auth.oauth2.ComputeEngineCredentials;
import com.google.auth.oauth2.GdchCredentials;
import com.google.cloud.BaseService;
import com.google.cloud.BatchResult;
import com.google.cloud.PageImpl;
Expand Down Expand Up @@ -87,6 +94,7 @@
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
Expand Down Expand Up @@ -890,6 +898,7 @@ public URL signUrl(BlobInfo blobInfo, long duration, TimeUnit unit, SignUrlOptio
"Signing key was not provided and could not be derived");
credentials = (ServiceAccountSigner) this.getOptions().getCredentials();
}
validateSigningCredentialsUniverseDomain(credentials);

long expiration =
isV4
Expand Down Expand Up @@ -997,6 +1006,7 @@ public PostPolicyV4 generateSignedPostPolicyV4(
"Signing key was not provided and could not be derived");
credentials = (ServiceAccountSigner) this.getOptions().getCredentials();
}
validateSigningCredentialsUniverseDomain(credentials);

checkArgument(
!(optionMap.containsKey(SignUrlOption.Option.VIRTUAL_HOSTED_STYLE)
Expand Down Expand Up @@ -1106,6 +1116,39 @@ public PostPolicyV4 generateSignedPostPolicyV4(
blobInfo, duration, unit, PostFieldsV4.newBuilder().build(), options);
}

private void validateSigningCredentialsUniverseDomain(ServiceAccountSigner signer) {
if (!(signer instanceof Credentials)
|| signer instanceof GdchCredentials
|| signer instanceof ComputeEngineCredentials) {
return;
}
Credentials credentialsToValidate = (Credentials) signer;
String credentialsUniverseDomain;
try {
credentialsUniverseDomain =
firstNonNull(
credentialsToValidate.getUniverseDomain(), Credentials.GOOGLE_DEFAULT_UNIVERSE);
} catch (IOException e) {
throw unauthenticated(EndpointContext.UNABLE_TO_RETRIEVE_CREDENTIALS_ERROR_MESSAGE, e);
}
String configuredUniverseDomain = getOptions().getResolvedUniverseDomain();
if (!configuredUniverseDomain.equals(credentialsUniverseDomain)) {
String errorMessage =
String.format(
EndpointContext.INVALID_UNIVERSE_DOMAIN_ERROR_TEMPLATE,
configuredUniverseDomain,
credentialsUniverseDomain);
throw unauthenticated(errorMessage, new Throwable(errorMessage));
}
}

private static StorageException unauthenticated(String message, Throwable cause) {
UnauthenticatedException unauthenticatedException =
new UnauthenticatedException(
message, cause, HttpJsonStatusCode.of(StatusCode.Code.UNAUTHENTICATED), false);
return new StorageException(401, message, unauthenticatedException);
}

private String constructResourceUriPath(
String slashlessBucketName,
String escapedBlobName,
Expand Down Expand Up @@ -1202,27 +1245,26 @@ private SignatureInfo buildSignatureInfo(

signatureInfoBuilder.setTimestamp(getOptions().getClock().millisTime());

ImmutableMap.Builder<String, String> extHeadersBuilder = new ImmutableMap.Builder<>();
Map<String, String> extHeaders = new LinkedHashMap<>();

boolean isV4 =
SignUrlOption.SignatureVersion.V4.equals(
optionMap.get(SignUrlOption.Option.SIGNATURE_VERSION));
if (isV4) { // We don't sign the host header for V2 signed URLs; only do this for V4.
// Add the host here first, allowing it to be overridden in the EXT_HEADERS option below.
if (optionMap.containsKey(SignUrlOption.Option.VIRTUAL_HOSTED_STYLE)) {
extHeadersBuilder.put(
extHeaders.put(
"host",
slashlessBucketNameFromBlobInfo(blobInfo) + "." + getBaseStorageHostName(optionMap));
} else if (optionMap.containsKey(SignUrlOption.Option.HOST_NAME)
|| optionMap.containsKey(SignUrlOption.Option.BUCKET_BOUND_HOST_NAME)
|| getOptions().getUniverseDomain() != null) {
extHeadersBuilder.put("host", getBaseStorageHostName(optionMap));
|| getOptions().getConfiguredUniverseDomain() != null) {
extHeaders.put("host", getBaseStorageHostName(optionMap));
}
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
}

if (optionMap.containsKey(SignUrlOption.Option.EXT_HEADERS)) {
extHeadersBuilder.putAll(
(Map<String, String>) optionMap.get(SignUrlOption.Option.EXT_HEADERS));
extHeaders.putAll((Map<String, String>) optionMap.get(SignUrlOption.Option.EXT_HEADERS));
}

ImmutableMap.Builder<String, String> queryParamsBuilder = new ImmutableMap.Builder<>();
Expand All @@ -1232,7 +1274,7 @@ private SignatureInfo buildSignatureInfo(
}

return signatureInfoBuilder
.setCanonicalizedExtensionHeaders(extHeadersBuilder.build())
.setCanonicalizedExtensionHeaders(ImmutableMap.copyOf(extHeaders))
.setCanonicalizedQueryParams(queryParamsBuilder.build())
.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

import com.google.api.core.BetaApi;
import com.google.api.core.InternalApi;
import com.google.api.gax.rpc.EndpointContext;
import com.google.auth.Credentials;
import com.google.cloud.NoCredentials;
import com.google.cloud.ServiceDefaults;
import com.google.cloud.ServiceOptions;
Expand All @@ -34,6 +36,8 @@
import com.google.cloud.storage.Storage.BlobWriteOption;
import com.google.cloud.storage.TransportCompatibility.Transport;
import com.google.cloud.storage.spi.StorageRpcFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.metrics.MeterProvider;
import java.io.IOException;
Expand All @@ -42,6 +46,7 @@
import java.time.Duration;
import java.util.Locale;
import java.util.Properties;
import java.util.function.Function;
import java.util.logging.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
Expand All @@ -50,6 +55,7 @@ public abstract class StorageOptions extends ServiceOptions<Storage, StorageOpti

private static final long serialVersionUID = -7295846567928013233L;
private static final String VERSION;
private static volatile Function<String, String> envResolver = System::getenv;

static {
String tmp = "unresolved";
Expand Down Expand Up @@ -127,6 +133,7 @@ public abstract static class Builder
private boolean customOpenTelemetryConfigured = false;
private boolean customMeterProviderConfigured = false;
private boolean hostManuallySet = false;
private @Nullable String explicitUniverseDomain = null;

Builder() {
setUseJwtAccessWithScope(false);
Expand All @@ -135,6 +142,7 @@ public abstract static class Builder
Builder(StorageOptions options) {
super(options);
this.hostManuallySet = !options.usesDefaultHost();
this.explicitUniverseDomain = options.getUniverseDomain();
this.enableOtelMetrics = options.getRawEnableOtelMetrics();
this.enableOtelDebugMetrics = options.getRawEnableOtelDebugMetrics();
this.meterProvider = options.getMeterProvider();
Expand All @@ -149,6 +157,13 @@ public Builder setHost(String host) {
return super.setHost(host);
}

@Override
public Builder setUniverseDomain(String universeDomain) {
super.setUniverseDomain(universeDomain);
this.explicitUniverseDomain = universeDomain;
return this;
}

/** Whether the host was set with {@link #setHost(String)}. */
boolean isHostManuallySet() {
return hostManuallySet;
Expand All @@ -159,6 +174,11 @@ Builder setResolvedHostInternal(@Nullable String host) {
return super.setHost(host);
}

/** The universe domain set on this builder, or else the configured one, if any. */
@Nullable String resolveBuilderUniverseDomain() {
return StorageOptions.resolveConfiguredUniverseDomain(explicitUniverseDomain);
}

@Nullable Boolean getEnableOtelMetrics() {
return enableOtelMetrics;
}
Expand Down Expand Up @@ -310,9 +330,51 @@ public StorageOptions.Builder setMetricInterval(Duration metricInterval) {
}
}

@VisibleForTesting
static void setEnvResolverForTesting(Function<String, String> testEnv) {
envResolver = testEnv != null ? testEnv : System::getenv;
}

@VisibleForTesting
static void resetEnvResolverForTesting() {
envResolver = System::getenv;
}

/**
* Returns the explicitly configured or environment universe domain, or {@code null} if unset.
*
* @throws IllegalArgumentException if the resolved universe domain is empty
*/
private static @Nullable String resolveConfiguredUniverseDomain(
@Nullable String explicitUniverseDomain) {
String resolved =
explicitUniverseDomain != null
? explicitUniverseDomain
: envResolver.apply(EndpointContext.GOOGLE_CLOUD_UNIVERSE_DOMAIN);
if (resolved != null && resolved.isEmpty()) {
throw new IllegalArgumentException("The universe domain cannot be empty");
}
return resolved;
}

@Nullable String getConfiguredUniverseDomain() {
return resolveConfiguredUniverseDomain(getUniverseDomain());
}

@NonNull String getResolvedUniverseDomain() {
return MoreObjects.firstNonNull(
getConfiguredUniverseDomain(), Credentials.GOOGLE_DEFAULT_UNIVERSE);
}

@Override
@InternalApi
public String resolveUniverseDomain() {
return getResolvedUniverseDomain();
}

/**
* Whether {@link #getHost()} is the host this transport derives from {@link #getUniverseDomain()}
* when no host is set with {@link Builder#setHost(String)}.
* Whether {@link #getHost()} is the host this transport derives from {@link
* #getResolvedUniverseDomain()} when no host is set with {@link Builder#setHost(String)}.
*/
boolean usesDefaultHost() {
return false;
Expand Down
Loading
Loading