From 9d67031f2149905ffd6cbf7a48c5365e2c7f449e Mon Sep 17 00:00:00 2001 From: Matt Castelaz Date: Fri, 13 Nov 2026 22:29:43 +0000 Subject: [PATCH 1/6] fix(auth): don't throw NullPointerException on IAM error responses without a body IamUtils.sign() and IamUtils.getIdToken() parse the JSON body of every 4xx response. HttpURLConnection discards the body of a 401 response to a request sent in streaming mode (NetHttpTransport sends every POST with content in streaming mode), so the response has no content and parseAs() throws a NullPointerException. Callers such as ImpersonatedCredentials.sign(), ImpersonatedCredentials.idTokenWithAudience() and ComputeEngineCredentials.sign() then surface a bare NPE instead of the 401. Use the HTTP status message when the error response has no content, so these calls fail with an IOException (or SigningException) that includes the status code. --- .../java/com/google/auth/oauth2/IamUtils.java | 29 ++++-- .../com/google/auth/oauth2/IamUtilsTest.java | 88 +++++++++++++++++++ 2 files changed, 109 insertions(+), 8 deletions(-) diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java index 7f1005430cb4..c3d1794d48fc 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java @@ -168,10 +168,7 @@ private static String getSignature( response, LOGGER_PROVIDER, "Received response for signature to sign the blob"); int statusCode = response.getStatusCode(); if (statusCode >= 400 && statusCode < HttpStatusCodes.STATUS_CODE_SERVER_ERROR) { - GenericData responseError = response.parseAs(GenericData.class); - Map error = - OAuth2Utils.validateMap(responseError, "error", PARSE_ERROR_MESSAGE); - String errorMessage = OAuth2Utils.validateString(error, "message", PARSE_ERROR_MESSAGE); + String errorMessage = parseErrorMessage(response); throw new IOException( String.format( "Error code %s trying to sign provided bytes: %s", statusCode, errorMessage)); @@ -197,6 +194,25 @@ private static String getSignature( return OAuth2Utils.validateString(responseData, "signedBlob", PARSE_ERROR_SIGNATURE); } + /** + * Returns the error message from an IAM Credentials 4xx response. + * + *

