Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: adds support for 3PI credentials #464

Merged
merged 6 commits into from
Aug 26, 2020
Merged
Show file tree
Hide file tree
Changes from 3 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

Large diffs are not rendered by default.

255 changes: 255 additions & 0 deletions oauth2_http/java/com/google/auth/oauth2/IdentityPoolCredentials.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,255 @@
/*
* Copyright 2020 Google LLC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.google.auth.oauth2;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.JsonObjectParser;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;

/**
* Url-sourced and file-sourced external account credentials.
*
* <p>By default, attempts to exchange the 3PI credential for a GCP access token.
*/
public class IdentityPoolCredentials extends ExternalAccountCredentials {

/**
* The IdentityPool credential source. Dictates the retrieval method of the 3PI credential, which
* can either be through a metadata server or a local file.
*/
@VisibleForTesting
static class IdentityPoolCredentialSource extends CredentialSource {

enum IdentityPoolCredentialSourceType {
FILE,
URL
}

private String credentialLocation;
private IdentityPoolCredentialSourceType credentialSourceType;

@Nullable private Map<String, String> headers;

/**
* The source of the 3P credential.
*
* <p>If the this a file based 3P credential, the credentials file can be retrieved using the
* `file` key.
*
* <p>If this is url-based 3p credential, the metadata server URL can be retrieved using the
lsirac marked this conversation as resolved.
Show resolved Hide resolved
* `url` key.
*
* <p>Optional headers can be present, and should be keyed by `headers`.
*/
public IdentityPoolCredentialSource(Map<String, Object> credentialSourceMap) {
super(credentialSourceMap);

if (credentialSourceMap.containsKey("file")) {
credentialLocation = (String) credentialSourceMap.get("file");
credentialSourceType = IdentityPoolCredentialSourceType.FILE;
} else {
credentialLocation = (String) credentialSourceMap.get("url");
credentialSourceType = IdentityPoolCredentialSourceType.URL;
}
Comment on lines +92 to +95
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we fail early if this input is invalid and doesn't contain file or url?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good question, I'm not sure. The input here should be from a file generated by gCloud, and should be valid.


Map<String, String> headersMap = (Map<String, String>) credentialSourceMap.get("headers");
if (headersMap != null && !headersMap.isEmpty()) {
headers = new HashMap<>();
headers.putAll(headersMap);
}
}

private boolean hasHeaders() {
return headers != null && !headers.isEmpty();
}
}

/**
* Internal constructor. See {@link
* ExternalAccountCredentials#ExternalAccountCredentials(HttpTransportFactory, String, String,
* String, String, CredentialSource, String, String, String, String, Collection)}
*/
IdentityPoolCredentials(
HttpTransportFactory transportFactory,
String audience,
String subjectTokenType,
String tokenUrl,
String tokenInfoUrl,
IdentityPoolCredentialSource credentialSource,
@Nullable String serviceAccountImpersonationUrl,
@Nullable String quotaProjectId,
@Nullable String clientId,
@Nullable String clientSecret,
@Nullable Collection<String> scopes) {
super(
transportFactory,
audience,
subjectTokenType,
tokenUrl,
tokenInfoUrl,
credentialSource,
serviceAccountImpersonationUrl,
quotaProjectId,
clientId,
clientSecret,
scopes);
}

@Override
public AccessToken refreshAccessToken() throws IOException {
String credential = retrieveSubjectToken();
chingor13 marked this conversation as resolved.
Show resolved Hide resolved
StsTokenExchangeRequest.Builder stsTokenExchangeRequest =
StsTokenExchangeRequest.newBuilder(credential, subjectTokenType).setAudience(audience);

if (scopes != null && !scopes.isEmpty()) {
stsTokenExchangeRequest.setScopes(new ArrayList<>(scopes));
}

AccessToken accessToken = exchange3PICredentialForAccessToken(stsTokenExchangeRequest.build());
return attemptServiceAccountImpersonation(accessToken);
}

@Override
public String retrieveSubjectToken() throws IOException {
IdentityPoolCredentialSource identityPoolCredentialSource =
(IdentityPoolCredentialSource) credentialSource;
if (identityPoolCredentialSource.credentialSourceType
== IdentityPoolCredentialSource.IdentityPoolCredentialSourceType.FILE) {
return retrieveSubjectTokenFromCredentialFile();
}
return getSubjectTokenFromMetadataServer();
}

private String retrieveSubjectTokenFromCredentialFile() throws IOException {
IdentityPoolCredentialSource identityPoolCredentialSource =
(IdentityPoolCredentialSource) credentialSource;
String credentialFilePath = identityPoolCredentialSource.credentialLocation;
if (!Files.exists(Paths.get(credentialFilePath), LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Invalid credential location. The file does not exist.");
lsirac marked this conversation as resolved.
Show resolved Hide resolved
}
try {
return new String(Files.readAllBytes(Paths.get(credentialFilePath)));
} catch (IOException e) {
throw new IOException(
"Error when attempting to read the subject token from the credential file.", e);
}
}

private String getSubjectTokenFromMetadataServer() throws IOException {
IdentityPoolCredentialSource identityPoolCredentialSource =
(IdentityPoolCredentialSource) credentialSource;

HttpRequest request =
transportFactory
.create()
.createRequestFactory()
.buildGetRequest(new GenericUrl(identityPoolCredentialSource.credentialLocation));
request.setParser(new JsonObjectParser(OAuth2Utils.JSON_FACTORY));

if (identityPoolCredentialSource.hasHeaders()) {
HttpHeaders headers = new HttpHeaders();
headers.putAll(identityPoolCredentialSource.headers);
request.setHeaders(headers);
}

try {
HttpResponse response = request.execute();
return response.parseAsString();
} catch (IOException e) {
throw new IOException(
String.format("Error getting subject token from metadata server: %s", e.getMessage()), e);
}
}

/** Clones the IdentityPoolCredentials with the specified scopes. */
@Override
public GoogleCredentials createScoped(Collection<String> newScopes) {
return new IdentityPoolCredentials(
transportFactory,
audience,
subjectTokenType,
tokenUrl,
tokenInfoUrl,
(IdentityPoolCredentialSource) credentialSource,
serviceAccountImpersonationUrl,
quotaProjectId,
clientId,
clientSecret,
newScopes);
}

public static Builder newBuilder() {
return new Builder();
}

public static Builder newBuilder(IdentityPoolCredentials identityPoolCredentials) {
return new Builder(identityPoolCredentials);
}

public static class Builder extends ExternalAccountCredentials.Builder {

protected Builder() {}

protected Builder(ExternalAccountCredentials credentials) {
super(credentials);
}

@Override
public IdentityPoolCredentials build() {
return new IdentityPoolCredentials(
transportFactory,
audience,
subjectTokenType,
tokenUrl,
tokenInfoUrl,
(IdentityPoolCredentialSource) credentialSource,
serviceAccountImpersonationUrl,
quotaProjectId,
clientId,
clientSecret,
scopes);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -137,17 +137,15 @@ private GenericData buildTokenRequest() {
GenericData tokenRequest =
new GenericData()
.set("grant_type", TOKEN_EXCHANGE_GRANT_TYPE)
.set("scope", CLOUD_PLATFORM_SCOPE)
.set("subject_token_type", request.getSubjectTokenType())
.set("subject_token", request.getSubjectToken());

// Add scopes as a space-delimited string.
List<String> scopes = new ArrayList<>();
scopes.add(CLOUD_PLATFORM_SCOPE);
if (request.hasScopes()) {
scopes.addAll(request.getScopes());
tokenRequest.set("scope", Joiner.on(' ').join(scopes));
}
tokenRequest.set("scope", Joiner.on(' ').join(scopes));

// Set the requested token type, which defaults to
// urn:ietf:params:oauth:token-type:access_token.
Expand Down
36 changes: 34 additions & 2 deletions oauth2_http/javatests/com/google/auth/TestUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
Expand All @@ -45,17 +47,21 @@
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;

/** Utilities for test code under com.google.auth. */
public class TestUtils {

public static final String UTF_8 = "UTF-8";

private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

public static final String UTF_8 = "UTF-8";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please see comments on original PR


public static void assertContainsBearerToken(Map<String, List<String>> metadata, String token) {
assertNotNull(metadata);
assertNotNull(token);
Expand Down Expand Up @@ -119,5 +125,31 @@ public static String errorJson(String message) throws IOException {
return errorResponse.toPrettyString();
}

public static HttpResponseException buildHttpResponseException(
String error, @Nullable String errorDescription, @Nullable String errorUri)
throws IOException {
GenericJson json = new GenericJson();
json.setFactory(JacksonFactory.getDefaultInstance());
json.set("error", error);
if (errorDescription != null) {
json.set("error_description", errorDescription);
}
if (errorUri != null) {
json.set("error_uri", errorUri);
}
return new HttpResponseException.Builder(
/* statusCode= */ 400, /* statusMessage= */ "statusMessage", new HttpHeaders())
.setContent(json.toPrettyString())
.build();
}

public static String getDefaultExpireTime() {
Date currentDate = new Date();
Calendar c = Calendar.getInstance();
c.setTime(currentDate);
c.add(Calendar.SECOND, 300);
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(c.getTime());
}

private TestUtils() {}
}
Loading