Skip to content
Merged
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 @@ -82,6 +82,7 @@ public class JwtCredentials extends Credentials implements JwtProvider {
private final String privateKeyId;
private final JwtClaims jwtClaims;
private final Long lifeSpanSeconds;
private final String universeDomain;
@VisibleForTesting transient Clock clock;

private transient String jwt;
Expand All @@ -95,6 +96,11 @@ private JwtCredentials(Builder builder) {
Preconditions.checkState(jwtClaims.isComplete(), JWT_INCOMPLETE_ERROR_MESSAGE);
this.lifeSpanSeconds = Preconditions.checkNotNull(builder.getLifeSpanSeconds());
this.clock = Preconditions.checkNotNull(builder.getClock());
if (builder.universeDomain == null || builder.universeDomain.trim().isEmpty()) {
this.universeDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE;
} else {
this.universeDomain = builder.universeDomain;
}
}

public static Builder newBuilder() {
Expand Down Expand Up @@ -152,9 +158,22 @@ public JwtCredentials jwtWithClaims(JwtClaims newClaims) {
.setPrivateKey(privateKey)
.setPrivateKeyId(privateKeyId)
.setJwtClaims(jwtClaims.merge(newClaims))
.setUniverseDomain(this.universeDomain)
.build();
}

/**
* Returns the universe domain for the credential.
*
* @return the configured universe domain, or {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} if none
* was explicitly configured
* @throws IOException if retrieving the universe domain fails
*/
@Override
public String getUniverseDomain() throws IOException {
return this.universeDomain;
}
Comment on lines +172 to +175

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.

high

Since JwtCredentials implements Serializable, adding the new universeDomain field introduces a backward compatibility issue. When deserializing an older serialized instance of JwtCredentials (which does not contain the universeDomain field), Java serialization will initialize universeDomain to null. To prevent getUniverseDomain() from returning null in these cases, we should return Credentials.GOOGLE_DEFAULT_UNIVERSE if this.universeDomain is null.

Suggested change
@Override
public String getUniverseDomain() throws IOException {
return this.universeDomain;
}
@Override
public String getUniverseDomain() throws IOException {
return this.universeDomain == null ? Credentials.GOOGLE_DEFAULT_UNIVERSE : this.universeDomain;
}
References
  1. When adding a new field to a serializable class that may be null when deserializing older versions, provide a getter with a default fallback value.

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.

These serialization compatibility issues seem legit to me, wdyt?


@Override
public String getAuthenticationType() {
return "JWT";
Expand Down Expand Up @@ -190,12 +209,18 @@ public boolean equals(@Nullable Object obj) {
return Objects.equals(this.privateKey, other.privateKey)
&& Objects.equals(this.privateKeyId, other.privateKeyId)
&& Objects.equals(this.jwtClaims, other.jwtClaims)
&& Objects.equals(this.lifeSpanSeconds, other.lifeSpanSeconds);
&& Objects.equals(this.lifeSpanSeconds, other.lifeSpanSeconds)
&& Objects.equals(this.universeDomain, other.universeDomain);
}

@Override
public int hashCode() {
return Objects.hash(this.privateKey, this.privateKeyId, this.jwtClaims, this.lifeSpanSeconds);
return Objects.hash(
this.privateKey,
this.privateKeyId,
this.jwtClaims,
this.lifeSpanSeconds,
this.universeDomain);
}
Comment on lines 209 to 224

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.

high

To ensure backward compatibility with older serialized instances where universeDomain is deserialized as null, we should treat null as equivalent to Credentials.GOOGLE_DEFAULT_UNIVERSE in both equals and hashCode comparisons.

    String thisUniverse = this.universeDomain == null ? Credentials.GOOGLE_DEFAULT_UNIVERSE : this.universeDomain;
    String otherUniverse = other.universeDomain == null ? Credentials.GOOGLE_DEFAULT_UNIVERSE : other.universeDomain;
    return Objects.equals(this.privateKey, other.privateKey)
        && Objects.equals(this.privateKeyId, other.privateKeyId)
        && Objects.equals(this.jwtClaims, other.jwtClaims)
        && Objects.equals(this.lifeSpanSeconds, other.lifeSpanSeconds)
        && Objects.equals(thisUniverse, otherUniverse);
  }

  @Override
  public int hashCode() {
    String effectiveUniverse = this.universeDomain == null ? Credentials.GOOGLE_DEFAULT_UNIVERSE : this.universeDomain;
    return Objects.hash(
        this.privateKey,
        this.privateKeyId,
        this.jwtClaims,
        this.lifeSpanSeconds,
        effectiveUniverse);
  }
References
  1. When adding a new field to a serializable class that may be null when deserializing older versions, and providing a getter with a default fallback value, ensure that equals() and hashCode() use the getter method (or apply the same fallback logic) rather than accessing the field directly, to maintain consistency between deserialized and newly constructed instances.


Clock getClock() {
Expand All @@ -211,6 +236,7 @@ public static class Builder {
private JwtClaims jwtClaims;
private Clock clock = Clock.SYSTEM;
private Long lifeSpanSeconds = TimeUnit.HOURS.toSeconds(1);
private @Nullable String universeDomain;

protected Builder() {}

Expand Down Expand Up @@ -254,6 +280,24 @@ public Long getLifeSpanSeconds() {
return lifeSpanSeconds;
}

/**
* Sets the universe domain for the credential. If null or blank, defaults to {@link
* Credentials#GOOGLE_DEFAULT_UNIVERSE}.
*
* @param universeDomain the universe domain (for example, {@code googleapis.com})
* @return this builder
*/
@CanIgnoreReturnValue
public Builder setUniverseDomain(@Nullable String universeDomain) {
this.universeDomain = universeDomain;
return this;
}

/** Returns the configured universe domain, or {@code null} if not explicitly set. */
public @Nullable String getUniverseDomain() {
return universeDomain;
}

@CanIgnoreReturnValue
Builder setClock(Clock clock) {
this.clock = Preconditions.checkNotNull(clock);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
package com.google.auth.oauth2;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
Expand All @@ -41,12 +42,18 @@
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.json.webtoken.JsonWebSignature;
import com.google.api.client.util.Clock;
import com.google.auth.Credentials;
import com.google.auth.http.AuthHttpConstants;
import java.io.IOException;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import org.junit.jupiter.api.Test;

class JwtCredentialsTest extends BaseSerializationTest {
Expand Down Expand Up @@ -78,24 +85,16 @@ static PrivateKey getPrivateKey() {

@Test
void serialize() throws IOException, ClassNotFoundException {
JwtClaims claims =
JwtClaims.newBuilder()
.setAudience("some-audience")
.setIssuer("some-issuer")
.setSubject("some-subject")
.build();
JwtCredentials credentials =
JwtCredentials.newBuilder()
.setJwtClaims(claims)
.setPrivateKey(getPrivateKey())
.setPrivateKeyId(PRIVATE_KEY_ID)
.build();
for (String universeDomain : Arrays.asList(null, "example.com")) {
JwtCredentials credentials = createTestBuilder().setUniverseDomain(universeDomain).build();

JwtCredentials deserializedCredentials = serializeAndDeserialize(credentials);
assertEquals(credentials, deserializedCredentials);
assertEquals(credentials.hashCode(), deserializedCredentials.hashCode());
assertEquals(credentials.toString(), deserializedCredentials.toString());
assertSame(Clock.SYSTEM, deserializedCredentials.getClock());
JwtCredentials deserializedCredentials = serializeAndDeserialize(credentials);
assertEquals(credentials, deserializedCredentials);
assertEquals(credentials.hashCode(), deserializedCredentials.hashCode());
assertEquals(credentials.toString(), deserializedCredentials.toString());
assertEquals(credentials.getUniverseDomain(), deserializedCredentials.getUniverseDomain());
assertSame(Clock.SYSTEM, deserializedCredentials.getClock());
}
}

@Test
Expand Down Expand Up @@ -253,6 +252,101 @@ void privateKeyIdNotSpecified() throws IOException {
verifyJwtAccess(metadata, "some-audience", "some-issuer", "some-subject", null);
}

private static JwtClaims createTestClaims() {
return JwtClaims.newBuilder()
.setAudience("some-audience")
.setIssuer("some-issuer")
.setSubject("some-subject")
.build();
}

private static JwtCredentials.Builder createTestBuilder() {
return JwtCredentials.newBuilder()
.setJwtClaims(createTestClaims())
.setPrivateKey(getPrivateKey())
.setPrivateKeyId(PRIVATE_KEY_ID);
}

@Test
void builder_universeDomain() {
JwtCredentials.Builder builder = createTestBuilder();
assertNull(builder.getUniverseDomain());

builder.setUniverseDomain("example.com");
assertEquals("example.com", builder.getUniverseDomain());
}

@Test
void getUniverseDomain() throws IOException {
Map<String, String> testCases = new LinkedHashMap<>();
testCases.put(null, Credentials.GOOGLE_DEFAULT_UNIVERSE);
testCases.put("", Credentials.GOOGLE_DEFAULT_UNIVERSE);
testCases.put(" ", Credentials.GOOGLE_DEFAULT_UNIVERSE);
testCases.put("example.com", "example.com");

for (Map.Entry<String, String> testCase : testCases.entrySet()) {
JwtCredentials credentials = createTestBuilder().setUniverseDomain(testCase.getKey()).build();
assertEquals(testCase.getValue(), credentials.getUniverseDomain());
}
}

@Test
void jwtWithClaims_preservesUniverseDomain() throws IOException {
JwtClaims newClaims = JwtClaims.newBuilder().setAudience("new-audience").build();
for (String universeDomain : Arrays.asList(null, "example.com")) {
JwtCredentials credentials = createTestBuilder().setUniverseDomain(universeDomain).build();
JwtCredentials updated = credentials.jwtWithClaims(newClaims);
assertEquals(credentials.getUniverseDomain(), updated.getUniverseDomain());
}
}

@Test
void equals_true() {
JwtCredentials credentials =
createTestBuilder().setLifeSpanSeconds(600L).setUniverseDomain("example.com").build();
JwtCredentials other =
createTestBuilder().setLifeSpanSeconds(600L).setUniverseDomain("example.com").build();

assertEquals(credentials, credentials);
assertEquals(credentials, other);
assertEquals(other, credentials);
assertEquals(credentials.hashCode(), other.hashCode());
}

@Test
void equals_false() throws NoSuchAlgorithmException {
JwtCredentials baseline =
createTestBuilder().setLifeSpanSeconds(600L).setUniverseDomain("example.com").build();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
PrivateKey otherPrivateKey = keyPairGenerator.generateKeyPair().getPrivate();
JwtClaims otherClaims =
JwtClaims.newBuilder()
.setAudience("other-audience")
.setIssuer("some-issuer")
.setSubject("some-subject")
.build();

List<Consumer<JwtCredentials.Builder>> mutations =
Arrays.asList(
b -> b.setPrivateKey(otherPrivateKey),
b -> b.setPrivateKeyId("other-key-id"),
b -> b.setJwtClaims(otherClaims),
b -> b.setLifeSpanSeconds(1200L),
b -> b.setUniverseDomain("other.example.com"));

assertNotEquals(baseline, null);
assertNotEquals(baseline, "not-a-credential");
for (Consumer<JwtCredentials.Builder> mutation : mutations) {
JwtCredentials.Builder builder =
createTestBuilder().setLifeSpanSeconds(600L).setUniverseDomain("example.com");
mutation.accept(builder);
JwtCredentials other = builder.build();
assertNotEquals(baseline, other);
assertNotEquals(other, baseline);
}
}

private void verifyJwtAccess(
Map<String, List<String>> metadata,
String expectedAudience,
Expand Down
Loading