The response can have no content. For example, {@code HttpURLConnection} (used by {@code + * NetHttpTransport}) discards the body of a 401 response to a request sent in streaming mode, + * which includes every POST with content. In that case, the HTTP status message is returned + * instead of failing with a {@link NullPointerException} while parsing. + */ + private static String parseErrorMessage(HttpResponse response) throws IOException { + if (response.getContent() == null) { + String statusMessage = response.getStatusMessage(); + return statusMessage != null ? statusMessage : "(no error details in the response)"; + } + GenericData responseError = response.parseAs(GenericData.class); + Map error = + OAuth2Utils.validateMap(responseError, "error", PARSE_ERROR_MESSAGE); + return OAuth2Utils.validateString(error, "message", PARSE_ERROR_MESSAGE); + } + /** * Returns an IdToken issued to the serviceAccount with a specified targetAudience * @@ -257,10 +273,7 @@ static IdToken getIdToken( LoggingUtils.logResponse(response, LOGGER_PROVIDER, "Received response for ID token request"); int statusCode = response.getStatusCode(); if (statusCode >= 400 && statusCode < HttpStatusCodes.STATUS_CODE_SERVER_ERROR) { - GenericData responseError = response.parseAs(GenericData.class); - Map error = - OAuth2Utils.validateMap(responseError, "error", PARSE_ERROR_MESSAGE); - String errorMessage = OAuth2Utils.validateString(error, "message", PARSE_ERROR_MESSAGE); + String errorMessage = parseErrorMessage(response); throw new IOException( String.format("Error code %s trying to getIDToken: %s", statusCode, errorMessage)); } diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java index 3e9e8258a0d9..66eb649ad727 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java @@ -36,6 +36,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.http.HttpStatusCodes; +import com.google.api.client.testing.http.MockHttpTransport; +import com.google.api.client.testing.http.MockLowLevelHttpResponse; +import com.google.auth.CredentialTypeForMetrics; import com.google.auth.Credentials; import com.google.auth.ServiceAccountSigner; import com.google.common.collect.ImmutableMap; @@ -238,4 +241,89 @@ void sign_4xxError_noRetry_exception() { // Only one request will have been made for a 4xx error (no retries) assertEquals(1, transportFactory.getTransport().getNumRequests()); } + + /** + * {@code HttpURLConnection} discards the body of a 401 response to a request sent in streaming + * mode (every POST with content), so the response has no content. The error must surface as an + * {@link IOException} with the status code, not a {@link NullPointerException}. + */ + @Test + void sign_4xxErrorWithEmptyBody_throwsSigningExceptionWithStatusCode() { + MockHttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpResponse( + new MockLowLevelHttpResponse() + .setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) + .setReasonPhrase("Unauthorized")) + .build(); + + ServiceAccountSigner.SigningException exception = + assertThrows( + ServiceAccountSigner.SigningException.class, + () -> + IamUtils.sign( + CLIENT_EMAIL, + credentials, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + transport, + new byte[] {0xD, 0xE, 0xA, 0xD}, + ImmutableMap.of())); + assertTrue(exception.getCause() instanceof IOException); + assertEquals( + "Error code 401 trying to sign provided bytes: Unauthorized", + exception.getCause().getMessage()); + } + + @Test + void getIdToken_4xxErrorWithEmptyBody_throwsIOExceptionWithStatusCode() { + MockHttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpResponse( + new MockLowLevelHttpResponse() + .setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) + .setReasonPhrase("Unauthorized")) + .build(); + + IOException exception = + assertThrows( + IOException.class, + () -> + IamUtils.getIdToken( + CLIENT_EMAIL, + credentials, + transport, + "https://example.com", + false, + ImmutableMap.of(), + CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT, + Credentials.GOOGLE_DEFAULT_UNIVERSE)); + assertEquals("Error code 401 trying to getIDToken: Unauthorized", exception.getMessage()); + } + + @Test + void getIdToken_4xxErrorWithJsonBody_includesServerMessage() { + MockHttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpResponse( + new MockLowLevelHttpResponse() + .setStatusCode(HttpStatusCodes.STATUS_CODE_FORBIDDEN) + .setContentType("application/json") + .setContent("{\"error\": {\"code\": 403, \"message\": \"Permission denied\"}}")) + .build(); + + IOException exception = + assertThrows( + IOException.class, + () -> + IamUtils.getIdToken( + CLIENT_EMAIL, + credentials, + transport, + "https://example.com", + false, + ImmutableMap.of(), + CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT, + Credentials.GOOGLE_DEFAULT_UNIVERSE)); + assertEquals("Error code 403 trying to getIDToken: Permission denied", exception.getMessage()); + } } From 1a66098a3e1e0f6209e025d19fb4c0311a23ca38 Mon Sep 17 00:00:00 2001 From: Matt Castelaz Date: Sat, 14 Nov 2026 03:42:32 +0000 Subject: [PATCH 2/6] fix(auth): also handle empty IAM error bodies and empty reason phrases - Fall back to the status message when the 4xx body is empty but not null (the JSON parser throws IllegalArgumentException: no JSON input found). - Treat an empty reason phrase like a missing one. - Tests: empty-string body, missing reason phrase, sign() with a JSON body, and an IAM-shaped 401 (Bearer challenge) for getIdToken that asserts no credential refresh. --- .../java/com/google/auth/oauth2/IamUtils.java | 28 ++++-- .../com/google/auth/oauth2/IamUtilsTest.java | 88 ++++++++++++++++++- 2 files changed, 107 insertions(+), 9 deletions(-) diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java index c3d1794d48fc..6f7aeeab8e82 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java @@ -49,6 +49,7 @@ import com.google.auth.ServiceAccountSigner; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.MetricsUtils.RequestType; +import com.google.common.base.Strings; import com.google.common.io.BaseEncoding; import java.io.IOException; import java.io.InputStream; @@ -197,22 +198,35 @@ private static String getSignature( /** * Returns the error message from an IAM Credentials 4xx response. * - *

The response can have no content. For example, {@code HttpURLConnection} (used by {@code - * NetHttpTransport}) discards the body of a 401 response to a request sent in streaming mode, - * which includes every POST with content. In that case, the HTTP status message is returned - * instead of failing with a {@link NullPointerException} while parsing. + *

The response can have no content or an empty body. For example, {@code HttpURLConnection} + * (used by {@code NetHttpTransport}) discards the body of a 401 or 407 response to a request sent + * in streaming mode, which includes every POST with content, and of any response with {@code + * Content-Length: 0}. In those cases, the HTTP status message is returned instead of failing with + * a {@link NullPointerException} or {@link IllegalArgumentException} while parsing. */ private static String parseErrorMessage(HttpResponse response) throws IOException { if (response.getContent() == null) { - String statusMessage = response.getStatusMessage(); - return statusMessage != null ? statusMessage : "(no error details in the response)"; + return getStatusMessageOrDefault(response); + } + GenericData responseError; + try { + responseError = response.parseAs(GenericData.class); + } catch (IllegalArgumentException e) { + // The JSON parser throws IllegalArgumentException for an empty body ("no JSON input found"). + return getStatusMessageOrDefault(response); } - GenericData responseError = response.parseAs(GenericData.class); Map error = OAuth2Utils.validateMap(responseError, "error", PARSE_ERROR_MESSAGE); return OAuth2Utils.validateString(error, "message", PARSE_ERROR_MESSAGE); } + private static String getStatusMessageOrDefault(HttpResponse response) { + String statusMessage = response.getStatusMessage(); + return Strings.isNullOrEmpty(statusMessage) + ? "(no error details in the response)" + : statusMessage; + } + /** * Returns an IdToken issued to the serviceAccount with a specified targetAudience * diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java index 66eb649ad727..d58d89f88483 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java @@ -275,13 +275,16 @@ void sign_4xxErrorWithEmptyBody_throwsSigningExceptionWithStatusCode() { } @Test - void getIdToken_4xxErrorWithEmptyBody_throwsIOExceptionWithStatusCode() { + void getIdToken_4xxErrorWithEmptyBody_throwsIOExceptionWithStatusCode() throws IOException { + // IAM's 401 carries a Bearer challenge without an error parameter, so HttpCredentialsAdapter + // doesn't refresh and retry. MockHttpTransport transport = new MockHttpTransport.Builder() .setLowLevelHttpResponse( new MockLowLevelHttpResponse() .setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) - .setReasonPhrase("Unauthorized")) + .setReasonPhrase("Unauthorized") + .addHeader("WWW-Authenticate", "Bearer realm=\"https://accounts.google.com/\"")) .build(); IOException exception = @@ -298,6 +301,7 @@ void getIdToken_4xxErrorWithEmptyBody_throwsIOExceptionWithStatusCode() { CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT, Credentials.GOOGLE_DEFAULT_UNIVERSE)); assertEquals("Error code 401 trying to getIDToken: Unauthorized", exception.getMessage()); + Mockito.verify(credentials, Mockito.never()).refresh(); } @Test @@ -326,4 +330,84 @@ void getIdToken_4xxErrorWithJsonBody_includesServerMessage() { Credentials.GOOGLE_DEFAULT_UNIVERSE)); assertEquals("Error code 403 trying to getIDToken: Permission denied", exception.getMessage()); } + + @Test + void sign_4xxErrorWithEmptyStringBody_usesStatusMessage() { + MockHttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpResponse( + new MockLowLevelHttpResponse() + .setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) + .setReasonPhrase("Unauthorized") + .setContent("")) + .build(); + + ServiceAccountSigner.SigningException exception = + assertThrows( + ServiceAccountSigner.SigningException.class, + () -> + IamUtils.sign( + CLIENT_EMAIL, + credentials, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + transport, + new byte[] {0xD, 0xE, 0xA, 0xD}, + ImmutableMap.of())); + assertEquals( + "Error code 401 trying to sign provided bytes: Unauthorized", + exception.getCause().getMessage()); + } + + @Test + void sign_4xxErrorWithEmptyBodyAndNoReasonPhrase_usesFallbackMessage() { + MockHttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpResponse( + new MockLowLevelHttpResponse() + .setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) + .setReasonPhrase("")) + .build(); + + ServiceAccountSigner.SigningException exception = + assertThrows( + ServiceAccountSigner.SigningException.class, + () -> + IamUtils.sign( + CLIENT_EMAIL, + credentials, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + transport, + new byte[] {0xD, 0xE, 0xA, 0xD}, + ImmutableMap.of())); + assertEquals( + "Error code 401 trying to sign provided bytes: (no error details in the response)", + exception.getCause().getMessage()); + } + + @Test + void sign_4xxErrorWithJsonBody_includesServerMessage() { + MockHttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpResponse( + new MockLowLevelHttpResponse() + .setStatusCode(HttpStatusCodes.STATUS_CODE_FORBIDDEN) + .setContentType("application/json") + .setContent("{\"error\": {\"code\": 403, \"message\": \"Permission denied\"}}")) + .build(); + + ServiceAccountSigner.SigningException exception = + assertThrows( + ServiceAccountSigner.SigningException.class, + () -> + IamUtils.sign( + CLIENT_EMAIL, + credentials, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + transport, + new byte[] {0xD, 0xE, 0xA, 0xD}, + ImmutableMap.of())); + assertEquals( + "Error code 403 trying to sign provided bytes: Permission denied", + exception.getCause().getMessage()); + } } From 37f886e4fcfd57de54ea39d2301201529b118930 Mon Sep 17 00:00:00 2001 From: Matt Castelaz Date: Mon, 16 Nov 2026 14:35:54 +0000 Subject: [PATCH 3/6] test(auth): cover a JSON null IAM error body --- .../com/google/auth/oauth2/IamUtilsTest.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java index d58d89f88483..81a5a4704e47 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java @@ -410,4 +410,35 @@ void sign_4xxErrorWithJsonBody_includesServerMessage() { "Error code 403 trying to sign provided bytes: Permission denied", exception.getCause().getMessage()); } + + @Test + void sign_4xxErrorWithJsonNullBody_throwsSigningExceptionNotNullPointerException() { + // A JSON null body parses to Data.nullOf(GenericData.class), not a Java null, so the missing + // "error" field is reported as a parse error with the status code. + MockHttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpResponse( + new MockLowLevelHttpResponse() + .setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) + .setReasonPhrase("Unauthorized") + .setContentType("application/json") + .setContent("null")) + .build(); + + ServiceAccountSigner.SigningException exception = + assertThrows( + ServiceAccountSigner.SigningException.class, + () -> + IamUtils.sign( + CLIENT_EMAIL, + credentials, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + transport, + new byte[] {0xD, 0xE, 0xA, 0xD}, + ImmutableMap.of())); + assertTrue(exception.getCause() instanceof IOException); + assertTrue( + exception.getCause().getMessage().startsWith("Error parsing error message response."), + exception.getCause().getMessage()); + } } From efcae79473c3474881ffa988481b8d4aa7d4e7bb Mon Sep 17 00:00:00 2001 From: Matt Castelaz Date: Fri, 20 Nov 2026 02:34:31 +0000 Subject: [PATCH 4/6] fix(auth): fall back to status message on non-JSON or incomplete IAM 4xx bodies --- .../java/com/google/auth/oauth2/IamUtils.java | 49 ++++--- .../com/google/auth/oauth2/IamUtilsTest.java | 124 +++++++++++++++++- 2 files changed, 150 insertions(+), 23 deletions(-) diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java index 6f7aeeab8e82..3e7ac2a69444 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java @@ -196,28 +196,41 @@ private static String getSignature( } /** - * Returns the error message from an IAM Credentials 4xx response. + * Returns the error message from an IAM Credentials 4xx response, or falls back to the HTTP + * status message when the body is missing, empty, not JSON, or lacks {@code error.message}. * - *

The response can have no content or an empty body. For example, {@code HttpURLConnection} - * (used by {@code NetHttpTransport}) discards the body of a 401 or 407 response to a request sent - * in streaming mode, which includes every POST with content, and of any response with {@code - * Content-Length: 0}. In those cases, the HTTP status message is returned instead of failing with - * a {@link NullPointerException} or {@link IllegalArgumentException} while parsing. + *

For example, {@code HttpURLConnection} (used by {@code NetHttpTransport}) discards the body + * of a 401 or 407 response to a request sent in streaming mode (every POST with content) and of + * any response with {@code Content-Length: 0}, and proxies can return HTML or other non-IAM + * bodies. Falling back preserves the HTTP status code in the caller's {@link IOException} instead + * of failing with a {@link NullPointerException}, {@link IllegalArgumentException}, or JSON parse + * error. */ - private static String parseErrorMessage(HttpResponse response) throws IOException { - if (response.getContent() == null) { - return getStatusMessageOrDefault(response); - } - GenericData responseError; + private static String parseErrorMessage(HttpResponse response) { try { - responseError = response.parseAs(GenericData.class); - } catch (IllegalArgumentException e) { - // The JSON parser throws IllegalArgumentException for an empty body ("no JSON input found"). - return getStatusMessageOrDefault(response); + if (response.getContent() != null) { + GenericData responseError = response.parseAs(GenericData.class); + if (responseError != null) { + Object error = responseError.get("error"); + if (error instanceof Map) { + Object message = ((Map) error).get("message"); + if (message instanceof String && !((String) message).isEmpty()) { + return (String) message; + } + } + } + } + } catch (IOException | IllegalArgumentException e) { + // Empty body ("no JSON input found"), non-JSON body (for example, an HTML error page from a + // proxy), or unreadable stream: fall back to the HTTP status message below. + } finally { + try { + response.disconnect(); + } catch (IOException ignored) { + // Best-effort cleanup before throwing the 4xx error. + } } - Map error = - OAuth2Utils.validateMap(responseError, "error", PARSE_ERROR_MESSAGE); - return OAuth2Utils.validateString(error, "message", PARSE_ERROR_MESSAGE); + return getStatusMessageOrDefault(response); } private static String getStatusMessageOrDefault(HttpResponse response) { diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java index 81a5a4704e47..cc519511208b 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java @@ -412,9 +412,9 @@ void sign_4xxErrorWithJsonBody_includesServerMessage() { } @Test - void sign_4xxErrorWithJsonNullBody_throwsSigningExceptionNotNullPointerException() { - // A JSON null body parses to Data.nullOf(GenericData.class), not a Java null, so the missing - // "error" field is reported as a parse error with the status code. + void sign_4xxErrorWithJsonNullBody_usesStatusMessage() { + // A JSON null body parses to Data.nullOf(GenericData.class), not a Java null, and has no + // "error.message" field, so it falls back to the HTTP status message with the status code. MockHttpTransport transport = new MockHttpTransport.Builder() .setLowLevelHttpResponse( @@ -437,8 +437,122 @@ void sign_4xxErrorWithJsonNullBody_throwsSigningExceptionNotNullPointerException new byte[] {0xD, 0xE, 0xA, 0xD}, ImmutableMap.of())); assertTrue(exception.getCause() instanceof IOException); - assertTrue( - exception.getCause().getMessage().startsWith("Error parsing error message response."), + assertEquals( + "Error code 401 trying to sign provided bytes: Unauthorized", exception.getCause().getMessage()); } + + @Test + void sign_4xxErrorWithHtmlBody_usesStatusMessage() { + MockHttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpResponse( + new MockLowLevelHttpResponse() + .setStatusCode(HttpStatusCodes.STATUS_CODE_FORBIDDEN) + .setReasonPhrase("Forbidden") + .setContentType("text/html") + .setContent("

403 Forbidden

")) + .build(); + + ServiceAccountSigner.SigningException exception = + assertThrows( + ServiceAccountSigner.SigningException.class, + () -> + IamUtils.sign( + CLIENT_EMAIL, + credentials, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + transport, + new byte[] {0xD, 0xE, 0xA, 0xD}, + ImmutableMap.of())); + assertTrue(exception.getCause() instanceof IOException); + assertEquals( + "Error code 403 trying to sign provided bytes: Forbidden", + exception.getCause().getMessage()); + } + + @Test + void sign_4xxErrorWithEmptyJsonObject_usesStatusMessage() { + MockHttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpResponse( + new MockLowLevelHttpResponse() + .setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) + .setReasonPhrase("Unauthorized") + .setContentType("application/json") + .setContent("{}")) + .build(); + + ServiceAccountSigner.SigningException exception = + assertThrows( + ServiceAccountSigner.SigningException.class, + () -> + IamUtils.sign( + CLIENT_EMAIL, + credentials, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + transport, + new byte[] {0xD, 0xE, 0xA, 0xD}, + ImmutableMap.of())); + assertTrue(exception.getCause() instanceof IOException); + assertEquals( + "Error code 401 trying to sign provided bytes: Unauthorized", + exception.getCause().getMessage()); + } + + @Test + void getIdToken_4xxErrorWithHtmlBody_usesStatusMessage() { + MockHttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpResponse( + new MockLowLevelHttpResponse() + .setStatusCode(HttpStatusCodes.STATUS_CODE_FORBIDDEN) + .setReasonPhrase("Forbidden") + .setContentType("text/html") + .setContent("

403 Forbidden

")) + .build(); + + IOException exception = + assertThrows( + IOException.class, + () -> + IamUtils.getIdToken( + CLIENT_EMAIL, + credentials, + transport, + "https://example.com", + false, + ImmutableMap.of(), + CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT, + Credentials.GOOGLE_DEFAULT_UNIVERSE)); + assertEquals("Error code 403 trying to getIDToken: Forbidden", exception.getMessage()); + } + + @Test + void getIdToken_4xxErrorWithJsonMissingMessage_usesStatusMessage() { + MockHttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpResponse( + new MockLowLevelHttpResponse() + .setStatusCode(HttpStatusCodes.STATUS_CODE_FORBIDDEN) + .setReasonPhrase("Forbidden") + .setContentType("application/json") + .setContent("{\"error\": {\"code\": 403}}")) + .build(); + + IOException exception = + assertThrows( + IOException.class, + () -> + IamUtils.getIdToken( + CLIENT_EMAIL, + credentials, + transport, + "https://example.com", + false, + ImmutableMap.of(), + CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT, + Credentials.GOOGLE_DEFAULT_UNIVERSE)); + assertEquals("Error code 403 trying to getIDToken: Forbidden", exception.getMessage()); + } } From 6aa20e71e0e08d9df81fde3edf77ce83017f1b34 Mon Sep 17 00:00:00 2001 From: Matt Castelaz Date: Fri, 20 Nov 2026 03:31:44 +0000 Subject: [PATCH 5/6] fix(auth): avoid disconnecting pooled HTTP responses in IamUtils.parseErrorMessage --- .../java/com/google/auth/oauth2/IamUtils.java | 31 +++++++++---------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java index 3e7ac2a69444..3111bef92402 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java @@ -207,27 +207,24 @@ private static String getSignature( * error. */ private static String parseErrorMessage(HttpResponse response) { + GenericData responseError; try { - if (response.getContent() != null) { - GenericData responseError = response.parseAs(GenericData.class); - if (responseError != null) { - Object error = responseError.get("error"); - if (error instanceof Map) { - Object message = ((Map) error).get("message"); - if (message instanceof String && !((String) message).isEmpty()) { - return (String) message; - } - } - } + if (response.getContent() == null) { + return getStatusMessageOrDefault(response); } + responseError = response.parseAs(GenericData.class); } catch (IOException | IllegalArgumentException e) { // Empty body ("no JSON input found"), non-JSON body (for example, an HTML error page from a - // proxy), or unreadable stream: fall back to the HTTP status message below. - } finally { - try { - response.disconnect(); - } catch (IOException ignored) { - // Best-effort cleanup before throwing the 4xx error. + // proxy), or unreadable stream. + return getStatusMessageOrDefault(response); + } + if (responseError != null) { + Object error = responseError.get("error"); + if (error instanceof Map) { + Object message = ((Map) error).get("message"); + if (message instanceof String && !((String) message).isEmpty()) { + return (String) message; + } } } return getStatusMessageOrDefault(response); From 752c7e5b13037f21fbaba3c83ede578e98914b7f Mon Sep 17 00:00:00 2001 From: Matt Castelaz Date: Fri, 20 Nov 2026 04:19:11 +0000 Subject: [PATCH 6/6] test(auth): cover null reason phrase and empty error.message in IamUtilsTest --- .../com/google/auth/oauth2/IamUtilsTest.java | 59 ++++++++++++++++++- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java index cc519511208b..b136f264f998 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java @@ -364,8 +364,7 @@ void sign_4xxErrorWithEmptyBodyAndNoReasonPhrase_usesFallbackMessage() { new MockHttpTransport.Builder() .setLowLevelHttpResponse( new MockLowLevelHttpResponse() - .setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) - .setReasonPhrase("")) + .setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED)) .build(); ServiceAccountSigner.SigningException exception = @@ -384,6 +383,34 @@ void sign_4xxErrorWithEmptyBodyAndNoReasonPhrase_usesFallbackMessage() { exception.getCause().getMessage()); } + @Test + void getIdToken_4xxErrorWithEmptyBodyAndEmptyReasonPhrase_usesFallbackMessage() { + MockHttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpResponse( + new MockLowLevelHttpResponse() + .setStatusCode(HttpStatusCodes.STATUS_CODE_FORBIDDEN) + .setReasonPhrase("")) + .build(); + + IOException exception = + assertThrows( + IOException.class, + () -> + IamUtils.getIdToken( + CLIENT_EMAIL, + credentials, + transport, + "https://example.com", + false, + ImmutableMap.of(), + CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT, + Credentials.GOOGLE_DEFAULT_UNIVERSE)); + assertEquals( + "Error code 403 trying to getIDToken: (no error details in the response)", + exception.getMessage()); + } + @Test void sign_4xxErrorWithJsonBody_includesServerMessage() { MockHttpTransport transport = @@ -555,4 +582,32 @@ void getIdToken_4xxErrorWithJsonMissingMessage_usesStatusMessage() { Credentials.GOOGLE_DEFAULT_UNIVERSE)); assertEquals("Error code 403 trying to getIDToken: Forbidden", exception.getMessage()); } + + @Test + void getIdToken_4xxErrorWithJsonEmptyMessage_usesStatusMessage() { + MockHttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpResponse( + new MockLowLevelHttpResponse() + .setStatusCode(HttpStatusCodes.STATUS_CODE_FORBIDDEN) + .setReasonPhrase("Forbidden") + .setContentType("application/json") + .setContent("{\"error\": {\"code\": 403, \"message\": \"\"}}")) + .build(); + + IOException exception = + assertThrows( + IOException.class, + () -> + IamUtils.getIdToken( + CLIENT_EMAIL, + credentials, + transport, + "https://example.com", + false, + ImmutableMap.of(), + CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT, + Credentials.GOOGLE_DEFAULT_UNIVERSE)); + assertEquals("Error code 403 trying to getIDToken: Forbidden", exception.getMessage()); + } }