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)

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

* only create jwt cred when needed
  • Loading branch information
arithmetic1728 authored and TimurSadykov committed Feb 17, 2023
1 parent c1c265c commit 22bfcc2
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 @@ -731,6 +733,11 @@ public boolean getUseJwtAccessWithScope() {
return useJwtAccessWithScope;
}

@VisibleForTesting
JwtCredentials getSelfSignedJwtCredentialsWithScope() {
return selfSignedJwtCredentialsWithScope;
}

@Override
public String getAccount() {
return getClientEmail();
Expand Down Expand Up @@ -971,8 +978,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 @@ -1421,6 +1421,7 @@ 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 @@ -1472,6 +1473,7 @@ 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 22bfcc2

Please sign in to comment.