From f5a95ac81306d25956da2d7a81a6f516719b404a Mon Sep 17 00:00:00 2001 From: Ben McIlwain Date: Thu, 19 Nov 2026 17:38:05 -0500 Subject: [PATCH] Propagate request reason to Cloud SQL requests Environments with GCP access-justification / request-reason enforcement reject human calls to the Cloud SQL Admin API (GetConnectSettings / GenerateEphemeralCert) with 403 Forbidden (NOT_AUTHORIZED) unless requests include a valid X-Goog-Request-Reason HTTP header, even when the caller holds the required IAM permissions. The Cloud SQL JDBC Socket Factory does not read the standard CLOUDSDK_CORE_REQUEST_REASON environment variable on its own, causing nomulus CLI commands that connect to Cloud SQL to fail under these restrictions. Propagate CLOUDSDK_CORE_REQUEST_REASON into the X-Goog-Request-Reason header on outgoing Cloud SQL Admin API requests so justified nomulus CLI commands pass validation and succeed. Usage: run nomulus with CLOUDSDK_CORE_REQUEST_REASON set in the environment to a request-reason value accepted by your organization's policy (for example, exported by an access-justification session wrapper or passed by a shell wrapper around nomulus): CLOUDSDK_CORE_REQUEST_REASON="" \ nomulus -e production list_cursors --type=RECURRING_BILLING Note that environments enforcing structured justification tokens expect an encoded request-reason payload (typically minted by a wrapper CLI) rather than raw free-form text. When CLOUDSDK_CORE_REQUEST_REASON is unset or whitespace-only, no header is added and existing behavior is unchanged. Implementation details in CloudSqlCredentialSupplier: - Store credentials and normalized request reason in an immutable record published via a single volatile reference so concurrent readers observe consistent snapshots without TOCTOU races. - Validate credentials and fail-fast validate non-empty request reasons as printable US-ASCII (after trimming Unicode whitespace) before publishing state or setting the credential-factory system property. - Override CredentialFactory.getCredentials() and unify uninitialized access checks in create() and getCredentials() via checkState(). - Make the class final with an explicit public no-arg constructor for reflective instantiation and use a static nested HttpCredentialsAdapter subclass to attach X-Goog-Request-Reason. - Add comprehensive unit tests in CloudSqlCredentialSupplierTest covering header propagation, Unicode whitespace trimming, blank/null omission and resets, 401-retry initialize() idempotency, reflective instantiation, uninitialized calls, invalid header characters, non-mutation on invalid inputs, and static test state cleanup. Tested end-to-end by running a read-only nomulus CLI SQL command (list_cursors) against sandbox: failed with 403 Forbidden without CLOUDSDK_CORE_REQUEST_REASON, and succeeded when run with a valid encoded CLOUDSDK_CORE_REQUEST_REASON set. BUG= http://b/587970232 --- .../CloudSqlCredentialSupplier.java | 99 +++++- .../CloudSqlCredentialSupplierTest.java | 300 ++++++++++++++++++ 2 files changed, 393 insertions(+), 6 deletions(-) create mode 100644 core/src/test/java/google/registry/persistence/transaction/CloudSqlCredentialSupplierTest.java diff --git a/core/src/main/java/google/registry/persistence/transaction/CloudSqlCredentialSupplier.java b/core/src/main/java/google/registry/persistence/transaction/CloudSqlCredentialSupplier.java index afbe8b0f04e..f7cfa133813 100644 --- a/core/src/main/java/google/registry/persistence/transaction/CloudSqlCredentialSupplier.java +++ b/core/src/main/java/google/registry/persistence/transaction/CloudSqlCredentialSupplier.java @@ -14,24 +14,111 @@ package google.registry.persistence.transaction; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; +import static java.util.function.Predicate.not; + +import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.sql.CredentialFactory; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.CharMatcher; +import java.io.IOException; +import java.util.Optional; +import javax.annotation.Nullable; + +/** + * Supplier class to provide credentials for the Cloud SQL JDBC Socket Factory. + * + *

