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 @@ -85,7 +85,11 @@ protected LazyWriteChannel<StorageObject> newLazyWriteChannel() {
() ->
ResumableMedia.http()
.write()
.byteChannel(blobChannelContext.getHttpClientContext())
.byteChannel(
start.getSignedUrl() == null
? blobChannelContext.getHttpClientContext()
: HttpClientContext.forSignedUrl(
blobChannelContext.getStorageOptions().getStorageRpcV1()))
Comment thread
Dhriti07 marked this conversation as resolved.
Resolved
.resumable()
.setCommittedBytesCallback(this::setCommittedPosition)
.withRetryConfig(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.ObjectParser;
import com.google.cloud.storage.spi.v1.HttpStorageRpc;
import com.google.cloud.storage.spi.v1.StorageRpc;
import io.opencensus.trace.Span;
import io.opencensus.trace.Tracer;
Expand Down Expand Up @@ -78,6 +79,15 @@ static HttpClientContext from(StorageRpc storageRpc) {
Tracing.getTracer());
}

static HttpClientContext forSignedUrl(StorageRpc storageRpc) {
HttpRequestFactory requestFactory =
storageRpc instanceof HttpStorageRpc
? ((HttpStorageRpc) storageRpc).getSignedUrlRequestFactory()
: storageRpc.getStorage().getRequestFactory().getTransport().createRequestFactory();
return new HttpClientContext(
requestFactory, storageRpc.getStorage().getObjectParser(), Tracing.getTracer());
}
Comment thread
Dhriti07 marked this conversation as resolved.
Resolved
Comment on lines +82 to +89

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.

[Medium] For any StorageRpc that isn't an HttpStorageRpc (e.g. one from a custom setServiceRpcFactory), the fallback builds a bare transport.createRequestFactory(). That drops the timeouts, Census tracing, invocation-id/idempotency headers, and x-goog-api-client/user-agent. Before this PR, those callers got from(storageRpc), and no test covers this branch. Could we keep the previous behavior for non-HTTP RPCs?

Suggested change
static HttpClientContext forSignedUrl(StorageRpc storageRpc) {
HttpRequestFactory requestFactory =
storageRpc instanceof HttpStorageRpc
? ((HttpStorageRpc) storageRpc).getSignedUrlRequestFactory()
: storageRpc.getStorage().getRequestFactory().getTransport().createRequestFactory();
return new HttpClientContext(
requestFactory, storageRpc.getStorage().getObjectParser(), Tracing.getTracer());
}
static HttpClientContext forSignedUrl(StorageRpc storageRpc) {
if (!(storageRpc instanceof HttpStorageRpc)) {
return from(storageRpc);
}
HttpStorageRpc httpStorageRpc = (HttpStorageRpc) storageRpc;
return new HttpClientContext(
httpStorageRpc.getSignedUrlRequestFactory(),
httpStorageRpc.getStorage().getObjectParser(),
Tracing.getTracer());
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

In practice HttpStorageRpc is the only production StorageRpc implementation and StorageRpc.getStorage() is @InternalApi, so external callers should not hit this branch unless they wrap HttpStorageRpc. For a wrapper, returning from(storageRpc) would keep the authenticated request factory and send credentials on signed URL uploads. I kept the bare factory so that fallback stays credential-free, happy to revisit if you know of a custom non-HttpStorageRpc caller.


public static HttpClientContext of(
HttpRequestFactory requestFactory, JsonObjectParser jsonObjectParser) {
return new HttpClientContext(requestFactory, jsonObjectParser, Tracing.getTracer());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.checkerframework.checker.lock.qual.GuardedBy;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;

final class JsonResumableWrite implements Serializable {
private static final long serialVersionUID = 7934407897802252292L;
Expand Down Expand Up @@ -80,6 +81,10 @@ ImmutableMap<String, String> getExtraHeaders() {
return uploadId;
}

@Nullable String getSignedUrl() {
Comment thread
Dhriti07 marked this conversation as resolved.
Resolved
return signedUrl;
}

public long getBeginOffset() {
return beginOffset;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Data;
import com.google.api.core.InternalApi;
import com.google.api.gax.core.GaxProperties;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.HeaderProvider;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.Storage.BucketAccessControls;
import com.google.api.services.storage.Storage.Buckets;
Expand Down Expand Up @@ -77,6 +81,7 @@
import com.google.api.services.storage.model.ServiceAccount;
import com.google.api.services.storage.model.StorageObject;
import com.google.api.services.storage.model.TestIamPermissionsResponse;
import com.google.cloud.ServiceOptions;
import com.google.cloud.Tuple;
import com.google.cloud.http.CensusHttpModule;
import com.google.cloud.http.HttpTransportOptions;
Expand Down Expand Up @@ -132,6 +137,15 @@ public class HttpStorageRpc implements StorageRpc {

private final StorageOptions options;
private final Storage storage;

/**
* Eagerly constructed request factory for requests sent to a signed URL. Requests built from this
* factory carry no client credentials or quota project and intentionally do not run {@link
* HttpTransportOptions#getHttpRequestInitializer(ServiceOptions)}; customizations made by
* subclasses of {@code HttpTransportOptions} therefore do not apply. The timeout and header
* handling in the constructor mirrors that initializer and must be kept in sync with it.
*/
private final HttpRequestFactory signedUrlRequestFactory;
Comment thread
Dhriti07 marked this conversation as resolved.
Resolved
private final Tracer tracer = Tracing.getTracer();
private final HttpRequestInitializer batchRequestInitializer;

Expand Down Expand Up @@ -184,12 +198,63 @@ public HttpStorageRpc(StorageOptions options, JsonFactory jsonFactory) {
storageBuilder.setRootUrl(host);
}
storage = storageBuilder.build();
Map<String, String> signedUrlHeaders = signedUrlHeaders(options);
HttpRequestInitializer signedUrlInitializer =
request -> {
if (transportOptions.getConnectTimeout() >= 0) {
request.setConnectTimeout(transportOptions.getConnectTimeout());
}
if (transportOptions.getReadTimeout() >= 0) {
request.setReadTimeout(transportOptions.getReadTimeout());
}
HttpHeaders headers = request.getHeaders();
for (Entry<String, String> e : signedUrlHeaders.entrySet()) {
// Mirrors com.google.api.gax.httpjson.HttpHeadersUtils#setHeader (without Long
// conversion for Age/Content-Length): fields declared on HttpHeaders are list valued.
boolean listValued = headers.getClassInfo().getFieldInfo(e.getKey()) != null;
headers.set(e.getKey(), listValued ? ImmutableList.of(e.getValue()) : e.getValue());
}
Comment on lines +211 to +216

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: This loop re-implements HttpHeadersUtils#setHeader with one difference: headers like Content-Length and Age get a String value here, while gax converts them to Long. That's unlikely to matter for header-provider headers, but a comment pointing at the gax helper would help keep them in sync.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I agree it is unlikely to break anything. Added it to be extra careful

};
Comment thread
Dhriti07 marked this conversation as resolved.
Resolved
signedUrlRequestFactory =
transport.createRequestFactory(
new InvocationIdInitializer(
censusHttpModule.getHttpRequestInitializer(signedUrlInitializer),
applicationName,
tm));
}

/**
* Headers for requests sent to a signed URL. These are the same headers sent on other requests,
* except {@code Authorization} and {@code x-goog-user-project}, which are stripped even if
* configured through a user {@link HeaderProvider}.
*/
private static Map<String, String> signedUrlHeaders(StorageOptions options) {
HeaderProvider internalHeaderProvider =
ApiClientHeaderProvider.newBuilder()
.setClientLibToken(
ServiceOptions.getGoogApiClientLibName(),
GaxProperties.getLibraryVersion(options.getClass()))
.build();
ImmutableMap.Builder<String, String> headers = ImmutableMap.builder();
for (Entry<String, String> e :
options.getMergedHeaderProvider(internalHeaderProvider).getHeaders().entrySet()) {
String key = e.getKey();
if (!"authorization".equalsIgnoreCase(key) && !"x-goog-user-project".equalsIgnoreCase(key)) {
headers.put(e);
}
}
return headers.build();
Comment thread
Dhriti07 marked this conversation as resolved.
Resolved
}

public Storage getStorage() {
return storage;
}

@InternalApi
public HttpRequestFactory getSignedUrlRequestFactory() {
return signedUrlRequestFactory;
}

private static final class InvocationIdInitializer implements HttpRequestInitializer {
@Nullable HttpRequestInitializer initializer;
@Nullable private final String applicationName;
Expand Down Expand Up @@ -1224,9 +1289,8 @@ public String open(String signedURL) {
url.set("uploadType", "resumable");
String bytesArrayParameters = "";
byte[] bytesArray = new byte[bytesArrayParameters.length()];
HttpRequestFactory requestFactory = storage.getRequestFactory();
HttpRequest httpRequest =
requestFactory.buildPostRequest(
signedUrlRequestFactory.buildPostRequest(
Comment thread
Dhriti07 marked this conversation as resolved.
Resolved
url, new ByteArrayContent("", bytesArray, 0, bytesArray.length));
HttpHeaders requestHeaders = httpRequest.getHeaders();
requestHeaders.set("X-Upload-Content-Type", "");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,25 @@
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.api.gax.rpc.FixedHeaderProvider;
import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.RestorableState;
import com.google.cloud.WriteChannel;
import com.google.cloud.http.HttpTransportOptions;
import com.google.cloud.storage.Retrying.RetrierWithAlg;
import com.google.cloud.storage.spi.v1.StorageRpc;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import org.junit.Assert;
import org.junit.Test;
Expand All @@ -33,6 +49,8 @@ public final class ResumableMediaTest {
"http://localhost/test-bucket/test1.txt?GoogAccessId=testClient-test@test.com&Expires=1553839761&Signature=MJUBXAZ7";
private static final String SIGNED_URL_VALID =
"http://localhost/test-bucket/test1.txt?GoogleAccessId=testClient-test@test.com&Expires=1553839761&Signature=MJUBXAZ7";
private static final String SIGNED_URL_V4_VALID =
"http://localhost/test-bucket/test1.txt?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=c&X-Goog-Date=20260101T000000Z&X-Goog-Expires=60&X-Goog-SignedHeaders=host&X-Goog-Signature=MJUBXAZ7";

@Test
public void startUploadForSignedUrl_expectStorageException_whenUrlInvalid() throws Exception {
Expand Down Expand Up @@ -61,4 +79,124 @@ public void startUploadForSignedUrl_whenUrlValid() throws Exception {
ResumableMedia.startUploadForSignedUrl(options, url, RetrierWithAlg.attemptOnce());
assertThat(uploadIdSupplier.get()).isEqualTo("upload-id");
}

@Test
public void writerUrl_requestsDoNotIncludeCredentials() throws Exception {
RecordingTransport transport = new RecordingTransport();
try (WriteChannel writer = newStorage(transport).writer(new URL(SIGNED_URL_VALID))) {
writer.write(ByteBuffer.wrap(new byte[10]));
}

assertThat(transport.methods).containsExactly("POST", "PUT").inOrder();
assertSignedUrlHeaders(transport);
}

@Test
public void writerUrl_v4_requestsDoNotIncludeCredentials() throws Exception {
RecordingTransport transport = new RecordingTransport();
try (WriteChannel writer = newStorage(transport).writer(new URL(SIGNED_URL_V4_VALID))) {
writer.write(ByteBuffer.wrap(new byte[10]));
}

assertThat(transport.methods).containsExactly("POST", "PUT").inOrder();
assertSignedUrlHeaders(transport);
}

@Test
public void writerUrl_restoredWriterRequestsDoNotIncludeCredentials() throws Exception {
RecordingTransport transport = new RecordingTransport();
RestorableState<WriteChannel> state =
newStorage(transport).writer(new URL(SIGNED_URL_VALID)).capture();
try (WriteChannel writer = state.restore()) {
writer.write(ByteBuffer.wrap(new byte[10]));
}

assertThat(transport.methods).containsExactly("POST", "PUT").inOrder();
assertSignedUrlHeaders(transport);
}

@Test
public void writerUrl_stripsHeaderProviderQuotaProject() throws Exception {
RecordingTransport transport = new RecordingTransport();
Storage storage =
HttpStorageOptions.newBuilder()
.setProjectId("p")
.setHost("http://localhost")
.setHeaderProvider(
FixedHeaderProvider.create(
"x-custom", "v", "Authorization", "Bearer user", "X-Goog-User-Project", "up"))
.setTransportOptions(
HttpTransportOptions.newBuilder().setHttpTransportFactory(() -> transport).build())
.build()
.getService();
try (WriteChannel writer = storage.writer(new URL(SIGNED_URL_VALID))) {
writer.write(ByteBuffer.wrap(new byte[10]));
}
assertSignedUrlHeaders(transport);
}

@Test
public void writerBlobInfo_requestsIncludeClientHeaders() throws Exception {
RecordingTransport transport = new RecordingTransport();
try (WriteChannel writer =
newStorage(transport).writer(BlobInfo.newBuilder("b", "o").build())) {
writer.write(ByteBuffer.wrap(new byte[10]));
}

assertThat(transport.methods).containsExactly("POST", "PUT").inOrder();
for (Map<String, List<String>> headers : transport.headers) {
assertThat(headers).containsKey("authorization");
assertThat(headers).containsKey("x-goog-user-project");
assertThat(headers).containsKey("x-custom");
}
}

private static Storage newStorage(RecordingTransport transport) {
return HttpStorageOptions.newBuilder()
.setProjectId("p")
.setHost("http://localhost")
.setQuotaProjectId("q")
.setHeaderProvider(
FixedHeaderProvider.create("x-custom", "v", "Authorization", "Bearer user"))
.setCredentials(
GoogleCredentials.create(
new AccessToken("t", new Date(System.currentTimeMillis() + 3_600_000))))
.setTransportOptions(
HttpTransportOptions.newBuilder().setHttpTransportFactory(() -> transport).build())
.build()
.getService();
}

private static void assertSignedUrlHeaders(RecordingTransport transport) {
for (Map<String, List<String>> headers : transport.headers) {
assertThat(headers).doesNotContainKey("authorization");
assertThat(headers).doesNotContainKey("x-goog-user-project");
assertThat(headers).containsKey("x-custom");
}
}

private static final class RecordingTransport extends HttpTransport {
private final List<String> methods = Collections.synchronizedList(new ArrayList<>());
private final List<Map<String, List<String>>> headers =
Collections.synchronizedList(new ArrayList<>());

@Override
protected LowLevelHttpRequest buildRequest(String method, String url) {
return new MockLowLevelHttpRequest(url) {
@Override
public MockLowLevelHttpResponse execute() {
methods.add(method);
headers.add(getHeaders());
if (method.equals("POST")) {
return new MockLowLevelHttpResponse()
.setStatusCode(url.contains("Signature=") ? 201 : 200)
.addHeader("Location", "http://localhost/upload?upload_id=u");
}
return new MockLowLevelHttpResponse()
.addHeader("Content-Type", "application/json; charset=UTF-8")
.setContent("{\"bucket\":\"b\",\"name\":\"o\",\"size\":\"10\"}");
}
};
}
}
Comment thread
Dhriti07 marked this conversation as resolved.
Resolved
}
Loading