Skip to content

Commit

Permalink
fix: create and reuse self signed jwt creds for better performance (#…
Browse files Browse the repository at this point in the history
…1154) (#1166)

* fix: create and reuse self signed jwt creds for better performance

* only create jwt cred when needed

Co-authored-by: arithmetic1728 <58957152+arithmetic1728@users.noreply.github.com>
  • Loading branch information
TimurSadykov and arithmetic1728 committed Feb 18, 2023
1 parent f4dd20f commit 87f4cb8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
Expand Up @@ -119,6 +119,8 @@ public class ServiceAccountCredentials extends GoogleCredentials

private transient HttpTransportFactory transportFactory;

private transient JwtCredentials selfSignedJwtCredentialsWithScope = null;

/**
* Internal constructor
*
Expand Down Expand Up @@ -732,6 +734,11 @@ public boolean getUseJwtAccessWithScope() {
return useJwtAccessWithScope;
}

@VisibleForTesting
JwtCredentials getSelfSignedJwtCredentialsWithScope() {
return selfSignedJwtCredentialsWithScope;
}

@Override
public String getAccount() {
return getClientEmail();
Expand Down Expand Up @@ -972,8 +979,11 @@ public Map<String, List<String>> getRequestMetadata(URI uri) throws IOException
// Otherwise, use self signed JWT with uri as the audience.
JwtCredentials jwtCredentials;
if (!createScopedRequired() && useJwtAccessWithScope) {
// Create JWT credentials with the scopes.
jwtCredentials = createSelfSignedJwtCredentials(null);
// Create selfSignedJwtCredentialsWithScope when needed and reuse it for better performance.
if (selfSignedJwtCredentialsWithScope == null) {
selfSignedJwtCredentialsWithScope = createSelfSignedJwtCredentials(null);
}
jwtCredentials = selfSignedJwtCredentialsWithScope;
} else {
// Create JWT credentials with the uri as audience.
jwtCredentials = createSelfSignedJwtCredentials(uri);
Expand Down
Expand Up @@ -1465,6 +1465,7 @@ public void getRequestMetadata_selfSignedJWT_withScopes() throws IOException {
.build();

Map<String, List<String>> metadata = credentials.getRequestMetadata(CALL_URI);
assertNotNull(((ServiceAccountCredentials) credentials).getSelfSignedJwtCredentialsWithScope());
verifyJwtAccess(metadata, "dummy.scope");
}

Expand Down Expand Up @@ -1518,6 +1519,7 @@ public void getRequestMetadata_selfSignedJWT_withAudience() throws IOException {
.build();

Map<String, List<String>> metadata = credentials.getRequestMetadata(CALL_URI);
assertNull(((ServiceAccountCredentials) credentials).getSelfSignedJwtCredentialsWithScope());
verifyJwtAccess(metadata, null);
}

Expand Down

0 comments on commit 87f4cb8

Please sign in to comment.