When {@code CLOUDSDK_CORE_REQUEST_REASON} is set in the environment, outgoing Cloud SQL Admin + * API requests also include it in the {@code X-Goog-Request-Reason} HTTP header. + */ +public final class CloudSqlCredentialSupplier implements CredentialFactory { + + private static final String REQUEST_REASON_ENV_VAR = "CLOUDSDK_CORE_REQUEST_REASON"; + private static final String REQUEST_REASON_HEADER = "X-Goog-Request-Reason"; + private static final CharMatcher PRINTABLE_ASCII = CharMatcher.inRange(' ', '~'); -/** Supplier class to provide Credential for Cloud SQL library. */ -public class CloudSqlCredentialSupplier implements CredentialFactory { - private static GoogleCredentials credential; + @Nullable private static volatile SupplierConfig config; - /** Initialize the supplier with given credential json and scopes. */ + /** Required public no-arg constructor for {@link CredentialFactory} reflective instantiation. */ + public CloudSqlCredentialSupplier() {} + + /** Initializes the supplier with the given credential and environment request reason, if any. */ public static void setupCredentialSupplier(GoogleCredentials credential) { + setupCredentialSupplier(credential, System.getenv(REQUEST_REASON_ENV_VAR)); + } + + @VisibleForTesting + static void setupCredentialSupplier( + GoogleCredentials credential, @Nullable String requestReason) { + GoogleCredentials validatedCredential = checkNotNull(credential, "credential"); + Optional normalizedReason = normalizeRequestReason(requestReason); + config = new SupplierConfig(validatedCredential, normalizedReason); System.setProperty( CredentialFactory.CREDENTIAL_FACTORY_PROPERTY, CloudSqlCredentialSupplier.class.getName()); - CloudSqlCredentialSupplier.credential = credential; + } + + @VisibleForTesting + static void resetForTesting() { + config = null; } @Override public HttpRequestInitializer create() { - return new HttpCredentialsAdapter(credential); + SupplierConfig currentConfig = getConfig(); + Optional requestReason = currentConfig.requestReason(); + if (requestReason.isEmpty()) { + return new HttpCredentialsAdapter(currentConfig.credential()); + } + return new RequestReasonCredentialsAdapter(currentConfig.credential(), requestReason.get()); + } + + @Override + public GoogleCredentials getCredentials() { + return getConfig().credential(); + } + + private static SupplierConfig getConfig() { + SupplierConfig currentConfig = config; + checkState(currentConfig != null, "CloudSqlCredentialSupplier has not been initialized"); + return currentConfig; + } + + private static Optional normalizeRequestReason(@Nullable String requestReason) { + // Use Guava's CharMatcher.whitespace() rather than String.strip() so Unicode non-breaking + // spaces (such as U+00A0) are also trimmed. + Optional normalized = + Optional.ofNullable(requestReason) + .map(CharMatcher.whitespace()::trimFrom) + .filter(not(String::isEmpty)); + normalized.ifPresent( + reason -> + checkArgument( + PRINTABLE_ASCII.matchesAllOf(reason), + "%s must contain only printable ASCII characters", + REQUEST_REASON_ENV_VAR)); + return normalized; + } + + private record SupplierConfig(GoogleCredentials credential, Optional requestReason) {} + + private static final class RequestReasonCredentialsAdapter extends HttpCredentialsAdapter { + + private final String requestReason; + + private RequestReasonCredentialsAdapter(GoogleCredentials credential, String requestReason) { + super(credential); + this.requestReason = requestReason; + } + + @Override + public void initialize(HttpRequest request) throws IOException { + super.initialize(request); + request.getHeaders().set(REQUEST_REASON_HEADER, requestReason); + } } } diff --git a/core/src/test/java/google/registry/persistence/transaction/CloudSqlCredentialSupplierTest.java b/core/src/test/java/google/registry/persistence/transaction/CloudSqlCredentialSupplierTest.java new file mode 100644 index 00000000000..364c5d450df --- /dev/null +++ b/core/src/test/java/google/registry/persistence/transaction/CloudSqlCredentialSupplierTest.java @@ -0,0 +1,300 @@ +// Copyright 2026 The Nomulus Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package google.registry.persistence.transaction; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.google.api.client.http.GenericUrl; +import com.google.api.client.http.HttpRequest; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.testing.http.MockHttpTransport; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.AccessToken; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.sql.CredentialFactory; +import java.io.IOException; +import javax.annotation.Nullable; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +/** Unit tests for {@link CloudSqlCredentialSupplier}. */ +final class CloudSqlCredentialSupplierTest { + + private static final GenericUrl CONNECT_SETTINGS_URL = + new GenericUrl( + "https://sqladmin.googleapis.com/sql/v1beta4/projects/test/instances/db/connectSettings"); + private static final GoogleCredentials TEST_CREDENTIALS = + GoogleCredentials.create(new AccessToken("test-access-token", null)); + private static final GoogleCredentials OTHER_CREDENTIALS = + GoogleCredentials.create(new AccessToken("other-access-token", null)); + + @Nullable private String originalCredentialFactoryProperty; + + @BeforeEach + void beforeEach() { + originalCredentialFactoryProperty = + System.getProperty(CredentialFactory.CREDENTIAL_FACTORY_PROPERTY); + System.clearProperty(CredentialFactory.CREDENTIAL_FACTORY_PROPERTY); + CloudSqlCredentialSupplier.resetForTesting(); + } + + @AfterEach + void afterEach() { + CloudSqlCredentialSupplier.resetForTesting(); + if (originalCredentialFactoryProperty == null) { + System.clearProperty(CredentialFactory.CREDENTIAL_FACTORY_PROPERTY); + } else { + System.setProperty( + CredentialFactory.CREDENTIAL_FACTORY_PROPERTY, originalCredentialFactoryProperty); + } + } + + @Test + void testCreate_uninitialized_throwsIllegalStateException() { + IllegalStateException thrown = + assertThrows(IllegalStateException.class, () -> new CloudSqlCredentialSupplier().create()); + assertThat(thrown) + .hasMessageThat() + .isEqualTo("CloudSqlCredentialSupplier has not been initialized"); + } + + @Test + void testGetCredentials_uninitialized_throwsIllegalStateException() { + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> new CloudSqlCredentialSupplier().getCredentials()); + assertThat(thrown) + .hasMessageThat() + .isEqualTo("CloudSqlCredentialSupplier has not been initialized"); + } + + @Test + void testSetup_setsCredentialFactoryPropertyAndReturnsCredentials() { + CloudSqlCredentialSupplier.setupCredentialSupplier(TEST_CREDENTIALS, null); + CloudSqlCredentialSupplier supplier = new CloudSqlCredentialSupplier(); + + assertThat(System.getProperty(CredentialFactory.CREDENTIAL_FACTORY_PROPERTY)) + .isEqualTo(CloudSqlCredentialSupplier.class.getName()); + assertThat(supplier.getCredentials()).isSameInstanceAs(TEST_CREDENTIALS); + } + + @Test + void testSetup_supportsReflectiveInstantiationViaProperty() + throws ReflectiveOperationException, IOException { + CloudSqlCredentialSupplier.setupCredentialSupplier(TEST_CREDENTIALS, "ticket/12345"); + + String className = System.getProperty(CredentialFactory.CREDENTIAL_FACTORY_PROPERTY); + CredentialFactory factory = + Class.forName(className) + .asSubclass(CredentialFactory.class) + .getDeclaredConstructor() + .newInstance(); + + assertThat(factory).isInstanceOf(CloudSqlCredentialSupplier.class); + assertThat(factory.getCredentials()).isSameInstanceAs(TEST_CREDENTIALS); + HttpRequest request = buildGetRequest(factory.create()); + assertThat(request.getHeaders().getFirstHeaderStringValue("X-Goog-Request-Reason")) + .isEqualTo("ticket/12345"); + } + + @Test + void testCreate_withoutRequestReason_setsAuthorizationOnly() throws IOException { + CloudSqlCredentialSupplier.setupCredentialSupplier(TEST_CREDENTIALS, null); + HttpRequestInitializer initializer = new CloudSqlCredentialSupplier().create(); + + HttpRequest request = buildGetRequest(initializer); + + assertThat(initializer.getClass()).isEqualTo(HttpCredentialsAdapter.class); + assertThat(request.getHeaders().getAuthorization()).isEqualTo("Bearer test-access-token"); + assertThat(request.getHeaders().getFirstHeaderStringValue("X-Goog-Request-Reason")).isNull(); + } + + @ParameterizedTest + @ValueSource(strings = {"", " ", "\t", "\u00a0", "\u3000"}) + void testCreate_withBlankOrUnicodeWhitespaceRequestReason_omitsHeader(String requestReason) + throws IOException { + CloudSqlCredentialSupplier.setupCredentialSupplier(TEST_CREDENTIALS, requestReason); + HttpRequestInitializer initializer = new CloudSqlCredentialSupplier().create(); + + HttpRequest request = buildGetRequest(initializer); + + assertThat(initializer.getClass()).isEqualTo(HttpCredentialsAdapter.class); + assertThat(request.getHeaders().getAuthorization()).isEqualTo("Bearer test-access-token"); + assertThat(request.getHeaders().getFirstHeaderStringValue("X-Goog-Request-Reason")).isNull(); + } + + @Test + void testCreate_withRequestReason_attachesTrimmedHeaderAndAuthorization() throws IOException { + CloudSqlCredentialSupplier.setupCredentialSupplier( + TEST_CREDENTIALS, " \u00a0ticket/12345 investigate latency\u00a0 "); + CloudSqlCredentialSupplier supplier = new CloudSqlCredentialSupplier(); + HttpRequestInitializer initializer = supplier.create(); + + HttpRequest request = buildGetRequest(initializer); + + assertThat(initializer).isInstanceOf(HttpCredentialsAdapter.class); + assertThat(supplier.getCredentials()).isSameInstanceAs(TEST_CREDENTIALS); + assertThat(request.getHeaders().getAuthorization()).isEqualTo("Bearer test-access-token"); + assertThat(request.getHeaders().getFirstHeaderStringValue("X-Goog-Request-Reason")) + .isEqualTo("ticket/12345 investigate latency"); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = {" ", "\u00a0"}) + void testSetup_resetRequestReason_clearsHeader(@Nullable String resetReason) throws IOException { + CloudSqlCredentialSupplier.setupCredentialSupplier(TEST_CREDENTIALS, "ticket/12345"); + HttpRequest initialRequest = buildGetRequest(new CloudSqlCredentialSupplier().create()); + assertThat(initialRequest.getHeaders().getFirstHeaderStringValue("X-Goog-Request-Reason")) + .isEqualTo("ticket/12345"); + + CloudSqlCredentialSupplier.setupCredentialSupplier(TEST_CREDENTIALS, resetReason); + HttpRequestInitializer resetInitializer = new CloudSqlCredentialSupplier().create(); + HttpRequest resetRequest = buildGetRequest(resetInitializer); + + assertThat(resetInitializer.getClass()).isEqualTo(HttpCredentialsAdapter.class); + assertThat(resetRequest.getHeaders().getAuthorization()).isEqualTo("Bearer test-access-token"); + assertThat(resetRequest.getHeaders().getFirstHeaderStringValue("X-Goog-Request-Reason")) + .isNull(); + } + + @Test + void testCreate_initializeTwice_isIdempotentAndPreservesHeadersAndHandler() throws IOException { + CloudSqlCredentialSupplier.setupCredentialSupplier(TEST_CREDENTIALS, "ticket/12345"); + HttpRequestInitializer initializer = new CloudSqlCredentialSupplier().create(); + HttpRequest request = + new MockHttpTransport().createRequestFactory().buildGetRequest(CONNECT_SETTINGS_URL); + request.getHeaders().set("X-Existing-Header", "existing-value"); + + initializer.initialize(request); + initializer.initialize(request); + + assertThat(request.getHeaders().getAuthorization()).isEqualTo("Bearer test-access-token"); + assertThat(request.getHeaders().getHeaderStringValues("X-Goog-Request-Reason")) + .containsExactly("ticket/12345"); + assertThat(request.getHeaders().getFirstHeaderStringValue("X-Existing-Header")) + .isEqualTo("existing-value"); + assertThat(request.getUnsuccessfulResponseHandler()).isSameInstanceAs(initializer); + } + + @Test + void testSetup_nullCredential_throwsNullPointerExceptionWithoutMutatingState() { + NullPointerException thrown = + assertThrows( + NullPointerException.class, + () -> + CloudSqlCredentialSupplier.setupCredentialSupplier( + null, "ticket/12345 investigate latency")); + + assertThat(thrown).hasMessageThat().contains("credential"); + assertThat(System.getProperty(CredentialFactory.CREDENTIAL_FACTORY_PROPERTY)).isNull(); + assertThrows( + IllegalStateException.class, () -> new CloudSqlCredentialSupplier().getCredentials()); + } + + @Test + void testSetup_nullCredential_preservesExistingConfigAndProperty() throws IOException { + CloudSqlCredentialSupplier.setupCredentialSupplier(TEST_CREDENTIALS, "ticket/12345"); + + NullPointerException thrown = + assertThrows( + NullPointerException.class, + () -> CloudSqlCredentialSupplier.setupCredentialSupplier(null, "ticket/99999")); + + assertThat(thrown).hasMessageThat().contains("credential"); + assertThat(System.getProperty(CredentialFactory.CREDENTIAL_FACTORY_PROPERTY)) + .isEqualTo(CloudSqlCredentialSupplier.class.getName()); + CloudSqlCredentialSupplier supplier = new CloudSqlCredentialSupplier(); + assertThat(supplier.getCredentials()).isSameInstanceAs(TEST_CREDENTIALS); + HttpRequest request = buildGetRequest(supplier.create()); + assertThat(request.getHeaders().getFirstHeaderStringValue("X-Goog-Request-Reason")) + .isEqualTo("ticket/12345"); + } + + @ParameterizedTest + @ValueSource( + strings = { + "reason\rinjected", + "reason\ninjected", + "reason\r\nX-Injected: bad", + "reason\r\n folded", + "reason\0null", + "\0", + "reason\tvalue", + "reason\u007fvalue", + "ticket/caf\u00e9", + "ticket\u00a012345" + }) + void testSetup_invalidRequestReason_throwsIllegalArgumentExceptionWithoutMutatingState( + String invalidReason) { + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + CloudSqlCredentialSupplier.setupCredentialSupplier( + TEST_CREDENTIALS, invalidReason)); + + assertThat(thrown) + .hasMessageThat() + .isEqualTo("CLOUDSDK_CORE_REQUEST_REASON must contain only printable ASCII characters"); + assertThat(System.getProperty(CredentialFactory.CREDENTIAL_FACTORY_PROPERTY)).isNull(); + assertThrows( + IllegalStateException.class, () -> new CloudSqlCredentialSupplier().getCredentials()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "reason\rinjected", + "reason\ninjected", + "reason\r\nX-Injected: bad", + "reason\0null", + "ticket/caf\u00e9" + }) + void testSetup_invalidRequestReason_preservesExistingConfigAndProperty(String invalidReason) + throws IOException { + CloudSqlCredentialSupplier.setupCredentialSupplier(TEST_CREDENTIALS, "ticket/12345"); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + CloudSqlCredentialSupplier.setupCredentialSupplier( + OTHER_CREDENTIALS, invalidReason)); + + assertThat(thrown) + .hasMessageThat() + .isEqualTo("CLOUDSDK_CORE_REQUEST_REASON must contain only printable ASCII characters"); + assertThat(System.getProperty(CredentialFactory.CREDENTIAL_FACTORY_PROPERTY)) + .isEqualTo(CloudSqlCredentialSupplier.class.getName()); + CloudSqlCredentialSupplier supplier = new CloudSqlCredentialSupplier(); + assertThat(supplier.getCredentials()).isSameInstanceAs(TEST_CREDENTIALS); + HttpRequest request = buildGetRequest(supplier.create()); + assertThat(request.getHeaders().getFirstHeaderStringValue("X-Goog-Request-Reason")) + .isEqualTo("ticket/12345"); + } + + private static HttpRequest buildGetRequest(HttpRequestInitializer initializer) + throws IOException { + return new MockHttpTransport() + .createRequestFactory(initializer) + .buildGetRequest(CONNECT_SETTINGS_URL); + } +}