From 22a0ddb2ed6ecdac60d823900b451f5940d39bb4 Mon Sep 17 00:00:00 2001 From: Shaun Ford Date: Mon, 23 Apr 2018 15:40:32 -0700 Subject: [PATCH 1/3] Remove Vault client dependency --- gradle.properties | 2 +- gradle/dependencies.gradle | 10 +- .../client/auth/aws/CerberusClientTest.java | 174 ++++++++ .../client/auth/aws/VaultClientTest.java | 175 -------- .../nike/cerberus/client/CerberusClient.java | 383 ++++++++++++++++++ .../client/CerberusClientException.java | 22 + .../client/CerberusClientFactory.java | 253 ++++++++++++ .../client/CerberusServerException.java | 44 ++ .../nike/cerberus/client/ClientVersion.java | 11 +- .../client/DefaultCerberusClientFactory.java | 78 ++-- .../client/DefaultCerberusUrlResolver.java | 5 +- .../client/StaticCerberusUrlResolver.java | 50 +++ .../com/nike/cerberus/client/UrlResolver.java | 10 + .../client/auth/CerberusCredentials.java | 5 + .../auth/CerberusCredentialsProvider.java | 6 + .../CerberusCredentialsProviderChain.java | 106 +++++ ...faultCerberusCredentialsProviderChain.java | 15 +- ...nvironmentCerberusCredentialsProvider.java | 15 +- ...emPropertyCerberusCredentialsProvider.java | 15 +- .../client/auth/TokenCerberusCredentials.java | 24 ++ .../auth/aws/BaseAwsCredentialsProvider.java | 64 +-- ...tanceRoleCerberusCredentialsProvider.java} | 40 +- ...ambdaRoleCerberusCredentialsProvider.java} | 24 +- ...icIamRoleCerberusCredentialsProvider.java} | 34 +- .../nike/cerberus/client/http/HttpHeader.java | 9 + .../nike/cerberus/client/http/HttpMethod.java | 35 ++ .../nike/cerberus/client/http/HttpStatus.java | 51 +++ .../client/model/CerberusAuthResponse.java | 81 ++++ .../model/CerberusClientTokenResponse.java | 92 +++++ .../client/model/CerberusListResponse.java | 37 ++ .../client/model/CerberusResponse.java | 41 ++ .../client/CerberusClientFactoryTest.java | 136 +++++++ .../cerberus/client/CerberusClientTest.java | 288 +++++++++++++ .../cerberus/client/ClientVersionTest.java | 2 +- .../DefaultCerberusClientFactoryTest.java | 5 +- .../DefaultCerberusUrlResolverTest.java | 1 + .../client/StaticCerberusUrlResolverTest.java | 41 ++ .../CerberusCredentialsProviderChainTest.java | 171 ++++++++ ...tCerberusCredentialsProviderChainTest.java | 5 +- ...onmentCerberusCredentialsProviderTest.java | 9 +- ...opertyCerberusCredentialsProviderTest.java | 9 +- .../auth/TokenCerberusCredentialsTest.java | 36 ++ .../aws/BaseAwsCredentialsProviderTest.java | 16 +- ...eRoleCerberusCredentialsProviderTest.java} | 39 +- ...aRoleCerberusCredentialsProviderTest.java} | 47 ++- ...mRoleCerberusCredentialsProviderTest.java} | 28 +- .../com/nike/cerberus/client/auth.json | 14 + .../com/nike/cerberus/client/error.json | 6 + .../com/nike/cerberus/client/list.json | 9 + .../com/nike/cerberus/client/secret.json | 9 + 50 files changed, 2359 insertions(+), 423 deletions(-) create mode 100644 src/integration/java/com/nike/cerberus/client/auth/aws/CerberusClientTest.java delete mode 100644 src/integration/java/com/nike/cerberus/client/auth/aws/VaultClientTest.java create mode 100644 src/main/java/com/nike/cerberus/client/CerberusClient.java create mode 100644 src/main/java/com/nike/cerberus/client/CerberusClientException.java create mode 100644 src/main/java/com/nike/cerberus/client/CerberusClientFactory.java create mode 100644 src/main/java/com/nike/cerberus/client/CerberusServerException.java create mode 100644 src/main/java/com/nike/cerberus/client/StaticCerberusUrlResolver.java create mode 100644 src/main/java/com/nike/cerberus/client/UrlResolver.java create mode 100644 src/main/java/com/nike/cerberus/client/auth/CerberusCredentials.java create mode 100644 src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProvider.java create mode 100644 src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChain.java create mode 100644 src/main/java/com/nike/cerberus/client/auth/TokenCerberusCredentials.java rename src/main/java/com/nike/cerberus/client/auth/aws/{InstanceRoleVaultCredentialsProvider.java => InstanceRoleCerberusCredentialsProvider.java} (84%) rename src/main/java/com/nike/cerberus/client/auth/aws/{LambdaRoleVaultCredentialsProvider.java => LambdaRoleCerberusCredentialsProvider.java} (83%) rename src/main/java/com/nike/cerberus/client/auth/aws/{StaticIamRoleVaultCredentialsProvider.java => StaticIamRoleCerberusCredentialsProvider.java} (59%) create mode 100644 src/main/java/com/nike/cerberus/client/http/HttpHeader.java create mode 100644 src/main/java/com/nike/cerberus/client/http/HttpMethod.java create mode 100644 src/main/java/com/nike/cerberus/client/http/HttpStatus.java create mode 100644 src/main/java/com/nike/cerberus/client/model/CerberusAuthResponse.java create mode 100644 src/main/java/com/nike/cerberus/client/model/CerberusClientTokenResponse.java create mode 100644 src/main/java/com/nike/cerberus/client/model/CerberusListResponse.java create mode 100644 src/main/java/com/nike/cerberus/client/model/CerberusResponse.java create mode 100644 src/test/java/com/nike/cerberus/client/CerberusClientFactoryTest.java create mode 100644 src/test/java/com/nike/cerberus/client/CerberusClientTest.java create mode 100644 src/test/java/com/nike/cerberus/client/StaticCerberusUrlResolverTest.java create mode 100644 src/test/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChainTest.java create mode 100644 src/test/java/com/nike/cerberus/client/auth/TokenCerberusCredentialsTest.java rename src/test/java/com/nike/cerberus/client/auth/aws/{InstanceRoleVaultCredentialsProviderTest.java => InstanceRoleCerberusCredentialsProviderTest.java} (83%) rename src/test/java/com/nike/cerberus/client/auth/aws/{LambdaRoleVaultCredentialsProviderTest.java => LambdaRoleCerberusCredentialsProviderTest.java} (73%) rename src/test/java/com/nike/cerberus/client/auth/aws/{StaticIamRoleVaultCredentialsProviderTest.java => StaticIamRoleCerberusCredentialsProviderTest.java} (72%) create mode 100644 src/test/resources/com/nike/cerberus/client/auth.json create mode 100644 src/test/resources/com/nike/cerberus/client/error.json create mode 100644 src/test/resources/com/nike/cerberus/client/list.json create mode 100644 src/test/resources/com/nike/cerberus/client/secret.json diff --git a/gradle.properties b/gradle.properties index cd4ef47..58d3b60 100644 --- a/gradle.properties +++ b/gradle.properties @@ -13,6 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # -version=4.3.0 +version=5.0.0 groupId=com.nike artifactId=cerberus-client diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 818cab5..9a4637c 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -19,7 +19,6 @@ repositories { } def AWS_SDK_VERSION = '1.11.123' -def VAULT_CLIENT_COORDINATES = "com.nike:vault-client:2.1.0" //noinspection GroovyAssignabilityCheck dependencies { @@ -35,13 +34,17 @@ dependencies { ***********************************************************************************************************************/ // these will be added to the POM and excluded from the shadow jar - shadow VAULT_CLIENT_COORDINATES - compile VAULT_CLIENT_COORDINATES shadow "joda-time:joda-time:2.8.1" shadow "org.apache.commons:commons-lang3:3.4" shadow "org.slf4j:slf4j-api:1.7.25" + shadow "com.google.code.gson:gson:2.5" + shadow "com.google.code.findbugs:jsr305:3.0.1" compile "com.squareup.okhttp3:okhttp:3.9.0" + compile "org.apache.commons:commons-lang3:3.4" + compile "com.google.code.gson:gson:2.5" + compile "com.google.code.findbugs:jsr305:3.0.1" + compile "org.slf4j:slf4j-api:1.7.25" compile "com.amazonaws:aws-java-sdk-core:${AWS_SDK_VERSION}" compile "com.amazonaws:aws-java-sdk-kms:${AWS_SDK_VERSION}" @@ -60,6 +63,7 @@ dependencies { } testCompile "org.assertj:assertj-core:2.3.0" testCompile "com.squareup.okhttp3:mockwebserver:3.7.0" + testCompile "commons-io:commons-io:2.4" } shadowJar { diff --git a/src/integration/java/com/nike/cerberus/client/auth/aws/CerberusClientTest.java b/src/integration/java/com/nike/cerberus/client/auth/aws/CerberusClientTest.java new file mode 100644 index 0000000..1d2ad03 --- /dev/null +++ b/src/integration/java/com/nike/cerberus/client/auth/aws/CerberusClientTest.java @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2017 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.nike.cerberus.client.auth.aws; + +import com.fieldju.commons.EnvUtils; +import com.nike.cerberus.client.CerberusClient; +import com.nike.cerberus.client.CerberusServerException; +import com.nike.cerberus.client.DefaultCerberusUrlResolver; +import com.nike.cerberus.client.model.CerberusListResponse; +import com.nike.cerberus.client.model.CerberusResponse; +import okhttp3.OkHttpClient; +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Tests StaticIamRoleCerberusCredentialsProvider class + */ +public class CerberusClientTest { + + private static final String ROOT_SDB_PATH = "app/cerberus-integration-tests-sdb/"; + + private static String iam_principal_arn; + private static String region; + + private static String secretPath; + private static String sdbFullSecretPath; + private static Map secretData; + + private static CerberusClient cerberusClient; + + private static StaticIamRoleCerberusCredentialsProvider staticIamRoleCerberusCredentialsProvider; + + @BeforeClass + public static void setUp() { + iam_principal_arn = EnvUtils.getRequiredEnv("TEST_IAM_PRINCIPAL_ARN", "The role to be assume by the integration test"); + region = EnvUtils.getRequiredEnv("TEST_REGION"); + + EnvUtils.getRequiredEnv("CERBERUS_ADDR"); + + secretPath = UUID.randomUUID().toString(); + sdbFullSecretPath = ROOT_SDB_PATH + secretPath; + + String key = RandomStringUtils.randomAlphabetic(15); + String value = RandomStringUtils.randomAlphabetic(25); + secretData = new HashMap<>(); + secretData.put(key, value); + } + + private Map generateNewSecretData() { + String key = RandomStringUtils.randomAlphabetic(20); + String value = RandomStringUtils.randomAlphabetic(30); + Map newSecretData = new HashMap<>(); + newSecretData.put(key, value); + + return newSecretData; + } + + @Test + public void test_cerberus_client_crud_after_auth_with_account_id_and_role_name() { + Pattern arn_pattern = Pattern.compile("arn:aws:iam::(?[0-9].*):role\\/(?.*)"); + Matcher matcher = arn_pattern.matcher(iam_principal_arn); + if (! matcher.matches()) { + throw new AssertionError("IAM Principal ARN does not match expected format"); + } + String account_id = matcher.group("accountId"); + String role_name = matcher.group("roleName"); + + staticIamRoleCerberusCredentialsProvider = new StaticIamRoleCerberusCredentialsProvider( + new DefaultCerberusUrlResolver(), + account_id, + role_name, + region); + + cerberusClient = new CerberusClient(new DefaultCerberusUrlResolver(), + staticIamRoleCerberusCredentialsProvider, new OkHttpClient()); + + // create secret + cerberusClient.write(sdbFullSecretPath, secretData); + + // read secret + CerberusResponse cerberusReadResponse = cerberusClient.read(sdbFullSecretPath); + assertEquals(secretData, cerberusReadResponse.getData()); + + // list secrets + CerberusListResponse cerberusListResponse = cerberusClient.list(ROOT_SDB_PATH); + assertTrue(cerberusListResponse.getKeys().contains(secretPath)); + + // update secret + Map newSecretData = generateNewSecretData(); + cerberusClient.write(sdbFullSecretPath, newSecretData); + secretData = newSecretData; + + // confirm updated secret data + CerberusResponse cerberusReadResponseUpdated = cerberusClient.read(sdbFullSecretPath); + assertEquals(newSecretData, cerberusReadResponseUpdated.getData()); + + // delete secret + cerberusClient.delete(sdbFullSecretPath); + + // confirm secret is deleted + try { + cerberusClient.read(sdbFullSecretPath); + } catch (CerberusServerException cse) { + assertEquals(404, cse.getCode()); + } + } + + @Test + public void test_secret_is_deleted_after_auth_with_iam_principal_name() { + + staticIamRoleCerberusCredentialsProvider = new StaticIamRoleCerberusCredentialsProvider( + new DefaultCerberusUrlResolver(), + iam_principal_arn, + region); + + cerberusClient = new CerberusClient(new DefaultCerberusUrlResolver(), + staticIamRoleCerberusCredentialsProvider, new OkHttpClient()); + + // create secret + cerberusClient.write(sdbFullSecretPath, secretData); + + // read secret + CerberusResponse cerberusReadResponse = cerberusClient.read(sdbFullSecretPath); + assertEquals(secretData, cerberusReadResponse.getData()); + + // list secrets + CerberusListResponse cerberusListResponse = cerberusClient.list(ROOT_SDB_PATH); + assertTrue(cerberusListResponse.getKeys().contains(secretPath)); + + // update secret + Map newSecretData = generateNewSecretData(); + cerberusClient.write(sdbFullSecretPath, newSecretData); + secretData = newSecretData; + + // confirm updated secret data + CerberusResponse cerberusReadResponseUpdated = cerberusClient.read(sdbFullSecretPath); + assertEquals(newSecretData, cerberusReadResponseUpdated.getData()); + + // delete secret + cerberusClient.delete(sdbFullSecretPath); + + // confirm secret is deleted + try { + cerberusClient.read(sdbFullSecretPath); + } catch (CerberusServerException cse) { + assertEquals(404, cse.getCode()); + } + } + +} diff --git a/src/integration/java/com/nike/cerberus/client/auth/aws/VaultClientTest.java b/src/integration/java/com/nike/cerberus/client/auth/aws/VaultClientTest.java deleted file mode 100644 index 11c270b..0000000 --- a/src/integration/java/com/nike/cerberus/client/auth/aws/VaultClientTest.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (c) 2017 Nike, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.nike.cerberus.client.auth.aws; - -import com.fieldju.commons.EnvUtils; -import com.nike.cerberus.client.DefaultCerberusUrlResolver; -import com.nike.vault.client.VaultClient; -import com.nike.vault.client.VaultServerException; -import com.nike.vault.client.model.VaultListResponse; -import com.nike.vault.client.model.VaultResponse; -import okhttp3.OkHttpClient; -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * Tests StaticIamRoleVaultCredentialsProvider class - */ -public class VaultClientTest { - - private static final String ROOT_SDB_PATH = "app/cerberus-integration-tests-sdb/"; - - private static String account_id; - private static String role_name; - private static String iam_principal_arn; - private static String region; - - private static String secretPath; - private static String sdbFullSecretPath; - private static Map secretData; - - private static VaultClient vaultClient; - - private static StaticIamRoleVaultCredentialsProvider staticIamRoleVaultCredentialsProvider; - - @BeforeClass - public static void setUp() { - account_id = EnvUtils.getRequiredEnv("TEST_ACCOUNT_ID", "TEST_ACCOUNT_ID is used to assume a role in the given account"); - role_name = EnvUtils.getRequiredEnv("TEST_ROLE_NAME", "role_name is role to assume to auth with Cerberus"); - region = EnvUtils.getRequiredEnv("TEST_REGION"); - - EnvUtils.getRequiredEnv("CERBERUS_ADDR"); - - iam_principal_arn = String.format("arn:aws:iam::%s:role/%s", account_id, role_name); - secretPath = UUID.randomUUID().toString(); - sdbFullSecretPath = ROOT_SDB_PATH + secretPath; - - String key = RandomStringUtils.randomAlphabetic(15); - String value = RandomStringUtils.randomAlphabetic(25); - secretData = new HashMap<>(); - secretData.put(key, value); - } - - @AfterClass - public static void tearDown() { - vaultClient.delete(sdbFullSecretPath); - } - - private Map generateNewSecretData() { - String key = RandomStringUtils.randomAlphabetic(20); - String value = RandomStringUtils.randomAlphabetic(30); - Map newSecretData = new HashMap<>(); - newSecretData.put(key, value); - - return newSecretData; - } - - @Test - public void test_vault_client_crud_after_auth_with_account_id_and_role_name() { - - staticIamRoleVaultCredentialsProvider = new StaticIamRoleVaultCredentialsProvider( - new DefaultCerberusUrlResolver(), - account_id, - role_name, - region); - - vaultClient = new VaultClient(new DefaultCerberusUrlResolver(), - staticIamRoleVaultCredentialsProvider, new OkHttpClient()); - - // create secret - vaultClient.write(sdbFullSecretPath, secretData); - - // read secret - VaultResponse vaultReadResponse = vaultClient.read(sdbFullSecretPath); - assertEquals(secretData, vaultReadResponse.getData()); - - // list secrets - VaultListResponse vaultListResponse = vaultClient.list(ROOT_SDB_PATH); - assertTrue(vaultListResponse.getKeys().contains(secretPath)); - - // update secret - Map newSecretData = generateNewSecretData(); - vaultClient.write(sdbFullSecretPath, newSecretData); - secretData = newSecretData; - - // confirm updated secret data - VaultResponse vaultReadResponseUpdated = vaultClient.read(sdbFullSecretPath); - assertEquals(newSecretData, vaultReadResponseUpdated.getData()); - - // delete secret - vaultClient.delete(sdbFullSecretPath); - - // confirm secret is deleted - try { - vaultClient.read(sdbFullSecretPath); - } catch (VaultServerException vse) { - assertEquals(404, vse.getCode()); - } - } - - @Test - public void test_secret_is_deleted_after_auth_with_iam_principal_name() { - - staticIamRoleVaultCredentialsProvider = new StaticIamRoleVaultCredentialsProvider( - new DefaultCerberusUrlResolver(), - iam_principal_arn, - region); - - vaultClient = new VaultClient(new DefaultCerberusUrlResolver(), - staticIamRoleVaultCredentialsProvider, new OkHttpClient()); - - // create secret - vaultClient.write(sdbFullSecretPath, secretData); - - // read secret - VaultResponse vaultReadResponse = vaultClient.read(sdbFullSecretPath); - assertEquals(secretData, vaultReadResponse.getData()); - - // list secrets - VaultListResponse vaultListResponse = vaultClient.list(ROOT_SDB_PATH); - assertTrue(vaultListResponse.getKeys().contains(secretPath)); - - // update secret - Map newSecretData = generateNewSecretData(); - vaultClient.write(sdbFullSecretPath, newSecretData); - secretData = newSecretData; - - // confirm updated secret data - VaultResponse vaultReadResponseUpdated = vaultClient.read(sdbFullSecretPath); - assertEquals(newSecretData, vaultReadResponseUpdated.getData()); - - // delete secret - vaultClient.delete(sdbFullSecretPath); - - // confirm secret is deleted - try { - vaultClient.read(sdbFullSecretPath); - } catch (VaultServerException vse) { - assertEquals(404, vse.getCode()); - } - } - -} diff --git a/src/main/java/com/nike/cerberus/client/CerberusClient.java b/src/main/java/com/nike/cerberus/client/CerberusClient.java new file mode 100644 index 0000000..21d3930 --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/CerberusClient.java @@ -0,0 +1,383 @@ +package com.nike.cerberus.client; + +import com.google.gson.FieldNamingPolicy; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonSyntaxException; +import com.google.gson.reflect.TypeToken; +import com.nike.cerberus.client.auth.CerberusCredentialsProvider; +import com.nike.cerberus.client.http.HttpHeader; +import com.nike.cerberus.client.http.HttpMethod; +import com.nike.cerberus.client.http.HttpStatus; +import com.nike.cerberus.client.model.CerberusListResponse; +import com.nike.cerberus.client.model.CerberusResponse; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.SSLException; +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +/** + * Client for interacting with a Cerberus. + */ +public class CerberusClient { + + public static final String SECRET_PATH_PREFIX = "v1/secret/"; + + public static final MediaType DEFAULT_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8"); + + private final CerberusCredentialsProvider credentialsProvider; + + private final OkHttpClient httpClient; + + private final UrlResolver urlResolver; + + private final Headers defaultHeaders; + + private final Gson gson = new GsonBuilder() + .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) + .disableHtmlEscaping() + .create(); + + private final Logger logger = LoggerFactory.getLogger(getClass()); + + public CerberusClient(final UrlResolver cerberusUrlResolver, + final CerberusCredentialsProvider credentialsProvider, + final OkHttpClient httpClient, + final Headers defaultHeaders) { + if (cerberusUrlResolver == null) { + throw new IllegalArgumentException("Cerberus URL resolver cannot be null."); + } + + if (credentialsProvider == null) { + throw new IllegalArgumentException("Credentials provider cannot be null."); + } + + if (httpClient == null) { + throw new IllegalArgumentException("Http client cannot be null."); + } + + if (defaultHeaders == null) { + throw new IllegalArgumentException("Default headers cannot be null."); + } + + this.urlResolver = cerberusUrlResolver; + this.credentialsProvider = credentialsProvider; + this.httpClient = httpClient; + this.defaultHeaders = defaultHeaders; + } + + /** + * Explicit constructor that allows for full control over construction of the Cerberus client. + * + * @param cerberusUrlResolver URL resolver for Cerberus + * @param credentialsProvider Credential provider for acquiring a token for interacting with Cerberus + * @param httpClient HTTP client for calling Cerberus + */ + public CerberusClient(final UrlResolver cerberusUrlResolver, + final CerberusCredentialsProvider credentialsProvider, + final OkHttpClient httpClient) { + if (cerberusUrlResolver == null) { + throw new IllegalArgumentException("Cerberus URL resolver can not be null."); + } + + if (credentialsProvider == null) { + throw new IllegalArgumentException("Credentials provider can not be null."); + } + + if (httpClient == null) { + throw new IllegalArgumentException("Http client can not be null."); + } + + this.urlResolver = cerberusUrlResolver; + this.credentialsProvider = credentialsProvider; + this.httpClient = httpClient; + this.defaultHeaders = new Headers.Builder().build(); + } + + /** + * List operation for the specified path. Will return a {@link Map} with a single entry of keys which is an + * array of strings that represents the keys at that path. If Cerberus returns an unexpected response code, a + * {@link CerberusServerException} will be thrown with the code and error details. If an unexpected I/O error is + * encountered, a {@link CerberusClientException} will be thrown wrapping the underlying exception. + *

+ * See https://www.cerberusproject.io/docs/secrets/generic/index.html for details on what the list operation returns. + *

+ * + * @param path Path to the data + * @return Map containing the keys at that path + */ + public CerberusListResponse list(final String path) { + final HttpUrl url = buildUrl(SECRET_PATH_PREFIX, path + "?list=true"); + logger.debug("list: requestUrl={}", url); + + final Response response = execute(url, HttpMethod.GET, null); + + if (response.code() == HttpStatus.NOT_FOUND) { + response.close(); + return new CerberusListResponse(); + } else if (response.code() != HttpStatus.OK) { + parseAndThrowErrorResponse(response); + } + + final Type mapType = new TypeToken>() { + }.getType(); + final Map rootData = parseResponseBody(response, mapType); + return gson.fromJson(gson.toJson(rootData.get("data")), CerberusListResponse.class); + } + + /** + * Read operation for a specified path. Will return a {@link Map} of the data stored at the specified path. + * If Cerberus returns an unexpected response code, a {@link CerberusServerException} will be thrown with the code + * and error details. If an unexpected I/O error is encountered, a {@link CerberusClientException} will be thrown + * wrapping the underlying exception. + * + * @param path Path to the data + * @return Map of the data + */ + public CerberusResponse read(final String path) { + final HttpUrl url = buildUrl(SECRET_PATH_PREFIX, path); + logger.debug("read: requestUrl={}", url); + + final Response response = execute(url, HttpMethod.GET, null); + + if (response.code() != HttpStatus.OK) { + parseAndThrowErrorResponse(response); + } + + return parseResponseBody(response, CerberusResponse.class); + } + + /** + * Write operation for a specified path and data set. If Cerberus returns an unexpected response code, a + * {@link CerberusServerException} will be thrown with the code and error details. If an unexpected I/O + * error is encountered, a {@link CerberusClientException} will be thrown wrapping the underlying exception. + * + * @param path Path for where to store the data + * @param data Data to be stored + */ + public void write(final String path, final Map data) { + final HttpUrl url = buildUrl(SECRET_PATH_PREFIX, path); + logger.debug("write: requestUrl={}", url); + + final Response response = execute(url, HttpMethod.POST, data); + + if (response.code() != HttpStatus.NO_CONTENT) { + parseAndThrowErrorResponse(response); + } + } + + /** + * Delete operation for a specified path. If Cerberus returns an unexpected response code, a + * {@link CerberusServerException} will be thrown with the code and error details. If an unexpected I/O + * error is encountered, a {@link CerberusClientException} will be thrown wrapping the underlying exception. + * + * @param path Path to data to be deleted + */ + public void delete(final String path) { + final HttpUrl url = buildUrl(SECRET_PATH_PREFIX, path); + logger.debug("delete: requestUrl={}", url); + + final Response response = execute(url, HttpMethod.DELETE, null); + + if (response.code() != HttpStatus.NO_CONTENT) { + parseAndThrowErrorResponse(response); + } + } + + /** + * Returns a copy of the URL being used for communicating with Cerberus + * + * @return Copy of the HttpUrl object + */ + public HttpUrl getCerberusUrl() { + return HttpUrl.parse(urlResolver.resolve()); + } + + /** + * Returns the configured credentials provider. + * + * @return The configured credentials provider + */ + public CerberusCredentialsProvider getCredentialsProvider() { + return credentialsProvider; + } + + /** + * Gets the Gson object used for serializing and de-serializing requests. + * + * @return Gson object + */ + public Gson getGson() { + return gson; + } + + /** + * Returns the configured default HTTP headers. + * + * @return The configured default HTTP headers + */ + public Headers getDefaultHeaders() { + return defaultHeaders; + } + + /** + * Builds the full URL for preforming an operation against Cerberus. + * + * @param prefix Prefix between the environment URL and specified path + * @param path Path for the requested operation + * @return Full URL to execute a request against + */ + protected HttpUrl buildUrl(final String prefix, final String path) { + String baseUrl = urlResolver.resolve(); + + if (!StringUtils.endsWith(baseUrl, "/")) { + baseUrl += "/"; + } + + return HttpUrl.parse(baseUrl + prefix + path); + } + + /** + * Executes the HTTP request based on the input parameters. + * + * @param url The URL to execute the request against + * @param method The HTTP method for the request + * @param requestBody The request body of the HTTP request + * @return Response from the server + */ + protected Response execute(final HttpUrl url, final String method, final Object requestBody) { + try { + Request request = buildRequest(url, method, requestBody); + + return httpClient.newCall(request).execute(); + } catch (IOException e) { + if (e instanceof SSLException + && e.getMessage() != null + && e.getMessage().contains("Unrecognized SSL message, plaintext connection?")) { + throw new CerberusClientException("I/O error while communicating with Cerberus. Unrecognized SSL message may be due to a web proxy e.g. AnyConnect", e); + } else { + throw new CerberusClientException("I/O error while communicating with Cerberus.", e); + } + } + } + + /** + * Build the HTTP request to execute for the Cerberus Client + * @param url The URL to execute the request against + * @param method The HTTP method for the request + * @param requestBody The request body of the HTTP request + * @return - The HTTP request + */ + protected Request buildRequest(final HttpUrl url, final String method, final Object requestBody) { + Request.Builder requestBuilder = new Request.Builder() + .url(url) + .headers(defaultHeaders) // call headers method first because it overwrites all existing headers + .addHeader(HttpHeader.CERBERUS_TOKEN, credentialsProvider.getCredentials().getToken()) + .addHeader(HttpHeader.ACCEPT, DEFAULT_MEDIA_TYPE.toString()); + + if (requestBody != null) { + requestBuilder.addHeader(HttpHeader.CONTENT_TYPE, DEFAULT_MEDIA_TYPE.toString()) + .method(method, RequestBody.create(DEFAULT_MEDIA_TYPE, gson.toJson(requestBody))); + } else { + requestBuilder.method(method, null); + } + + return requestBuilder.build(); + } + + + /** + * Convenience method for parsing the HTTP response and mapping it to a class. + * + * @param response The HTTP response object + * @param responseClass The class to map the response body to + * @param Represents the type to map to + * @return Deserialized object from the response body + */ + protected M parseResponseBody(final Response response, final Class responseClass) { + final String responseBodyStr = responseBodyAsString(response); + try { + return gson.fromJson(responseBodyStr, responseClass); + } catch (JsonSyntaxException e) { + logger.error("parseResponseBody: responseCode={}, requestUrl={}, response={}", + response.code(), response.request().url(), responseBodyStr); + throw new CerberusClientException("Error parsing the response body from Cerberus, response code: " + response.code(), e); + } + } + + /** + * Convenience method for parsing the HTTP response and mapping it to a type. + * + * @param response The HTTP response object + * @param typeOf The type to map the response body to + * @param Represents the type to map to + * @return Deserialized object from the response body + */ + protected M parseResponseBody(final Response response, final Type typeOf) { + final String responseBodyStr = responseBodyAsString(response); + try { + return gson.fromJson(responseBodyStr, typeOf); + } catch (JsonSyntaxException e) { + logger.error("parseResponseBody: responseCode={}, requestUrl={}, response={}", + response.code(), response.request().url(), responseBodyStr); + throw new CerberusClientException("Error parsing the response body from Cerberus, response code: " + response.code(), e); + } + } + + /** + * Convenience method for parsing the errors from the HTTP response and throwing a {@link CerberusServerException}. + * + * @param response Response to parses the error details from + */ + protected void parseAndThrowErrorResponse(final Response response) { + final String responseBodyStr = responseBodyAsString(response); + logger.debug("parseAndThrowErrorResponse: responseCode={}, requestUrl={}, response={}", + response.code(), response.request().url(), responseBodyStr); + + try { + ErrorResponse errorResponse = gson.fromJson(responseBodyStr, ErrorResponse.class); + + if (errorResponse != null) { + throw new CerberusServerException(response.code(), errorResponse.getErrors()); + } else { + throw new CerberusServerException(response.code(), new LinkedList()); + } + } catch (JsonSyntaxException e) { + logger.error("ERROR Failed to parse error message, response body received: {}", responseBodyStr); + throw new CerberusClientException("Error parsing the error response body from Cerberus, response code: " + response.code(), e); + } + } + + /** + * POJO for representing error response body from Cerberus. + */ + protected static class ErrorResponse { + private List errors; + + public List getErrors() { + return errors; + } + } + + protected String responseBodyAsString(Response response) { + try { + return response.body().string(); + } catch (IOException ioe) { + logger.debug("responseBodyAsString: response={}", gson.toJson(response)); + return "ERROR failed to print response body as str: " + ioe.getMessage(); + } + } +} diff --git a/src/main/java/com/nike/cerberus/client/CerberusClientException.java b/src/main/java/com/nike/cerberus/client/CerberusClientException.java new file mode 100644 index 0000000..f484f68 --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/CerberusClientException.java @@ -0,0 +1,22 @@ +package com.nike.cerberus.client; + +public class CerberusClientException extends RuntimeException { + /** + * Constructs the exception with a message and underlying exception. + * + * @param message Message + * @param t Underlying exception + */ + public CerberusClientException(String message, Throwable t) { + super(message, t); + } + + /** + * Constructs the exception with a message. + * + * @param message Message + */ + public CerberusClientException(String message) { + super(message); + } +} diff --git a/src/main/java/com/nike/cerberus/client/CerberusClientFactory.java b/src/main/java/com/nike/cerberus/client/CerberusClientFactory.java new file mode 100644 index 0000000..dacf2a9 --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/CerberusClientFactory.java @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2016 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.nike.cerberus.client; + +import com.nike.cerberus.client.auth.CerberusCredentialsProvider; +import com.nike.cerberus.client.auth.DefaultCerberusCredentialsProviderChain; +import okhttp3.ConnectionSpec; +import okhttp3.Dispatcher; +import okhttp3.Headers; +import okhttp3.OkHttpClient; +import okhttp3.TlsVersion; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static okhttp3.ConnectionSpec.CLEARTEXT; +import static okhttp3.ConnectionSpec.MODERN_TLS; + +/** + * Convenience factory for creating instances of Cerberus clients. + */ +public class CerberusClientFactory { + + public static final int DEFAULT_TIMEOUT = 15_000; + public static final TimeUnit DEFAULT_TIMEOUT_UNIT = TimeUnit.MILLISECONDS; + + /** + * Modify "MODERN_TLS" to remove TLS v1.0 and 1.1 + */ + public static final ConnectionSpec TLS_1_2_OR_NEWER = new ConnectionSpec.Builder(MODERN_TLS) + .tlsVersions(TlsVersion.TLS_1_3, TlsVersion.TLS_1_2) + .build(); + + /** + * A CerberusClient may need to make many requests to Cerberus simultaneously. + *

+ * (Default value in OkHttpClient for maxRequests was 64 and maxRequestsPerHost was 5). + */ + private static final int DEFAULT_MAX_REQUESTS = 200; + private static final Map DEFAULT_HEADERS = new HashMap<>(); + + /** + * Basic factory method that will build a Cerberus client that + * looks up the Cerberus URL from one of the following places: + *

    + *
  • Environment Variable - CERBERUS_ADDR
  • + *
  • Java System Property - cerberus.addr
  • + *
+ * Default recommended credential provider and http client are used. + * + * @return Cerberus client + */ + public static CerberusClient getClient() { + return getClient(new DefaultCerberusUrlResolver(), + new DefaultCerberusCredentialsProviderChain(), + new HashMap()); + } + + /** + * Factory method allows setting of the Cerberus URL resolver, but will use + * the default recommended credentials provider chain and http client. + * + * @param cerberusUrlResolver URL resolver for Cerberus + * @return Cerberus client + */ + public static CerberusClient getClient(final UrlResolver cerberusUrlResolver) { + return getClient(cerberusUrlResolver, new DefaultCerberusCredentialsProviderChain(), DEFAULT_HEADERS); + } + + /** + * Factory method that allows for a user defined Cerberus URL resolver and credentials provider. + * + * @param cerberusUrlResolver URL resolver for Cerberus + * @param cerberusCredentialsProvider Credential provider for acquiring a token for interacting with Cerberus + * @return Cerberus client + */ + public static CerberusClient getClient(final UrlResolver cerberusUrlResolver, + final CerberusCredentialsProvider cerberusCredentialsProvider) { + return getClient(cerberusUrlResolver, cerberusCredentialsProvider, DEFAULT_HEADERS); + } + + /** + * Factory method that allows a user to define default HTTP defaultHeaders to be added to every HTTP request made from the + * CerberusClient. The user can also define their Cerberus URL resolver and credentials provider. + * + * @param cerberusUrlResolver URL resolver for Cerberus + * @param cerberusCredentialsProvider Credential provider for acquiring a token for interacting with Cerberus + * @param defaultHeaders Map of default header names and values to add to every HTTP request + * @return Cerberus client + */ + public static CerberusClient getClient(final UrlResolver cerberusUrlResolver, + final CerberusCredentialsProvider cerberusCredentialsProvider, + final Map defaultHeaders) { + + List connectionSpecs = new ArrayList<>(); + connectionSpecs.add(TLS_1_2_OR_NEWER); + // for unit tests + connectionSpecs.add(CLEARTEXT); + + return getClient( + cerberusUrlResolver, + cerberusCredentialsProvider, + defaultHeaders, + new OkHttpClient.Builder() + .connectTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT) + .writeTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT) + .readTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT) + .connectionSpecs(connectionSpecs) + .build() + ); + } + + /** + * Factory method that allows for a user defined Cerberus URL resolver and credentials provider. + * + * @param cerberusUrlResolver URL resolver for Cerberus + * @param cerberusCredentialsProvider Credential provider for acquiring a token for interacting with Cerberus + * @param maxRequestsPerHost Max Requests per Host used by the dispatcher + * @return Cerberus admin client + */ + public static CerberusClient getClient(final UrlResolver cerberusUrlResolver, + final CerberusCredentialsProvider cerberusCredentialsProvider, + final int maxRequestsPerHost) { + return getClient(cerberusUrlResolver, + cerberusCredentialsProvider, + DEFAULT_MAX_REQUESTS, + maxRequestsPerHost, + DEFAULT_TIMEOUT, + DEFAULT_TIMEOUT, + DEFAULT_TIMEOUT, + DEFAULT_HEADERS); + } + + /** + * Factory method that allows a user to define the OkHttpClient to be used. + * + * @param cerberusUrlResolver URL resolver for Cerberus + * @param cerberusCredentialsProvider Credential provider for acquiring a token for interacting with Cerberus + * @param defaultHeaders Map of default header names and values to add to every HTTP request + * @param httpClient + * @return Cerberus client + */ + public static CerberusClient getClient(final UrlResolver cerberusUrlResolver, + final CerberusCredentialsProvider cerberusCredentialsProvider, + final Map defaultHeaders, + final OkHttpClient httpClient) { + if (defaultHeaders == null) { + throw new IllegalArgumentException("Default headers cannot be null."); + } + + Headers.Builder headers = new Headers.Builder(); + for (Map.Entry header : defaultHeaders.entrySet()) { + headers.add(header.getKey(), header.getValue()); + } + + return new CerberusClient(cerberusUrlResolver, + cerberusCredentialsProvider, + httpClient, + headers.build()); + } + + /** + * Factory method that allows the user to completely configure the CerberusClient. + * + * @param cerberusUrlResolver URL resolver for Cerberus + * @param cerberusCredentialsProvider Credential provider for acquiring a token for interacting with Cerberus + * @param maxRequestsPerHost Max Requests per Host used by the dispatcher + * @param defaultHeaders Map of default header names and values to add to every HTTP request + * @return Cerberus admin client + */ + public static CerberusClient getClient(final UrlResolver cerberusUrlResolver, + final CerberusCredentialsProvider cerberusCredentialsProvider, + final int maxRequestsPerHost, + final Map defaultHeaders) { + return getClient(cerberusUrlResolver, + cerberusCredentialsProvider, + DEFAULT_MAX_REQUESTS, + maxRequestsPerHost, + DEFAULT_TIMEOUT, + DEFAULT_TIMEOUT, + DEFAULT_TIMEOUT, + defaultHeaders); + } + + /** + * Factory method that allows the user to completely configure the CerberusClient. + * + * @param cerberusUrlResolver URL resolver for Cerberus + * @param cerberusCredentialsProvider Credential provider for acquiring a token for interacting with Cerberus + * @param maxRequests Max HTTP Requests allowed in-flight + * @param maxRequestsPerHost Max HTTP Requests per Host + * @param connectTimeoutMillis HTTP connect timeout in milliseconds + * @param readTimeoutMillis HTTP read timeout in milliseconds + * @param writeTimeoutMillis HTTP write timeout in milliseconds + * @param defaultHeaders Map of default header names and values to add to every HTTP request + * @return Cerberus admin client + */ + public static CerberusClient getClient(final UrlResolver cerberusUrlResolver, + final CerberusCredentialsProvider cerberusCredentialsProvider, + final int maxRequests, + final int maxRequestsPerHost, + final int connectTimeoutMillis, + final int readTimeoutMillis, + final int writeTimeoutMillis, + final Map defaultHeaders) { + if (defaultHeaders == null) { + throw new IllegalArgumentException("Default headers cannot be null."); + } + + Dispatcher dispatcher = new Dispatcher(); + dispatcher.setMaxRequests(maxRequests); + dispatcher.setMaxRequestsPerHost(maxRequestsPerHost); + + + List connectionSpecs = new ArrayList<>(); + connectionSpecs.add(TLS_1_2_OR_NEWER); + // for unit tests + connectionSpecs.add(CLEARTEXT); + + Headers.Builder headers = new Headers.Builder(); + for (Map.Entry header : defaultHeaders.entrySet()) { + headers.add(header.getKey(), header.getValue()); + } + + return new CerberusClient(cerberusUrlResolver, + cerberusCredentialsProvider, + new OkHttpClient.Builder() + .connectTimeout(connectTimeoutMillis, DEFAULT_TIMEOUT_UNIT) + .writeTimeout(writeTimeoutMillis, DEFAULT_TIMEOUT_UNIT) + .readTimeout(readTimeoutMillis, DEFAULT_TIMEOUT_UNIT) + .dispatcher(dispatcher) + .connectionSpecs(connectionSpecs) + .build(), + headers.build()); + } +} diff --git a/src/main/java/com/nike/cerberus/client/CerberusServerException.java b/src/main/java/com/nike/cerberus/client/CerberusServerException.java new file mode 100644 index 0000000..e7a3c07 --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/CerberusServerException.java @@ -0,0 +1,44 @@ +package com.nike.cerberus.client; + +import org.apache.commons.lang3.StringUtils; + +import java.util.List; + +public class CerberusServerException extends CerberusClientException { + private static final String MESSAGE_FORMAT = "Response Code: %s, Messages: %s"; + private static final long serialVersionUID = 2096457341910045171L; + + private final int code; + + private final List errors; + + /** + * Construction of the exception with the specified code and error message list. + * + * @param code HTTP response code + * @param errors List of error messages + */ + public CerberusServerException(final int code, final List errors) { + super(String.format(MESSAGE_FORMAT, code, StringUtils.join(errors, ", "))); + this.code = code; + this.errors = errors; + } + + /** + * Returns the HTTP response code + * + * @return HTTP response code + */ + public int getCode() { + return code; + } + + /** + * Returns the list of error messages. + * + * @return Error messages + */ + public List getErrors() { + return errors; + } +} diff --git a/src/main/java/com/nike/cerberus/client/ClientVersion.java b/src/main/java/com/nike/cerberus/client/ClientVersion.java index f3f4f23..8e237b2 100644 --- a/src/main/java/com/nike/cerberus/client/ClientVersion.java +++ b/src/main/java/com/nike/cerberus/client/ClientVersion.java @@ -54,15 +54,6 @@ public static String getVersion() { } public static String getClientHeaderValue() { - - String vaultClientVersion = "unknown"; - - try { - vaultClientVersion = com.nike.vault.client.ClientVersion.getVersion(); - } catch (Exception e) { - LOGGER.error("Failed to get Vault Client version", e); - } - - return String.format("%s/%s JavaVaultClient/%s", HEADER_VALUE_PREFIX, getVersion(), vaultClientVersion); + return String.format("%s/%s", HEADER_VALUE_PREFIX, getVersion()); } } diff --git a/src/main/java/com/nike/cerberus/client/DefaultCerberusClientFactory.java b/src/main/java/com/nike/cerberus/client/DefaultCerberusClientFactory.java index 697cec1..a98f086 100644 --- a/src/main/java/com/nike/cerberus/client/DefaultCerberusClientFactory.java +++ b/src/main/java/com/nike/cerberus/client/DefaultCerberusClientFactory.java @@ -16,16 +16,12 @@ package com.nike.cerberus.client; +import com.nike.cerberus.client.auth.CerberusCredentialsProviderChain; import com.nike.cerberus.client.auth.DefaultCerberusCredentialsProviderChain; import com.nike.cerberus.client.auth.EnvironmentCerberusCredentialsProvider; import com.nike.cerberus.client.auth.SystemPropertyCerberusCredentialsProvider; -import com.nike.cerberus.client.auth.aws.LambdaRoleVaultCredentialsProvider; -import com.nike.cerberus.client.auth.aws.StaticIamRoleVaultCredentialsProvider; -import com.nike.vault.client.StaticVaultUrlResolver; -import com.nike.vault.client.UrlResolver; -import com.nike.vault.client.VaultClient; -import com.nike.vault.client.VaultClientFactory; -import com.nike.vault.client.auth.VaultCredentialsProviderChain; +import com.nike.cerberus.client.auth.aws.LambdaRoleCerberusCredentialsProvider; +import com.nike.cerberus.client.auth.aws.StaticIamRoleCerberusCredentialsProvider; import okhttp3.ConnectionSpec; import okhttp3.OkHttpClient; @@ -37,41 +33,41 @@ import java.util.Map; /** - * Client factory for creating a Vault client with a URL resolver and credentials provider specific to Cerberus. + * Client factory for creating a Cerberus client with a URL resolver and credentials provider specific to Cerberus. */ public final class DefaultCerberusClientFactory { /** - * Creates a new {@link VaultClient} with the {@link DefaultCerberusUrlResolver} for URL resolving + * Creates a new {@link CerberusClient} with the {@link DefaultCerberusUrlResolver} for URL resolving * and {@link DefaultCerberusCredentialsProviderChain} for obtaining credentials. * - * @return Vault client + * @return Cerberus client */ - public static VaultClient getClient() { + public static CerberusClient getClient() { final Map defaultHeaders = new HashMap<>(); defaultHeaders.put(ClientVersion.CERBERUS_CLIENT_HEADER, ClientVersion.getClientHeaderValue()); - return VaultClientFactory.getClient( + return CerberusClientFactory.getClient( new DefaultCerberusUrlResolver(), new DefaultCerberusCredentialsProviderChain(), defaultHeaders); } /** - * Creates a new {@link VaultClient} for the supplied Cerberus URL + * Creates a new {@link CerberusClient} for the supplied Cerberus URL * and {@link DefaultCerberusCredentialsProviderChain} for obtaining credentials. * * @param cerberusUrl e.g. https://dev.cerberus.example.com - * @return Vault client + * @return Cerberus client */ - public static VaultClient getClient(String cerberusUrl) { + public static CerberusClient getClient(String cerberusUrl) { final Map defaultHeaders = new HashMap<>(); defaultHeaders.put(ClientVersion.CERBERUS_CLIENT_HEADER, ClientVersion.getClientHeaderValue()); - UrlResolver urlResolver = new StaticVaultUrlResolver(cerberusUrl); + UrlResolver urlResolver = new StaticCerberusUrlResolver(cerberusUrl); - return VaultClientFactory.getClient( + return CerberusClientFactory.getClient( urlResolver, new DefaultCerberusCredentialsProviderChain(urlResolver), defaultHeaders); @@ -79,7 +75,7 @@ public static VaultClient getClient(String cerberusUrl) { } /** - * Creates a new {@link VaultClient} with the specified SSLSocketFactory and TrustManager. + * Creates a new {@link CerberusClient} with the specified SSLSocketFactory and TrustManager. *

* This factory method is generally not recommended unless you have a specific need * to configure your TLS for your httpClient differently than the default, e.g. Java 7. @@ -87,27 +83,27 @@ public static VaultClient getClient(String cerberusUrl) { * @param cerberusUrl e.g. https://dev.cerberus.example.com * @param sslSocketFactory the factory to use for TLS * @param trustManager the trust manager to use for TLS - * @return Vault client + * @return Cerberus client */ - public static VaultClient getClient(String cerberusUrl, SSLSocketFactory sslSocketFactory, X509TrustManager trustManager) { + public static CerberusClient getClient(String cerberusUrl, SSLSocketFactory sslSocketFactory, X509TrustManager trustManager) { final Map defaultHeaders = new HashMap<>(); defaultHeaders.put(ClientVersion.CERBERUS_CLIENT_HEADER, ClientVersion.getClientHeaderValue()); - UrlResolver urlResolver = new StaticVaultUrlResolver(cerberusUrl); + UrlResolver urlResolver = new StaticCerberusUrlResolver(cerberusUrl); List connectionSpecs = new ArrayList<>(); - connectionSpecs.add(VaultClientFactory.TLS_1_2_OR_NEWER); + connectionSpecs.add(CerberusClientFactory.TLS_1_2_OR_NEWER); OkHttpClient httpClient = new OkHttpClient.Builder() - .connectTimeout(VaultClientFactory.DEFAULT_TIMEOUT, VaultClientFactory.DEFAULT_TIMEOUT_UNIT) - .writeTimeout(VaultClientFactory.DEFAULT_TIMEOUT, VaultClientFactory.DEFAULT_TIMEOUT_UNIT) - .readTimeout(VaultClientFactory.DEFAULT_TIMEOUT, VaultClientFactory.DEFAULT_TIMEOUT_UNIT) + .connectTimeout(CerberusClientFactory.DEFAULT_TIMEOUT, CerberusClientFactory.DEFAULT_TIMEOUT_UNIT) + .writeTimeout(CerberusClientFactory.DEFAULT_TIMEOUT, CerberusClientFactory.DEFAULT_TIMEOUT_UNIT) + .readTimeout(CerberusClientFactory.DEFAULT_TIMEOUT, CerberusClientFactory.DEFAULT_TIMEOUT_UNIT) .sslSocketFactory(sslSocketFactory, trustManager) .connectionSpecs(connectionSpecs) .build(); - return VaultClientFactory.getClient( + return CerberusClientFactory.getClient( urlResolver, new DefaultCerberusCredentialsProviderChain(urlResolver, httpClient), defaultHeaders, @@ -115,8 +111,8 @@ public static VaultClient getClient(String cerberusUrl, SSLSocketFactory sslSock } /** - * Creates a new {@link VaultClient} for the supplied Cerberus URL and a credentials provider chain - * that includes the {@link StaticIamRoleVaultCredentialsProvider} for obtaining credentials. + * Creates a new {@link CerberusClient} for the supplied Cerberus URL and a credentials provider chain + * that includes the {@link StaticIamRoleCerberusCredentialsProvider} for obtaining credentials. *

* This method is used when you want to use a particular iamPrincipalArn during authentication rather * than auto-determining the ARN to use. Generally, it is simpler to use the {@code getClient()} or the @@ -126,43 +122,43 @@ public static VaultClient getClient(String cerberusUrl, SSLSocketFactory sslSock * @param cerberusUrl e.g. https://dev.cerberus.example.com * @param iamPrincipalArn the IAM principal to use in authentication, e.g. "arn:aws:iam::123456789012:role/some-role" * @param region the Region for the KMS key used in auth. Usually, this is your current region. - * @return Vault client + * @return Cerberus client */ - public static VaultClient getClient(String cerberusUrl, String iamPrincipalArn, String region) { + public static CerberusClient getClient(String cerberusUrl, String iamPrincipalArn, String region) { final Map defaultHeaders = new HashMap<>(); defaultHeaders.put(ClientVersion.CERBERUS_CLIENT_HEADER, ClientVersion.getClientHeaderValue()); - UrlResolver urlResolver = new StaticVaultUrlResolver(cerberusUrl); + UrlResolver urlResolver = new StaticCerberusUrlResolver(cerberusUrl); - return VaultClientFactory.getClient( + return CerberusClientFactory.getClient( urlResolver, - new VaultCredentialsProviderChain( + new CerberusCredentialsProviderChain( new EnvironmentCerberusCredentialsProvider(), new SystemPropertyCerberusCredentialsProvider(), - new StaticIamRoleVaultCredentialsProvider(urlResolver, iamPrincipalArn, region)), + new StaticIamRoleCerberusCredentialsProvider(urlResolver, iamPrincipalArn, region)), defaultHeaders); } /** - * Creates a new {@link VaultClient} with the {@link DefaultCerberusUrlResolver} for URL resolving - * and a credentials provider chain that includes the {@link LambdaRoleVaultCredentialsProvider} for obtaining + * Creates a new {@link CerberusClient} with the {@link DefaultCerberusUrlResolver} for URL resolving + * and a credentials provider chain that includes the {@link LambdaRoleCerberusCredentialsProvider} for obtaining * credentials. * * @param invokedFunctionArn The ARN for the AWS Lambda function being invoked. - * @return Vault client + * @return Cerberus client */ - public static VaultClient getClientForLambda(final String invokedFunctionArn) { + public static CerberusClient getClientForLambda(final String invokedFunctionArn) { final Map defaultHeaders = new HashMap<>(); defaultHeaders.put(ClientVersion.CERBERUS_CLIENT_HEADER, ClientVersion.getClientHeaderValue()); final DefaultCerberusUrlResolver urlResolver = new DefaultCerberusUrlResolver(); - return VaultClientFactory.getClient( + return CerberusClientFactory.getClient( urlResolver, - new VaultCredentialsProviderChain( + new CerberusCredentialsProviderChain( new EnvironmentCerberusCredentialsProvider(), new SystemPropertyCerberusCredentialsProvider(), - new LambdaRoleVaultCredentialsProvider(urlResolver, invokedFunctionArn)), + new LambdaRoleCerberusCredentialsProvider(urlResolver, invokedFunctionArn)), defaultHeaders); } } diff --git a/src/main/java/com/nike/cerberus/client/DefaultCerberusUrlResolver.java b/src/main/java/com/nike/cerberus/client/DefaultCerberusUrlResolver.java index fb6fc7a..ac0e710 100644 --- a/src/main/java/com/nike/cerberus/client/DefaultCerberusUrlResolver.java +++ b/src/main/java/com/nike/cerberus/client/DefaultCerberusUrlResolver.java @@ -16,7 +16,6 @@ package com.nike.cerberus.client; -import com.nike.vault.client.UrlResolver; import okhttp3.HttpUrl; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -36,9 +35,9 @@ public class DefaultCerberusUrlResolver implements UrlResolver { private final Logger logger = LoggerFactory.getLogger(getClass()); /** - * Attempts to acquire the Vault URL from Archaius. + * Attempts to acquire the Cerberus URL from Archaius. * - * @return Vault URL + * @return Cerberus URL */ @Nullable @Override diff --git a/src/main/java/com/nike/cerberus/client/StaticCerberusUrlResolver.java b/src/main/java/com/nike/cerberus/client/StaticCerberusUrlResolver.java new file mode 100644 index 0000000..ecc1945 --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/StaticCerberusUrlResolver.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2016 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.nike.cerberus.client; + +import org.apache.commons.lang3.StringUtils; + +/** + * Wrapper for the URL resolver interface for a static URL. + */ +public class StaticCerberusUrlResolver implements UrlResolver { + + private final String cerberusUrl; + + /** + * Explicit constructor for holding a static Cerberus URL. + * + * @param cerberusUrl Cerberus URL + */ + public StaticCerberusUrlResolver(final String cerberusUrl) { + if (StringUtils.isBlank(cerberusUrl)) { + throw new IllegalArgumentException("Cerberus URL can not be blank."); + } + + this.cerberusUrl = cerberusUrl; + } + + /** + * Returns a static Cerberus URL. + * + * @return Cerberus URL + */ + @Override + public String resolve() { + return cerberusUrl; + } +} diff --git a/src/main/java/com/nike/cerberus/client/UrlResolver.java b/src/main/java/com/nike/cerberus/client/UrlResolver.java new file mode 100644 index 0000000..d597d24 --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/UrlResolver.java @@ -0,0 +1,10 @@ +package com.nike.cerberus.client; + +public interface UrlResolver { + /** + * Resolves the URL for the Cerberus instance. + * + * @return Cerberus URL + */ + String resolve(); +} diff --git a/src/main/java/com/nike/cerberus/client/auth/CerberusCredentials.java b/src/main/java/com/nike/cerberus/client/auth/CerberusCredentials.java new file mode 100644 index 0000000..9574366 --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/auth/CerberusCredentials.java @@ -0,0 +1,5 @@ +package com.nike.cerberus.client.auth; + +public interface CerberusCredentials { + String getToken(); +} diff --git a/src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProvider.java b/src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProvider.java new file mode 100644 index 0000000..fda708e --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProvider.java @@ -0,0 +1,6 @@ +package com.nike.cerberus.client.auth; + + +public interface CerberusCredentialsProvider { + CerberusCredentials getCredentials(); +} diff --git a/src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChain.java b/src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChain.java new file mode 100644 index 0000000..4da2d4d --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChain.java @@ -0,0 +1,106 @@ +package com.nike.cerberus.client.auth; + +import com.nike.cerberus.client.CerberusClientException; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +public class CerberusCredentialsProviderChain implements CerberusCredentialsProvider { + private static final Logger LOGGER = LoggerFactory.getLogger(CerberusCredentialsProviderChain.class); + + private final List credentialsProviderList = new LinkedList<>(); + + private boolean reuseLastProvider = true; + private CerberusCredentialsProvider lastUsedProvider; + + /** + * Explicit constructor that takes a list of providers to use. + * + * @param credentialsProviderList List of providers + */ + public CerberusCredentialsProviderChain(final List credentialsProviderList) { + if (credentialsProviderList == null || credentialsProviderList.size() == 0) { + throw new IllegalArgumentException("No credentials providers specified"); + } + + this.credentialsProviderList.addAll(credentialsProviderList); + } + + /** + * Explicit constructor that takes an array of providers to use. + * + * @param credentialsProviders Array of providers + */ + public CerberusCredentialsProviderChain(final CerberusCredentialsProvider... credentialsProviders) { + if (credentialsProviders == null || credentialsProviders.length == 0) { + throw new IllegalArgumentException("No credentials providers specified"); + } + + Collections.addAll(this.credentialsProviderList, credentialsProviders); + } + + /** + * Iterates over the chain of providers looking for one that returns credentials. If this is a subsequent call + * to the method and a successful provider has already be identified, that identified provider will be used instead + * of iterating over the full chain. This is the default behavior and can be disabled via + * {@link #setReuseLastProvider(boolean)}. If no provider is able to acquire credentials a client exception is + * thrown. + * + * @return Credentials + */ + @Override + public CerberusCredentials getCredentials() { + if (reuseLastProvider && lastUsedProvider != null) { + return lastUsedProvider.getCredentials(); + } + + for (final CerberusCredentialsProvider credentialsProvider : credentialsProviderList) { + try { + final CerberusCredentials credentials = credentialsProvider.getCredentials(); + + if (StringUtils.isNotBlank(credentials.getToken())) { + lastUsedProvider = credentialsProvider; + return credentials; + } + } catch (CerberusClientException sce) { + if(LOGGER.isDebugEnabled()) { + LOGGER.debug("Failed to resolve Cerberus credentials with credential provider: {}. Moving " + + "on to next provider", credentialsProvider.getClass().toString(), sce); + } else { + LOGGER.info("Failed to resolve Cerberus credentials with credential provider: {} for reason: {} moving " + + "on to next provider", credentialsProvider.getClass().toString(), sce.getMessage()); + } + } catch (Exception e) { + // The catch all is so that we don't break the chain of providers. + // If we do get an unexpected exception, we should at least log it for review. + LOGGER.warn("Unexpected error attempting to get credentials with provider: " + + credentialsProvider.getClass().getName(), e); + } + } + + throw new CerberusClientException("Unable to find credentials from any provider in the specified chain!"); + } + + + /** + * Returns the reuse last provider flag. + * + * @return reuse last provider flag + */ + public boolean isReuseLastProvider() { + return reuseLastProvider; + } + + /** + * Enables the ability to enable or disable the reuse of the last successful provider. + * + * @param reuseLastProvider Flag for usage of the last successful provider + */ + public void setReuseLastProvider(final boolean reuseLastProvider) { + this.reuseLastProvider = reuseLastProvider; + } +} diff --git a/src/main/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChain.java b/src/main/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChain.java index 3c1b6c0..fd846e9 100644 --- a/src/main/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChain.java +++ b/src/main/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChain.java @@ -17,9 +17,8 @@ package com.nike.cerberus.client.auth; import com.nike.cerberus.client.DefaultCerberusUrlResolver; -import com.nike.cerberus.client.auth.aws.InstanceRoleVaultCredentialsProvider; -import com.nike.vault.client.UrlResolver; -import com.nike.vault.client.auth.VaultCredentialsProviderChain; +import com.nike.cerberus.client.UrlResolver; +import com.nike.cerberus.client.auth.aws.InstanceRoleCerberusCredentialsProvider; import okhttp3.OkHttpClient; /** @@ -33,9 +32,9 @@ * * @see EnvironmentCerberusCredentialsProvider * @see SystemPropertyCerberusCredentialsProvider - * @see InstanceRoleVaultCredentialsProvider + * @see InstanceRoleCerberusCredentialsProvider */ -public class DefaultCerberusCredentialsProviderChain extends VaultCredentialsProviderChain { +public class DefaultCerberusCredentialsProviderChain extends CerberusCredentialsProviderChain { /** * Default constructor that sets up a default provider chain. @@ -52,7 +51,7 @@ public DefaultCerberusCredentialsProviderChain() { public DefaultCerberusCredentialsProviderChain(UrlResolver urlResolver) { super(new EnvironmentCerberusCredentialsProvider(), new SystemPropertyCerberusCredentialsProvider(), - new InstanceRoleVaultCredentialsProvider(urlResolver)); + new InstanceRoleCerberusCredentialsProvider(urlResolver)); } /** @@ -65,7 +64,7 @@ public DefaultCerberusCredentialsProviderChain(UrlResolver urlResolver) { public DefaultCerberusCredentialsProviderChain(UrlResolver urlResolver, OkHttpClient httpClient) { super(new EnvironmentCerberusCredentialsProvider(), new SystemPropertyCerberusCredentialsProvider(), - new InstanceRoleVaultCredentialsProvider(urlResolver, httpClient)); + new InstanceRoleCerberusCredentialsProvider(urlResolver, httpClient)); } /** @@ -86,6 +85,6 @@ public DefaultCerberusCredentialsProviderChain(String xCerberusClientOverride) { public DefaultCerberusCredentialsProviderChain(UrlResolver urlResolver, String xCerberusClientOverride) { super(new EnvironmentCerberusCredentialsProvider(), new SystemPropertyCerberusCredentialsProvider(), - new InstanceRoleVaultCredentialsProvider(urlResolver, xCerberusClientOverride)); + new InstanceRoleCerberusCredentialsProvider(urlResolver, xCerberusClientOverride)); } } diff --git a/src/main/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProvider.java b/src/main/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProvider.java index bda0483..b762528 100644 --- a/src/main/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProvider.java +++ b/src/main/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProvider.java @@ -16,17 +16,14 @@ package com.nike.cerberus.client.auth; -import com.nike.vault.client.VaultClientException; -import com.nike.vault.client.auth.TokenVaultCredentials; -import com.nike.vault.client.auth.VaultCredentials; -import com.nike.vault.client.auth.VaultCredentialsProvider; +import com.nike.cerberus.client.CerberusClientException; import org.apache.commons.lang3.StringUtils; /** - * {@link VaultCredentialsProvider} implementation that attempts to acquire the token + * {@link CerberusCredentialsProvider} implementation that attempts to acquire the token * via the environment variable, CERBERUS_TOKEN. */ -public class EnvironmentCerberusCredentialsProvider implements VaultCredentialsProvider { +public class EnvironmentCerberusCredentialsProvider implements CerberusCredentialsProvider { public static final String CERBERUS_TOKEN_ENV_PROPERTY = "CERBERUS_TOKEN"; @@ -36,13 +33,13 @@ public class EnvironmentCerberusCredentialsProvider implements VaultCredentialsP * @return credentials */ @Override - public VaultCredentials getCredentials() { + public CerberusCredentials getCredentials() { final String token = System.getenv(CERBERUS_TOKEN_ENV_PROPERTY); if (StringUtils.isNotBlank(token)) { - return new TokenVaultCredentials(token); + return new TokenCerberusCredentials(token); } - throw new VaultClientException("Cerberus token not found in the environment property: " + CERBERUS_TOKEN_ENV_PROPERTY); + throw new CerberusClientException("Cerberus token not found in the environment property: " + CERBERUS_TOKEN_ENV_PROPERTY); } } diff --git a/src/main/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProvider.java b/src/main/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProvider.java index 602e0fc..d663609 100644 --- a/src/main/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProvider.java +++ b/src/main/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProvider.java @@ -16,17 +16,14 @@ package com.nike.cerberus.client.auth; -import com.nike.vault.client.VaultClientException; -import com.nike.vault.client.auth.TokenVaultCredentials; -import com.nike.vault.client.auth.VaultCredentials; -import com.nike.vault.client.auth.VaultCredentialsProvider; +import com.nike.cerberus.client.CerberusClientException; import org.apache.commons.lang3.StringUtils; /** - * {@link VaultCredentialsProvider} implementation that attempts to acquire the token + * {@link CerberusCredentialsProvider} implementation that attempts to acquire the token * via the system property, cerberus.token. */ -public class SystemPropertyCerberusCredentialsProvider implements VaultCredentialsProvider { +public class SystemPropertyCerberusCredentialsProvider implements CerberusCredentialsProvider { public static final String CERBERUS_TOKEN_SYS_PROPERTY = "cerberus.token"; @@ -36,13 +33,13 @@ public class SystemPropertyCerberusCredentialsProvider implements VaultCredentia * @return credentials */ @Override - public VaultCredentials getCredentials() { + public CerberusCredentials getCredentials() { final String token = System.getProperty(CERBERUS_TOKEN_SYS_PROPERTY); if (StringUtils.isNotBlank(token)) { - return new TokenVaultCredentials(token); + return new TokenCerberusCredentials(token); } - throw new VaultClientException("Cerberus token not found in the java system property: " + CERBERUS_TOKEN_SYS_PROPERTY); + throw new CerberusClientException("Cerberus token not found in the java system property: " + CERBERUS_TOKEN_SYS_PROPERTY); } } diff --git a/src/main/java/com/nike/cerberus/client/auth/TokenCerberusCredentials.java b/src/main/java/com/nike/cerberus/client/auth/TokenCerberusCredentials.java new file mode 100644 index 0000000..36d330f --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/auth/TokenCerberusCredentials.java @@ -0,0 +1,24 @@ +package com.nike.cerberus.client.auth; + +public class TokenCerberusCredentials implements CerberusCredentials { + private final String token; + + /** + * Explicit constructor that sets the token. + * + * @param token Token to represent + */ + public TokenCerberusCredentials(final String token) { + this.token = token; + } + + /** + * Returns the token set during construction. + * + * @return Token + */ + @Override + public String getToken() { + return token; + } +} diff --git a/src/main/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProvider.java b/src/main/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProvider.java index d6a0a1a..cde474e 100644 --- a/src/main/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProvider.java +++ b/src/main/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProvider.java @@ -27,17 +27,17 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; +import com.nike.cerberus.client.CerberusClientException; +import com.nike.cerberus.client.CerberusServerException; import com.nike.cerberus.client.ClientVersion; -import com.nike.vault.client.UrlResolver; -import com.nike.vault.client.VaultClientException; -import com.nike.vault.client.VaultServerException; -import com.nike.vault.client.auth.TokenVaultCredentials; -import com.nike.vault.client.auth.VaultCredentials; -import com.nike.vault.client.auth.VaultCredentialsProvider; -import com.nike.vault.client.http.HttpHeader; -import com.nike.vault.client.http.HttpMethod; -import com.nike.vault.client.http.HttpStatus; -import com.nike.vault.client.model.VaultAuthResponse; +import com.nike.cerberus.client.UrlResolver; +import com.nike.cerberus.client.auth.CerberusCredentials; +import com.nike.cerberus.client.auth.CerberusCredentialsProvider; +import com.nike.cerberus.client.auth.TokenCerberusCredentials; +import com.nike.cerberus.client.http.HttpHeader; +import com.nike.cerberus.client.http.HttpMethod; +import com.nike.cerberus.client.http.HttpStatus; +import com.nike.cerberus.client.model.CerberusAuthResponse; import okhttp3.ConnectionSpec; import okhttp3.MediaType; import okhttp3.OkHttpClient; @@ -61,20 +61,20 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; -import static com.nike.cerberus.client.auth.aws.StaticIamRoleVaultCredentialsProvider.IAM_ROLE_ARN_FORMAT; -import static com.nike.vault.client.VaultClientFactory.DEFAULT_TIMEOUT; -import static com.nike.vault.client.VaultClientFactory.DEFAULT_TIMEOUT_UNIT; -import static com.nike.vault.client.VaultClientFactory.TLS_1_2_OR_NEWER; +import static com.nike.cerberus.client.CerberusClientFactory.DEFAULT_TIMEOUT; +import static com.nike.cerberus.client.CerberusClientFactory.DEFAULT_TIMEOUT_UNIT; +import static com.nike.cerberus.client.CerberusClientFactory.TLS_1_2_OR_NEWER; +import static com.nike.cerberus.client.auth.aws.StaticIamRoleCerberusCredentialsProvider.IAM_ROLE_ARN_FORMAT; import static okhttp3.ConnectionSpec.CLEARTEXT; /** - * {@link VaultCredentialsProvider} implementation that uses some AWS + * {@link CerberusCredentialsProvider} implementation that uses some AWS * credentials provider to authenticate with Cerberus and decrypt the auth * response using KMS. If the assigned role has been granted the appropriate - * provisioned for usage of Vault, it will succeed and have a token that can be - * used to interact with Vault. + * provisioned for usage of Cerberus, it will succeed and have a token that can be + * used to interact with Cerberus. */ -public abstract class BaseAwsCredentialsProvider implements VaultCredentialsProvider { +public abstract class BaseAwsCredentialsProvider implements CerberusCredentialsProvider { public static final MediaType DEFAULT_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8"); @@ -91,7 +91,7 @@ public abstract class BaseAwsCredentialsProvider implements VaultCredentialsProv protected final int paddingTimeInSeconds = 60; - protected volatile TokenVaultCredentials credentials; + protected volatile TokenCerberusCredentials credentials; protected volatile DateTime expireDateTime = DateTime.now().minus(paddingTimeInSeconds); @@ -150,13 +150,13 @@ public BaseAwsCredentialsProvider(UrlResolver urlResolver, OkHttpClient httpClie } /** - * Returns the Vault credentials. If none have been acquired yet or has + * Returns the Cerberus credentials. If none have been acquired yet or has * expired, triggers a refresh. * - * @return Vault credentials + * @return Cerberus credentials */ @Override - public VaultCredentials getCredentials() { + public CerberusCredentials getCredentials() { readLock.lock(); try { boolean needsToAuthenticate = false; @@ -182,7 +182,7 @@ public VaultCredentials getCredentials() { } } - return new TokenVaultCredentials(credentials.getToken()); + return new TokenCerberusCredentials(credentials.getToken()); } finally { readLock.unlock(); } @@ -218,11 +218,11 @@ protected void getAndSetToken(final String iamPrincipalArn, final Region region) kmsClient.setRegion(region); final String encryptedAuthData = getEncryptedAuthData(iamPrincipalArn, region); - final VaultAuthResponse decryptedToken = decryptToken(kmsClient, encryptedAuthData); + final CerberusAuthResponse decryptedToken = decryptToken(kmsClient, encryptedAuthData); final DateTime expires = DateTime.now(DateTimeZone.UTC) .plusSeconds(decryptedToken.getLeaseDuration() - paddingTimeInSeconds); - credentials = new TokenVaultCredentials(decryptedToken.getClientToken()); + credentials = new TokenCerberusCredentials(decryptedToken.getClientToken()); expireDateTime = expires; } @@ -237,7 +237,7 @@ protected String getEncryptedAuthData(final String iamPrincipalArn, Region regio final String url = urlResolver.resolve(); if (StringUtils.isBlank(url)) { - throw new VaultClientException("Unable to find the Vault URL."); + throw new CerberusClientException("Unable to find the Cerberus URL."); } LOGGER.info(String.format("Attempting to authenticate with AWS IAM principal ARN [%s] against [%s]", @@ -266,10 +266,10 @@ protected String getEncryptedAuthData(final String iamPrincipalArn, Region regio iamPrincipalArn, url)); return authData.get(key); } else { - throw new VaultClientException("Success response from IAM role authenticate endpoint missing auth data!"); + throw new CerberusClientException("Success response from IAM role authenticate endpoint missing auth data!"); } } catch (IOException e) { - throw new VaultClientException("I/O error while communicating with Cerberus", e); + throw new CerberusClientException("I/O error while communicating with Cerberus", e); } } @@ -281,13 +281,13 @@ protected String getEncryptedAuthData(final String iamPrincipalArn, Region regio * @param encryptedToken Token to decode and decrypt * @return Decrypted token */ - protected VaultAuthResponse decryptToken(AWSKMS kmsClient, String encryptedToken) { + protected CerberusAuthResponse decryptToken(AWSKMS kmsClient, String encryptedToken) { byte[] decodedToken; try { decodedToken = Base64.decode(encryptedToken); } catch (IllegalArgumentException iae) { - throw new VaultClientException("Encrypted token not Base64 encoded", iae); + throw new CerberusClientException("Encrypted token not Base64 encoded", iae); } final DecryptRequest request = new DecryptRequest().withCiphertextBlob(ByteBuffer.wrap(decodedToken)); @@ -295,7 +295,7 @@ protected VaultAuthResponse decryptToken(AWSKMS kmsClient, String encryptedToken final String decryptedAuthData = new String(result.getPlaintext().array(), Charset.forName("UTF-8")); - return gson.fromJson(decryptedAuthData, VaultAuthResponse.class); + return gson.fromJson(decryptedAuthData, CerberusAuthResponse.class); } private RequestBody buildCredentialsRequestBody(final String iamPrincipalArn, Region region) { @@ -313,7 +313,7 @@ private void parseAndThrowErrorResponse(final int responseCode, final String res LOGGER.warn(message); List errors = new ArrayList<>(1); errors.add(message); - throw new VaultServerException(responseCode, errors); + throw new CerberusServerException(responseCode, errors); } private OkHttpClient createHttpClient() { diff --git a/src/main/java/com/nike/cerberus/client/auth/aws/InstanceRoleVaultCredentialsProvider.java b/src/main/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProvider.java similarity index 84% rename from src/main/java/com/nike/cerberus/client/auth/aws/InstanceRoleVaultCredentialsProvider.java rename to src/main/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProvider.java index b75e3de..345ba43 100644 --- a/src/main/java/com/nike/cerberus/client/auth/aws/InstanceRoleVaultCredentialsProvider.java +++ b/src/main/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProvider.java @@ -21,9 +21,9 @@ import com.amazonaws.regions.Regions; import com.amazonaws.util.EC2MetadataUtils; import com.google.gson.JsonSyntaxException; -import com.nike.vault.client.UrlResolver; -import com.nike.vault.client.VaultClientException; -import com.nike.vault.client.auth.VaultCredentialsProvider; +import com.nike.cerberus.client.CerberusClientException; +import com.nike.cerberus.client.UrlResolver; +import com.nike.cerberus.client.auth.CerberusCredentialsProvider; import okhttp3.OkHttpClient; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -34,23 +34,23 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import static com.nike.cerberus.client.auth.aws.StaticIamRoleVaultCredentialsProvider.IAM_ROLE_ARN_FORMAT; +import static com.nike.cerberus.client.auth.aws.StaticIamRoleCerberusCredentialsProvider.IAM_ROLE_ARN_FORMAT; /** - * {@link VaultCredentialsProvider} implementation that uses the assigned role + * {@link CerberusCredentialsProvider} implementation that uses the assigned role * to an EC2 instance to authenticate with Cerberus and decrypt the auth * response using KMS. If the assigned role has been granted the appropriate - * provisioned for usage of Vault, it will succeed and have a token that can be - * used to interact with Vault. + * provisioned for usage of Cerberus, it will succeed and have a token that can be + * used to interact with Cerberus. *

* This class uses the AWS Instance Metadata endpoint to look-up information automatically. * * @see AWS Instance Metadata */ -public class InstanceRoleVaultCredentialsProvider extends BaseAwsCredentialsProvider { +public class InstanceRoleCerberusCredentialsProvider extends BaseAwsCredentialsProvider { - private static final Logger LOGGER = LoggerFactory.getLogger(InstanceRoleVaultCredentialsProvider.class); + private static final Logger LOGGER = LoggerFactory.getLogger(InstanceRoleCerberusCredentialsProvider.class); public static final Pattern IAM_ARN_PATTERN = Pattern.compile("(arn\\:aws\\:iam\\:\\:)(?[0-9].*)(\\:.*)"); @@ -62,7 +62,7 @@ public class InstanceRoleVaultCredentialsProvider extends BaseAwsCredentialsProv * * @param urlResolver Resolver for resolving the Cerberus URL */ - public InstanceRoleVaultCredentialsProvider(UrlResolver urlResolver) { + public InstanceRoleCerberusCredentialsProvider(UrlResolver urlResolver) { super(urlResolver); } @@ -73,7 +73,7 @@ public InstanceRoleVaultCredentialsProvider(UrlResolver urlResolver) { * @param urlResolver Resolver for resolving the Cerberus URL * @param httpClient the client for interacting with Cerberus */ - public InstanceRoleVaultCredentialsProvider(UrlResolver urlResolver, OkHttpClient httpClient) { + public InstanceRoleCerberusCredentialsProvider(UrlResolver urlResolver, OkHttpClient httpClient) { super(urlResolver, httpClient); } @@ -84,14 +84,14 @@ public InstanceRoleVaultCredentialsProvider(UrlResolver urlResolver, OkHttpClien * @param urlResolver Resolver for resolving the Cerberus URL * @param xCerberusClientOverride Overrides the default header value for the 'X-Cerberus-Client' header */ - public InstanceRoleVaultCredentialsProvider(UrlResolver urlResolver, String xCerberusClientOverride) { + public InstanceRoleCerberusCredentialsProvider(UrlResolver urlResolver, String xCerberusClientOverride) { super(urlResolver, xCerberusClientOverride); } /** * Looks up the IAM roles assigned to the instance via the EC2 metadata * service. For each role assigned, an attempt is made to authenticate and - * decrypt the Vault auth response with KMS. If successful, the token + * decrypt the Cerberus auth response with KMS. If successful, the token * retrieved is cached locally for future calls to * {@link BaseAwsCredentialsProvider#getCredentials()}. */ @@ -106,8 +106,8 @@ protected void authenticate() { try { getAndSetToken(iamRole, region); return; - } catch (VaultClientException sce) { - LOGGER.warn("Unable to acquire Vault token for IAM role: " + iamRole + ", instance profile was " + instanceProfileArn, sce); + } catch (CerberusClientException sce) { + LOGGER.warn("Unable to acquire Cerberus token for IAM role: " + iamRole + ", instance profile was " + instanceProfileArn, sce); } } } catch (AmazonClientException ace) { @@ -116,7 +116,7 @@ protected void authenticate() { LOGGER.error("The decrypted auth response was not in the expected format!", jse); } - throw new VaultClientException("Unable to acquire token with EC2 instance role."); + throw new CerberusClientException("Unable to acquire token with EC2 instance role."); } /** @@ -135,7 +135,7 @@ protected String lookupAccountId() { } } - throw new VaultClientException("Unable to obtain AWS account ID from instance profile ARN."); + throw new CerberusClientException("Unable to obtain AWS account ID from instance profile ARN."); } protected String getInstanceProfileArn() { @@ -144,7 +144,7 @@ protected String getInstanceProfileArn() { if (iamInfo == null) { final String errorMessage = "No IAM Instance Profile assigned to running instance."; LOGGER.error(errorMessage); - throw new VaultClientException(errorMessage); + throw new CerberusClientException(errorMessage); } return iamInfo.instanceProfileArn; } @@ -185,14 +185,14 @@ protected static Set buildIamRoleArns(String instanceProfileArn, Set[a-zA-Z0-9-]+):(?[0-9]{12}):function:(?[a-zA-Z0-9-_]+)(:(?.*))?"); @@ -62,7 +62,7 @@ public class LambdaRoleVaultCredentialsProvider extends BaseAwsCredentialsProvid * @param urlResolver Resolver for resolving the Cerberus URL * @param invokedFunctionArn The invoked lambda function's ARN */ - public LambdaRoleVaultCredentialsProvider(final UrlResolver urlResolver, final String invokedFunctionArn) { + public LambdaRoleCerberusCredentialsProvider(final UrlResolver urlResolver, final String invokedFunctionArn) { super(urlResolver); final Matcher matcher = LAMBDA_FUNCTION_ARN_PATTERN.matcher(invokedFunctionArn); @@ -110,11 +110,11 @@ protected void authenticate() { LOGGER.warn("Unexpected error communicating with AWS services.", ace); } catch (JsonSyntaxException jse) { LOGGER.error("The decrypted auth response was not in the expected format!", jse); - } catch (VaultClientException sce) { - LOGGER.warn("Unable to acquire Vault token for IAM role: " + roleArn, sce); + } catch (CerberusClientException sce) { + LOGGER.warn("Unable to acquire Cerberus token for IAM role: " + roleArn, sce); } - throw new VaultClientException("Unable to acquire token with Lambda instance role."); + throw new CerberusClientException("Unable to acquire token with Lambda instance role."); } diff --git a/src/main/java/com/nike/cerberus/client/auth/aws/StaticIamRoleVaultCredentialsProvider.java b/src/main/java/com/nike/cerberus/client/auth/aws/StaticIamRoleCerberusCredentialsProvider.java similarity index 59% rename from src/main/java/com/nike/cerberus/client/auth/aws/StaticIamRoleVaultCredentialsProvider.java rename to src/main/java/com/nike/cerberus/client/auth/aws/StaticIamRoleCerberusCredentialsProvider.java index 389bc65..e0656d9 100644 --- a/src/main/java/com/nike/cerberus/client/auth/aws/StaticIamRoleVaultCredentialsProvider.java +++ b/src/main/java/com/nike/cerberus/client/auth/aws/StaticIamRoleCerberusCredentialsProvider.java @@ -18,69 +18,69 @@ import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; -import com.nike.vault.client.StaticVaultUrlResolver; -import com.nike.vault.client.UrlResolver; +import com.nike.cerberus.client.StaticCerberusUrlResolver; +import com.nike.cerberus.client.UrlResolver; /** - * Provider for allowing users to explicitly set the account id, rolename and region that they want to authenticate as. + * Provider for allowing users to explicitly set the account id, role name and region that they want to authenticate as. */ -public class StaticIamRoleVaultCredentialsProvider extends BaseAwsCredentialsProvider { +public class StaticIamRoleCerberusCredentialsProvider extends BaseAwsCredentialsProvider { public static final String IAM_ROLE_ARN_FORMAT = "arn:aws:iam::%s:role/%s"; protected String iamPrincipalArn; protected Region region; - public StaticIamRoleVaultCredentialsProvider(UrlResolver urlResolver, String accountId, String roleName, String region) { + public StaticIamRoleCerberusCredentialsProvider(UrlResolver urlResolver, String accountId, String roleName, String region) { this(urlResolver); this.iamPrincipalArn = generateIamRoleArn(accountId, roleName); this.region = Region.getRegion(Regions.fromName(region)); } - public StaticIamRoleVaultCredentialsProvider(String vaultUrl, String accountId, String roleName, String region) { - this(new StaticVaultUrlResolver(vaultUrl)); + public StaticIamRoleCerberusCredentialsProvider(String cerberusUrl, String accountId, String roleName, String region) { + this(new StaticCerberusUrlResolver(cerberusUrl)); this.iamPrincipalArn = generateIamRoleArn(accountId, roleName); this.region = Region.getRegion(Regions.fromName(region)); } - public StaticIamRoleVaultCredentialsProvider(UrlResolver urlResolver, String accountId, String roleName, Region region) { + public StaticIamRoleCerberusCredentialsProvider(UrlResolver urlResolver, String accountId, String roleName, Region region) { this(urlResolver); this.iamPrincipalArn = generateIamRoleArn(accountId, roleName); this.region = region; } - public StaticIamRoleVaultCredentialsProvider(String vaultUrl, String accountId, String roleName, Region region) { - this(new StaticVaultUrlResolver(vaultUrl)); + public StaticIamRoleCerberusCredentialsProvider(String cerberusUrl, String accountId, String roleName, Region region) { + this(new StaticCerberusUrlResolver(cerberusUrl)); this.iamPrincipalArn = generateIamRoleArn(accountId, roleName); this.region = region; } - public StaticIamRoleVaultCredentialsProvider(UrlResolver urlResolver, String iamRoleArn, String region) { + public StaticIamRoleCerberusCredentialsProvider(UrlResolver urlResolver, String iamRoleArn, String region) { this(urlResolver); this.iamPrincipalArn = iamRoleArn; this.region = Region.getRegion(Regions.fromName(region)); } - public StaticIamRoleVaultCredentialsProvider(String vaultUrl, String iamRoleArn, String region) { - this(new StaticVaultUrlResolver(vaultUrl)); + public StaticIamRoleCerberusCredentialsProvider(String cerberusUrl, String iamRoleArn, String region) { + this(new StaticCerberusUrlResolver(cerberusUrl)); this.iamPrincipalArn = iamRoleArn; this.region = Region.getRegion(Regions.fromName(region)); } - public StaticIamRoleVaultCredentialsProvider(UrlResolver urlResolver, String iamRoleArn, Region region) { + public StaticIamRoleCerberusCredentialsProvider(UrlResolver urlResolver, String iamRoleArn, Region region) { this(urlResolver); this.iamPrincipalArn = iamRoleArn; this.region = region; } - public StaticIamRoleVaultCredentialsProvider(String vaultUrl, String iamRoleArn, Region region) { - this(new StaticVaultUrlResolver(vaultUrl)); + public StaticIamRoleCerberusCredentialsProvider(String cerberusUrl, String iamRoleArn, Region region) { + this(new StaticCerberusUrlResolver(cerberusUrl)); this.iamPrincipalArn = iamRoleArn; this.region = region; } - private StaticIamRoleVaultCredentialsProvider(UrlResolver urlResolver) { + private StaticIamRoleCerberusCredentialsProvider(UrlResolver urlResolver) { super(urlResolver); } diff --git a/src/main/java/com/nike/cerberus/client/http/HttpHeader.java b/src/main/java/com/nike/cerberus/client/http/HttpHeader.java new file mode 100644 index 0000000..cea087e --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/http/HttpHeader.java @@ -0,0 +1,9 @@ +package com.nike.cerberus.client.http; + +public class HttpHeader { + public static final String CERBERUS_TOKEN = "X-Cerberus-Token"; + + public static final String ACCEPT = "Accept"; + + public static final String CONTENT_TYPE = "Content-Type"; +} diff --git a/src/main/java/com/nike/cerberus/client/http/HttpMethod.java b/src/main/java/com/nike/cerberus/client/http/HttpMethod.java new file mode 100644 index 0000000..2cfb92f --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/http/HttpMethod.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2016 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.nike.cerberus.client.http; + +/** + * Constants for HTTP methods used by the Cerberus client. + */ +public final class HttpMethod { + + public static final String GET = "GET"; + + public static final String POST = "POST"; + + public static final String PUT = "PUT"; + + public static final String DELETE = "DELETE"; + + public static final String HEAD = "HEAD"; + + public static final String PATCH = "PATCH"; +} diff --git a/src/main/java/com/nike/cerberus/client/http/HttpStatus.java b/src/main/java/com/nike/cerberus/client/http/HttpStatus.java new file mode 100644 index 0000000..d3dc91f --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/http/HttpStatus.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2016 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.nike.cerberus.client.http; + +/** + * Constants for HTTP status codes interpreted by the Cerberus client. + */ +public final class HttpStatus { + + public static final int OK = 200; + + public static final int CREATED = 201; + + public static final int ACCEPTED = 202; + + public static final int NO_CONTENT = 204; + + public static final int BAD_REQUEST = 400; + + public static final int UNAUTHORIZED = 401; + + public static final int FORBIDDEN = 403; + + public static final int NOT_FOUND = 404; + + public static final int CONFLICT = 409; + + public static final int TOO_MANY_REQUESTS = 429; + + public static final int INTERNAL_SERVER_ERROR = 500; + + public static final int BAD_GATEWAY = 502; + + public static final int SERVICE_UNAVAILABLE = 503; + + public static final int GATEWAY_TIMEOUT = 504; +} diff --git a/src/main/java/com/nike/cerberus/client/model/CerberusAuthResponse.java b/src/main/java/com/nike/cerberus/client/model/CerberusAuthResponse.java new file mode 100644 index 0000000..cda40e6 --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/model/CerberusAuthResponse.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2016 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.nike.cerberus.client.model; + +import java.util.Map; +import java.util.Set; + +/** + * Represents an authentication response from Cerberus + */ +public class CerberusAuthResponse { + + private String clientToken; + + private Set policies; + + private Map metadata; + + private int leaseDuration; + + private boolean renewable; + + public String getClientToken() { + return clientToken; + } + + public CerberusAuthResponse setClientToken(String clientToken) { + this.clientToken = clientToken; + return this; + } + + public Set getPolicies() { + return policies; + } + + public CerberusAuthResponse setPolicies(Set policies) { + this.policies = policies; + return this; + } + + public Map getMetadata() { + return metadata; + } + + public CerberusAuthResponse setMetadata(Map metadata) { + this.metadata = metadata; + return this; + } + + public int getLeaseDuration() { + return leaseDuration; + } + + public CerberusAuthResponse setLeaseDuration(int leaseDuration) { + this.leaseDuration = leaseDuration; + return this; + } + + public boolean isRenewable() { + return renewable; + } + + public CerberusAuthResponse setRenewable(boolean renewable) { + this.renewable = renewable; + return this; + } +} diff --git a/src/main/java/com/nike/cerberus/client/model/CerberusClientTokenResponse.java b/src/main/java/com/nike/cerberus/client/model/CerberusClientTokenResponse.java new file mode 100644 index 0000000..396c330 --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/model/CerberusClientTokenResponse.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2016 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.nike.cerberus.client.model; + +import java.util.Map; +import java.util.Set; + +/** + * Represents an authentication client token response from Cerberus + */ +public class CerberusClientTokenResponse { + + private String id; + + private Set policies; + + private String path; + + private Map meta; + + private String displayName; + + private int numUses; + + public String getId() { + return id; + } + + public CerberusClientTokenResponse setId(String id) { + this.id = id; + return this; + } + + public Set getPolicies() { + return policies; + } + + public CerberusClientTokenResponse setPolicies(Set policies) { + this.policies = policies; + return this; + } + + public String getPath() { + return path; + } + + public CerberusClientTokenResponse setPath(String path) { + this.path = path; + return this; + } + + public Map getMeta() { + return meta; + } + + public CerberusClientTokenResponse setMeta(Map meta) { + this.meta = meta; + return this; + } + + public String getDisplayName() { + return displayName; + } + + public CerberusClientTokenResponse setDisplayName(String displayName) { + this.displayName = displayName; + return this; + } + + public int getNumUses() { + return numUses; + } + + public CerberusClientTokenResponse setNumUses(int numUses) { + this.numUses = numUses; + return this; + } +} diff --git a/src/main/java/com/nike/cerberus/client/model/CerberusListResponse.java b/src/main/java/com/nike/cerberus/client/model/CerberusListResponse.java new file mode 100644 index 0000000..0f0fa3d --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/model/CerberusListResponse.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2016 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.nike.cerberus.client.model; + +import java.util.LinkedList; +import java.util.List; + +/** + * Represent a response for listing keys at a path. + */ +public class CerberusListResponse { + + private List keys = new LinkedList(); + + public List getKeys() { + return keys; + } + + public CerberusListResponse setKeys(List keys) { + this.keys = keys; + return this; + } +} diff --git a/src/main/java/com/nike/cerberus/client/model/CerberusResponse.java b/src/main/java/com/nike/cerberus/client/model/CerberusResponse.java new file mode 100644 index 0000000..ad8fd4b --- /dev/null +++ b/src/main/java/com/nike/cerberus/client/model/CerberusResponse.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2016 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.nike.cerberus.client.model; + +import java.util.Map; + +/** + * Represent a response for reading data from Cerberus + */ +public class CerberusResponse { + + private Map data; + + /** + * Returns the key/value pairs stored at a path + * + * @return Map of data + */ + public Map getData() { + return data; + } + + public CerberusResponse setData(Map data) { + this.data = data; + return this; + } +} diff --git a/src/test/java/com/nike/cerberus/client/CerberusClientFactoryTest.java b/src/test/java/com/nike/cerberus/client/CerberusClientFactoryTest.java new file mode 100644 index 0000000..8915c2c --- /dev/null +++ b/src/test/java/com/nike/cerberus/client/CerberusClientFactoryTest.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2016 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.nike.cerberus.client; + +import com.nike.cerberus.client.auth.TokenCerberusCredentials; +import com.nike.cerberus.client.auth.CerberusCredentials; +import com.nike.cerberus.client.auth.CerberusCredentialsProvider; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests the CerberusClientFactoryTest class + */ +public class CerberusClientFactoryTest { + + private final String url = "https://localhost/"; + + private final StaticCerberusUrlResolver urlResolver = new StaticCerberusUrlResolver(url); + + private final String TOKEN = "TOKEN"; + + private final CerberusCredentialsProvider credentialsProvider = new CerberusCredentialsProvider() { + + @Override + public CerberusCredentials getCredentials() { + return new TokenCerberusCredentials(TOKEN); + } + }; + + @Test + public void test_get_client_returns_configured_client() { + final CerberusClient client = CerberusClientFactory.getClient(); + assertThat(client).isNotNull(); + } + + @Test + public void test_get_client_uses_custom_url_resolver() { + final CerberusClient client = CerberusClientFactory.getClient(urlResolver); + assertThat(client).isNotNull(); + assertThat(client.getCerberusUrl().url().toString()).isEqualTo(url); + } + + @Test + public void test_get_client_uses_custom_url_resolver_and_creds_provider() { + final CerberusClient client = CerberusClientFactory.getClient(urlResolver, credentialsProvider); + assertThat(client).isNotNull(); + assertThat(client.getCerberusUrl().url().toString()).isEqualTo(url); + assertThat(client.getCredentialsProvider()).isNotNull(); + assertThat(client.getCredentialsProvider().getCredentials().getToken()).isEqualTo(TOKEN); + } + + @Test + public void test_get_client_uses_default_headers() { + final String headerKey = "HeaderKey"; + final String headerValue = "header value"; + final Map defaultHeaders = new HashMap<>(); + defaultHeaders.put(headerKey, headerValue); + final CerberusClient client = CerberusClientFactory.getClient(urlResolver, credentialsProvider, defaultHeaders); + assertThat(client).isNotNull(); + assertThat(client.getCerberusUrl().url().toString()).isEqualTo(url); + assertThat(client.getCredentialsProvider()).isNotNull(); + assertThat(client.getCredentialsProvider().getCredentials().getToken()).isEqualTo(TOKEN); + assertThat(client.getDefaultHeaders().size()).isEqualTo(1); + assertThat(client.getDefaultHeaders().get(headerKey)).isEqualTo(headerValue); + } + + @Test + public void test_get_admin_client_returns_configured_client() { + final CerberusClient client = CerberusClientFactory.getClient(); + assertThat(client).isNotNull(); + } + + @Test + public void test_get_admin_client_uses_custom_url_resolver() { + final CerberusClient client = CerberusClientFactory.getClient(urlResolver); + assertThat(client).isNotNull(); + assertThat(client.getCerberusUrl().url().toString()).isEqualTo(url); + } + + @Test + public void test_get_admin_client_uses_custom_url_resolver_and_creds_provider() { + final CerberusClient client = CerberusClientFactory.getClient(urlResolver, credentialsProvider); + assertThat(client).isNotNull(); + assertThat(client.getCerberusUrl().url().toString()).isEqualTo(url); + assertThat(client.getCredentialsProvider()).isNotNull(); + assertThat(client.getCredentialsProvider().getCredentials().getToken()).isEqualTo(TOKEN); + } + + @Test + public void test_get_admin_client_uses_all_parameters() { + final String headerKey = "HeaderKey"; + final String headerValue = "header value"; + final Map defaultHeaders = new HashMap<>(); + defaultHeaders.put(headerKey, headerValue); + final CerberusClient client = CerberusClientFactory.getClient(urlResolver, credentialsProvider, 100, defaultHeaders); + assertThat(client).isNotNull(); + assertThat(client.getCerberusUrl().url().toString()).isEqualTo(url); + assertThat(client.getCredentialsProvider()).isNotNull(); + assertThat(client.getCredentialsProvider().getCredentials().getToken()).isEqualTo(TOKEN); + assertThat(client.getDefaultHeaders().size()).isEqualTo(1); + assertThat(client.getDefaultHeaders().get(headerKey)).isEqualTo(headerValue); + } + + @Test + public void test_get_admin_client_uses_default_headers() { + final String headerKey = "HeaderKey"; + final String headerValue = "header value"; + final Map defaultHeaders = new HashMap<>(); + defaultHeaders.put(headerKey, headerValue); + final CerberusClient client = CerberusClientFactory.getClient(urlResolver, credentialsProvider, defaultHeaders); + assertThat(client).isNotNull(); + assertThat(client.getCerberusUrl().url().toString()).isEqualTo(url); + assertThat(client.getCredentialsProvider()).isNotNull(); + assertThat(client.getCredentialsProvider().getCredentials().getToken()).isEqualTo(TOKEN); + assertThat(client.getDefaultHeaders().size()).isEqualTo(1); + assertThat(client.getDefaultHeaders().get(headerKey)).isEqualTo(headerValue); + } +} \ No newline at end of file diff --git a/src/test/java/com/nike/cerberus/client/CerberusClientTest.java b/src/test/java/com/nike/cerberus/client/CerberusClientTest.java new file mode 100644 index 0000000..7bab335 --- /dev/null +++ b/src/test/java/com/nike/cerberus/client/CerberusClientTest.java @@ -0,0 +1,288 @@ +/* + * Copyright (c) 2016 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.nike.cerberus.client; + +import com.nike.cerberus.client.auth.DefaultCerberusCredentialsProviderChain; +import com.nike.cerberus.client.auth.CerberusCredentials; +import com.nike.cerberus.client.auth.CerberusCredentialsProvider; +import com.nike.cerberus.client.http.HttpStatus; +import com.nike.cerberus.client.model.CerberusClientTokenResponse; +import com.nike.cerberus.client.model.CerberusListResponse; +import com.nike.cerberus.client.model.CerberusResponse; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import org.apache.commons.io.IOUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.net.ServerSocket; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Tests the CerberusClient class + */ +public class CerberusClientTest { + + private CerberusClient cerberusClient; + + private MockWebServer mockWebServer; + + @Before + public void setup() throws IOException { + mockWebServer = new MockWebServer(); + mockWebServer.start(); + final String cerberusUrl = "http://localhost:" + mockWebServer.getPort(); + final CerberusCredentialsProvider cerberusCredentialsProvider = mock(CerberusCredentialsProvider.class); + cerberusClient = CerberusClientFactory.getClient( + new StaticCerberusUrlResolver(cerberusUrl), + cerberusCredentialsProvider); + + when(cerberusCredentialsProvider.getCredentials()).thenReturn(new TestCerberusCredentials()); + } + + @After + public void teardown() throws IOException { + mockWebServer.shutdown(); + } + + @Test(expected = IllegalArgumentException.class) + public void constructor_throws_error_if_no_resolver_set() { + new CerberusClient(null, + new DefaultCerberusCredentialsProviderChain(), + new OkHttpClient.Builder().build()); + } + + @Test(expected = IllegalArgumentException.class) + public void constructor_throws_error_if_no_creds_provider() { + new CerberusClient(new DefaultCerberusUrlResolver(), + null, + new OkHttpClient.Builder().build()); + } + + @Test(expected = IllegalArgumentException.class) + public void constructor_throws_error_if_no_http_client() { + new CerberusClient(new DefaultCerberusUrlResolver(), + new DefaultCerberusCredentialsProviderChain(), + null); + } + + @Test + public void list_returns_map_of_keys_for_specified_path_if_exists() throws IOException { + final MockResponse response = new MockResponse(); + response.setResponseCode(200); + response.setBody(getResponseJson("list")); + mockWebServer.enqueue(response); + + CerberusListResponse cerberusListResponse = cerberusClient.list("app/demo"); + + assertThat(cerberusListResponse).isNotNull(); + assertThat(cerberusListResponse.getKeys()).isNotEmpty(); + assertThat(cerberusListResponse.getKeys()).contains("foo", "foo/"); + } + + @Test + public void list_returns_an_empty_response_if_cerberus_returns_a_404() throws IOException { + final MockResponse response = new MockResponse(); + response.setResponseCode(404); + mockWebServer.enqueue(response); + + CerberusListResponse cerberusListResponse = cerberusClient.list("app/demo"); + + assertThat(cerberusListResponse).isNotNull(); + assertThat(cerberusListResponse.getKeys()).isEmpty(); + } + + @Test + public void read_returns_map_of_data_for_specified_path_if_exists() throws IOException { + final MockResponse response = new MockResponse(); + response.setResponseCode(200); + response.setBody(getResponseJson("secret")); + mockWebServer.enqueue(response); + + CerberusResponse cerberusResponse = cerberusClient.read("app/api-key"); + + assertThat(cerberusResponse).isNotNull(); + assertThat(cerberusResponse.getData().containsKey("value")).isTrue(); + assertThat(cerberusResponse.getData().get("value")).isEqualToIgnoringCase("world"); + } + + @Test + public void read_throws_cerberus_server_exception_if_response_is_not_ok() { + final MockResponse response = new MockResponse(); + response.setResponseCode(404); + response.setBody(getResponseJson("error")); + mockWebServer.enqueue(response); + + try { + cerberusClient.read("app/not-found-path"); + } catch (CerberusServerException se) { + assertThat(se.getCode()).isEqualTo(404); + assertThat(se.getErrors()).hasSize(2); + } + } + + @Test(expected = CerberusClientException.class) + public void read_throws_runtime_exception_if_unexpected_error_encountered() throws IOException { + final ServerSocket serverSocket = new ServerSocket(0); + final String cerberusUrl = "http://localhost:" + serverSocket.getLocalPort(); + final CerberusCredentialsProvider cerberusCredentialsProvider = mock(CerberusCredentialsProvider.class); + final OkHttpClient httpClient = buildHttpClient(1, TimeUnit.SECONDS); + cerberusClient = new CerberusClient(new StaticCerberusUrlResolver(cerberusUrl), cerberusCredentialsProvider, httpClient); + + when(cerberusCredentialsProvider.getCredentials()).thenReturn(new TestCerberusCredentials()); + + cerberusClient.read("app/api-key"); + } + + @Test + public void write_returns_gives_no_error_if_write_204_returned() { + final MockResponse response = new MockResponse(); + response.setResponseCode(204); + mockWebServer.enqueue(response); + + Map data = new HashMap<>(); + data.put("key", "value"); + cerberusClient.write("app/api-key", data); + } + + @Test + public void write_throws_cerberus_server_exception_if_response_is_not_204() { + final MockResponse response = new MockResponse(); + response.setResponseCode(403); + response.setBody(getResponseJson("error")); + mockWebServer.enqueue(response); + + try { + Map data = new HashMap<>(); + data.put("key", "value"); + cerberusClient.write("app/not-allowed", data); + } catch (CerberusServerException se) { + assertThat(se.getCode()).isEqualTo(403); + assertThat(se.getErrors()).hasSize(2); + } + } + + @Test(expected = CerberusClientException.class) + public void write_throws_runtime_exception_if_unexpected_error_encountered() throws IOException { + final ServerSocket serverSocket = new ServerSocket(0); + final String cerberusUrl = "http://localhost:" + serverSocket.getLocalPort(); + final CerberusCredentialsProvider cerberusCredentialsProvider = mock(CerberusCredentialsProvider.class); + final OkHttpClient httpClient = buildHttpClient(1, TimeUnit.SECONDS); + cerberusClient = new CerberusClient(new StaticCerberusUrlResolver(cerberusUrl), cerberusCredentialsProvider, httpClient); + + when(cerberusCredentialsProvider.getCredentials()).thenReturn(new TestCerberusCredentials()); + + Map data = new HashMap<>(); + data.put("key", "value"); + cerberusClient.write("app/api-key", data); + } + + @Test + public void delete_returns_gives_no_error_if_write_204_returned() { + final MockResponse response = new MockResponse(); + response.setResponseCode(204); + mockWebServer.enqueue(response); + + cerberusClient.delete("app/api-key"); + } + + @Test + public void delete_throws_cerberus_server_exception_if_response_is_not_204() { + final MockResponse response = new MockResponse(); + response.setResponseCode(403); + response.setBody(getResponseJson("error")); + mockWebServer.enqueue(response); + + try { + cerberusClient.delete("app/not-allowed"); + } catch (CerberusServerException se) { + assertThat(se.getCode()).isEqualTo(403); + assertThat(se.getErrors()).hasSize(2); + } + } + + @Test(expected = CerberusClientException.class) + public void delete_throws_runtime_exception_if_unexpected_error_encountered() throws IOException { + final ServerSocket serverSocket = new ServerSocket(0); + final String cerberusUrl = "http://localhost:" + serverSocket.getLocalPort(); + final CerberusCredentialsProvider cerberusCredentialsProvider = mock(CerberusCredentialsProvider.class); + final OkHttpClient httpClient = buildHttpClient(1, TimeUnit.SECONDS); + cerberusClient = new CerberusClient(new StaticCerberusUrlResolver(cerberusUrl), cerberusCredentialsProvider, httpClient); + + when(cerberusCredentialsProvider.getCredentials()).thenReturn(new TestCerberusCredentials()); + + cerberusClient.delete("app/api-key"); + } + + @Test + public void build_request_includes_default_headers() throws IOException { + final String headerKey = "headerKey"; + final String headerValue = "headerValue"; + final Headers headers = new Headers.Builder().add(headerKey, headerValue).build(); + + final String cerberusUrl = "http://localhost:" + mockWebServer.getPort(); + final CerberusCredentialsProvider cerberusCredentialsProvider = mock(CerberusCredentialsProvider.class); + when(cerberusCredentialsProvider.getCredentials()).thenReturn(new TestCerberusCredentials()); + final OkHttpClient httpClient = buildHttpClient(1, TimeUnit.SECONDS); + cerberusClient = new CerberusClient(new StaticCerberusUrlResolver(cerberusUrl), cerberusCredentialsProvider, httpClient, headers); + + Request result = cerberusClient.buildRequest(HttpUrl.parse(cerberusUrl), "get", null); + + assertThat(result.headers().get(headerKey)).isEqualTo(headerValue); + } + + private OkHttpClient buildHttpClient(int timeout, TimeUnit timeoutUnit) { + return new OkHttpClient.Builder() + .connectTimeout(timeout, timeoutUnit) + .writeTimeout(timeout, timeoutUnit) + .readTimeout(timeout, timeoutUnit) + .build(); + } + + private String getResponseJson(final String title) { + InputStream inputStream = getClass().getResourceAsStream( + String.format("/com/nike/cerberus/client/%s.json", title)); + try { + return IOUtils.toString(inputStream, Charset.forName("UTF-8")); + } catch (IOException e) { + throw new RuntimeException(e); + } finally { + IOUtils.closeQuietly(inputStream); + } + } + + private static class TestCerberusCredentials implements CerberusCredentials { + @Override + public String getToken() { + return "TOKEN"; + } + } +} \ No newline at end of file diff --git a/src/test/java/com/nike/cerberus/client/ClientVersionTest.java b/src/test/java/com/nike/cerberus/client/ClientVersionTest.java index 12614ca..9619171 100644 --- a/src/test/java/com/nike/cerberus/client/ClientVersionTest.java +++ b/src/test/java/com/nike/cerberus/client/ClientVersionTest.java @@ -42,6 +42,6 @@ public void test_that_header_value_includes_right_prefix() { String result = ClientVersion.getClientHeaderValue(); assertTrue(StringUtils.contains(result, ClientVersion.HEADER_VALUE_PREFIX)); - assertTrue(StringUtils.contains(result, com.nike.vault.client.ClientVersion.getVersion())); + assertTrue(StringUtils.contains(result, ClientVersion.getVersion())); } } diff --git a/src/test/java/com/nike/cerberus/client/DefaultCerberusClientFactoryTest.java b/src/test/java/com/nike/cerberus/client/DefaultCerberusClientFactoryTest.java index 6d6de50..9a48443 100644 --- a/src/test/java/com/nike/cerberus/client/DefaultCerberusClientFactoryTest.java +++ b/src/test/java/com/nike/cerberus/client/DefaultCerberusClientFactoryTest.java @@ -16,7 +16,6 @@ package com.nike.cerberus.client; -import com.nike.vault.client.VaultClient; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -28,7 +27,7 @@ public class DefaultCerberusClientFactoryTest { @Test public void test_that_getClient_adds_client_version_as_a_default_header() { - VaultClient result = DefaultCerberusClientFactory.getClient(); + CerberusClient result = DefaultCerberusClientFactory.getClient(); assertEquals( ClientVersion.getClientHeaderValue(), result.getDefaultHeaders().get(ClientVersion.CERBERUS_CLIENT_HEADER)); @@ -36,7 +35,7 @@ public void test_that_getClient_adds_client_version_as_a_default_header() { @Test public void test_that_getClientForLambda_adds_client_version_as_a_default_header() { - VaultClient result = DefaultCerberusClientFactory.getClientForLambda("arn:aws:lambda:us-west-2:000000000000:function:name:qualifier"); + CerberusClient result = DefaultCerberusClientFactory.getClientForLambda("arn:aws:lambda:us-west-2:000000000000:function:name:qualifier"); assertEquals( ClientVersion.getClientHeaderValue(), result.getDefaultHeaders().get(ClientVersion.CERBERUS_CLIENT_HEADER)); diff --git a/src/test/java/com/nike/cerberus/client/DefaultCerberusUrlResolverTest.java b/src/test/java/com/nike/cerberus/client/DefaultCerberusUrlResolverTest.java index a4da6df..9ea0fd5 100644 --- a/src/test/java/com/nike/cerberus/client/DefaultCerberusUrlResolverTest.java +++ b/src/test/java/com/nike/cerberus/client/DefaultCerberusUrlResolverTest.java @@ -19,6 +19,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; diff --git a/src/test/java/com/nike/cerberus/client/StaticCerberusUrlResolverTest.java b/src/test/java/com/nike/cerberus/client/StaticCerberusUrlResolverTest.java new file mode 100644 index 0000000..269c2fb --- /dev/null +++ b/src/test/java/com/nike/cerberus/client/StaticCerberusUrlResolverTest.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2016 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.nike.cerberus.client; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests the StaticCerberusUrlResolverTest class + */ +public class StaticCerberusUrlResolverTest { + + private final String testUrl = "https://localhost"; + + @Test(expected = IllegalArgumentException.class) + public void test_constructor_throws_error_if_vault_url_is_blank() { + new StaticCerberusUrlResolver(" "); + } + + @Test + public void test_resolve_returns_url_that_was_set() { + final UrlResolver urlResolver = new StaticCerberusUrlResolver(testUrl); + + assertThat(urlResolver.resolve()).isEqualTo(testUrl); + } +} \ No newline at end of file diff --git a/src/test/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChainTest.java b/src/test/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChainTest.java new file mode 100644 index 0000000..5fc0425 --- /dev/null +++ b/src/test/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChainTest.java @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2016 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.nike.cerberus.client.auth; + +import com.nike.cerberus.client.CerberusClientException; +import org.junit.Before; +import org.junit.Test; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Tests the CerberusCredentialsProviderChain class + */ +public class CerberusCredentialsProviderChainTest { + + private static final String TOKEN = "TOKEN"; + + private CerberusCredentialsProvider credentialsProviderOne; + + private CerberusCredentialsProvider credentialsProviderTwo; + + private CerberusCredentialsProviderChain credentialsProviderChain; + + @Before + public void setup() { + credentialsProviderOne = mock(CerberusCredentialsProvider.class); + credentialsProviderTwo = mock(CerberusCredentialsProvider.class); + credentialsProviderChain = new CerberusCredentialsProviderChain(credentialsProviderOne, credentialsProviderTwo); + } + + @Test + public void getCredentials_returns_credentials_from_first_successful_provider() { + when(credentialsProviderOne.getCredentials()).thenReturn(new TestCerberusCredentials()); + + CerberusCredentials credentials = credentialsProviderChain.getCredentials(); + + assertThat(credentials).isNotNull(); + } + + @Test(expected = CerberusClientException.class) + public void getCredentials_throws_client_exception_if_all_providers_fail() { + when(credentialsProviderOne.getCredentials()).thenThrow(new CerberusClientException("")); + when(credentialsProviderTwo.getCredentials()).thenThrow(new CerberusClientException("")); + + credentialsProviderChain.getCredentials(); + } + + @Test + public void getCredentials_uses_last_successful_provider() { + when(credentialsProviderOne.getCredentials()).thenThrow(new CerberusClientException("")); + when(credentialsProviderTwo.getCredentials()).thenReturn(new TestCerberusCredentials()); + + CerberusCredentials credentials = credentialsProviderChain.getCredentials(); + + assertThat(credentials).isNotNull(); + + CerberusCredentials credentialsAgain = credentialsProviderChain.getCredentials(); + + verify(credentialsProviderOne, times(1)).getCredentials(); + verify(credentialsProviderTwo, times(2)).getCredentials(); + + assertThat(credentials.getToken()).isEqualTo(credentialsAgain.getToken()); + } + + @Test + public void getCredentials_with_reuse_last_provider_disabled_attempts_chain_of_providers() { + when(credentialsProviderOne.getCredentials()).thenThrow(new CerberusClientException("")); + when(credentialsProviderTwo.getCredentials()).thenReturn(new TestCerberusCredentials()); + + CerberusCredentials credentials = credentialsProviderChain.getCredentials(); + + assertThat(credentials).isNotNull(); + + credentialsProviderChain.setReuseLastProvider(false); + + CerberusCredentials credentialsAgain = credentialsProviderChain.getCredentials(); + + verify(credentialsProviderOne, times(2)).getCredentials(); + verify(credentialsProviderTwo, times(2)).getCredentials(); + + assertThat(credentials.getToken()).isEqualTo(credentialsAgain.getToken()); + } + + @Test + public void getCredentials_attempts_full_chain_even_if_one_throws_exception() { + when(credentialsProviderOne.getCredentials()).thenThrow(new RuntimeException()); + when(credentialsProviderTwo.getCredentials()).thenReturn(new TestCerberusCredentials()); + + CerberusCredentials credentials = credentialsProviderChain.getCredentials(); + + assertThat(credentials).isNotNull(); + assertThat(credentials.getToken()).isEqualTo(TOKEN); + } + + @Test + public void isReuseLastProvider_returns_if_reuse_last_provider_is_enabled() { + assertThat(credentialsProviderChain.isReuseLastProvider()).isTrue(); + credentialsProviderChain.setReuseLastProvider(false); + assertThat(credentialsProviderChain.isReuseLastProvider()).isFalse(); + credentialsProviderChain.setReuseLastProvider(true); + assertThat(credentialsProviderChain.isReuseLastProvider()).isTrue(); + } + + @Test + public void list_contstructor_set_provider_list() { + List list = new LinkedList<>(); + list.add(credentialsProviderOne); + list.add(credentialsProviderTwo); + + CerberusCredentialsProviderChain chain = new CerberusCredentialsProviderChain(list); + + when(credentialsProviderOne.getCredentials()).thenThrow(new CerberusClientException("")); + when(credentialsProviderTwo.getCredentials()).thenReturn(new TestCerberusCredentials()); + + CerberusCredentials credentials = chain.getCredentials(); + + assertThat(credentials).isNotNull(); + assertThat(credentials.getToken()).isEqualTo(TOKEN); + } + + @Test(expected = IllegalArgumentException.class) + public void new_chain_without_providers_throws_exception() { + new CerberusCredentialsProviderChain(); + } + + @Test(expected = IllegalArgumentException.class) + public void new_chain_with_empty_providers_throws_exception() { + new CerberusCredentialsProviderChain(new CerberusCredentialsProviderChain[]{}); + } + + @Test(expected = IllegalArgumentException.class) + public void new_chain_with_null_list_of_providers_throws_exception() { + List list = null; + new CerberusCredentialsProviderChain(list); + } + + @Test(expected = IllegalArgumentException.class) + public void new_chain_with_empty_list_of_providers_throws_exception() { + List list = Collections.emptyList(); + new CerberusCredentialsProviderChain(list); + } + + private static class TestCerberusCredentials implements CerberusCredentials { + @Override + public String getToken() { + return TOKEN; + } + } +} \ No newline at end of file diff --git a/src/test/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChainTest.java b/src/test/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChainTest.java index afa689f..70f508d 100644 --- a/src/test/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChainTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChainTest.java @@ -16,7 +16,6 @@ package com.nike.cerberus.client.auth; -import com.nike.vault.client.auth.VaultCredentials; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -53,7 +52,7 @@ public void env_set_credentials_always_returned_when_sys_property_is_also_set() when(System.getenv(EnvironmentCerberusCredentialsProvider.CERBERUS_TOKEN_ENV_PROPERTY)).thenReturn(ENV_VALUE); when(System.getProperty(SystemPropertyCerberusCredentialsProvider.CERBERUS_TOKEN_SYS_PROPERTY)).thenReturn(SYS_VALUE); - VaultCredentials credentials = credentialsProviderChain.getCredentials(); + CerberusCredentials credentials = credentialsProviderChain.getCredentials(); assertThat(credentials).isNotNull(); assertThat(credentials.getToken()).isEqualTo(ENV_VALUE); @@ -65,7 +64,7 @@ public void sys_value_set_if_env_is_not_set() { when(System.getenv(EnvironmentCerberusCredentialsProvider.CERBERUS_TOKEN_ENV_PROPERTY)).thenReturn(""); when(System.getProperty(SystemPropertyCerberusCredentialsProvider.CERBERUS_TOKEN_SYS_PROPERTY)).thenReturn(SYS_VALUE); - VaultCredentials credentials = credentialsProviderChain.getCredentials(); + CerberusCredentials credentials = credentialsProviderChain.getCredentials(); assertThat(credentials).isNotNull(); assertThat(credentials.getToken()).isEqualTo(SYS_VALUE); diff --git a/src/test/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProviderTest.java b/src/test/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProviderTest.java index 9539a77..d37d5fc 100644 --- a/src/test/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProviderTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProviderTest.java @@ -16,8 +16,7 @@ package com.nike.cerberus.client.auth; -import com.nike.vault.client.VaultClientException; -import com.nike.vault.client.auth.VaultCredentials; +import com.nike.cerberus.client.CerberusClientException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -49,13 +48,13 @@ public void getCredentials_returns_creds_from_env_when_set() { mockStatic(System.class); when(System.getenv(EnvironmentCerberusCredentialsProvider.CERBERUS_TOKEN_ENV_PROPERTY)).thenReturn(TOKEN); - VaultCredentials credentials = credentialsProvider.getCredentials(); + CerberusCredentials credentials = credentialsProvider.getCredentials(); assertThat(credentials).isNotNull(); assertThat(credentials.getToken()).isEqualTo(TOKEN); } - @Test(expected = VaultClientException.class) + @Test(expected = CerberusClientException.class) public void getCredentials_throws_client_exception_when_not_set() { mockStatic(System.class); when(System.getenv(EnvironmentCerberusCredentialsProvider.CERBERUS_TOKEN_ENV_PROPERTY)).thenReturn(null); @@ -63,7 +62,7 @@ public void getCredentials_throws_client_exception_when_not_set() { credentialsProvider.getCredentials(); } - @Test(expected = VaultClientException.class) + @Test(expected = CerberusClientException.class) public void getCredentials_returns_empty_creds_object_when_env_variable_is_blank() { mockStatic(System.class); when(System.getenv(EnvironmentCerberusCredentialsProvider.CERBERUS_TOKEN_ENV_PROPERTY)).thenReturn(""); diff --git a/src/test/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProviderTest.java b/src/test/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProviderTest.java index 9914f67..ac742d2 100644 --- a/src/test/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProviderTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProviderTest.java @@ -16,8 +16,7 @@ package com.nike.cerberus.client.auth; -import com.nike.vault.client.VaultClientException; -import com.nike.vault.client.auth.VaultCredentials; +import com.nike.cerberus.client.CerberusClientException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -49,13 +48,13 @@ public void getCredentials_returns_creds_from_system_property_when_set() { mockStatic(System.class); when(System.getProperty(SystemPropertyCerberusCredentialsProvider.CERBERUS_TOKEN_SYS_PROPERTY)).thenReturn(TOKEN); - VaultCredentials credentials = credentialsProvider.getCredentials(); + CerberusCredentials credentials = credentialsProvider.getCredentials(); assertThat(credentials).isNotNull(); assertThat(credentials.getToken()).isEqualTo(TOKEN); } - @Test(expected = VaultClientException.class) + @Test(expected = CerberusClientException.class) public void getCredentials_returns_empty_creds_object_when_sys_property_not_set() { mockStatic(System.class); when(System.getProperty(SystemPropertyCerberusCredentialsProvider.CERBERUS_TOKEN_SYS_PROPERTY)).thenReturn(null); @@ -63,7 +62,7 @@ public void getCredentials_returns_empty_creds_object_when_sys_property_not_set( credentialsProvider.getCredentials(); } - @Test(expected = VaultClientException.class) + @Test(expected = CerberusClientException.class) public void getCredentials_returns_empty_creds_object_when_sys_property_is_blank() { mockStatic(System.class); when(System.getProperty(SystemPropertyCerberusCredentialsProvider.CERBERUS_TOKEN_SYS_PROPERTY)).thenReturn(""); diff --git a/src/test/java/com/nike/cerberus/client/auth/TokenCerberusCredentialsTest.java b/src/test/java/com/nike/cerberus/client/auth/TokenCerberusCredentialsTest.java new file mode 100644 index 0000000..e174861 --- /dev/null +++ b/src/test/java/com/nike/cerberus/client/auth/TokenCerberusCredentialsTest.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2016 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.nike.cerberus.client.auth; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests the TokenCerberusCredentials class + */ +public class TokenCerberusCredentialsTest { + + @Test + public void getToken_returns_the_token_set_during_construction() { + final String token = "TOKEN"; + + TokenCerberusCredentials credentials = new TokenCerberusCredentials(token); + + assertThat(credentials.getToken()).isEqualTo(token); + } +} \ No newline at end of file diff --git a/src/test/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProviderTest.java b/src/test/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProviderTest.java index 1ba3603..fe89fba 100644 --- a/src/test/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProviderTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProviderTest.java @@ -19,11 +19,10 @@ import com.amazonaws.regions.Region; import com.amazonaws.regions.RegionUtils; import com.amazonaws.services.kms.AWSKMSClient; +import com.nike.cerberus.client.CerberusClientException; +import com.nike.cerberus.client.CerberusServerException; import com.nike.cerberus.client.DefaultCerberusUrlResolver; -import com.nike.vault.client.UrlResolver; -import com.nike.vault.client.VaultClientException; -import com.nike.vault.client.VaultServerException; -import com.nike.vault.client.auth.VaultCredentials; +import com.nike.cerberus.client.UrlResolver; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.After; @@ -32,7 +31,6 @@ import java.io.IOException; -import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.reset; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; @@ -67,19 +65,19 @@ public void tearDown() throws Exception { reset(urlResolver); } - @Test(expected = VaultClientException.class) + @Test(expected = CerberusClientException.class) public void getEncryptedAuthData_blank_url_throws_exception() throws Exception { when(urlResolver.resolve()).thenReturn(""); provider.getEncryptedAuthData(CERBERUS_TEST_ARN, REGION); } - @Test(expected = VaultClientException.class) + @Test(expected = CerberusClientException.class) public void decryptToken_throws_exception_when_non_encrypted_data_provided() { provider.decryptToken(mock(AWSKMSClient.class), "non-encrypted-token"); } - @Test(expected = VaultServerException.class) + @Test(expected = CerberusServerException.class) public void getEncryptedAuthData_throws_exception_on_bad_response_code() throws IOException { when(urlResolver.resolve()).thenReturn(vaultUrl); @@ -89,7 +87,7 @@ public void getEncryptedAuthData_throws_exception_on_bad_response_code() throws provider.getEncryptedAuthData(CERBERUS_TEST_ARN, REGION); } - @Test(expected = VaultClientException.class) + @Test(expected = CerberusClientException.class) public void getEncryptedAuthData_throws_exception_on_missing_auth_data() throws IOException { when(urlResolver.resolve()).thenReturn(vaultUrl); diff --git a/src/test/java/com/nike/cerberus/client/auth/aws/InstanceRoleVaultCredentialsProviderTest.java b/src/test/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProviderTest.java similarity index 83% rename from src/test/java/com/nike/cerberus/client/auth/aws/InstanceRoleVaultCredentialsProviderTest.java rename to src/test/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProviderTest.java index 43ca74c..21a1464 100644 --- a/src/test/java/com/nike/cerberus/client/auth/aws/InstanceRoleVaultCredentialsProviderTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProviderTest.java @@ -20,13 +20,12 @@ import com.amazonaws.regions.Regions; import com.amazonaws.services.kms.AWSKMSClient; import com.amazonaws.util.EC2MetadataUtils; +import com.nike.cerberus.client.CerberusClientException; import com.nike.cerberus.client.DefaultCerberusUrlResolver; -import com.nike.vault.client.UrlResolver; -import com.nike.vault.client.VaultClientException; -import com.nike.vault.client.auth.VaultCredentials; +import com.nike.cerberus.client.UrlResolver; +import com.nike.cerberus.client.auth.CerberusCredentials; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; -import org.apache.commons.lang3.StringUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -42,25 +41,23 @@ import java.util.Map; import java.util.Set; -import static com.nike.cerberus.client.auth.aws.InstanceRoleVaultCredentialsProvider.buildIamRoleArns; -import static com.nike.cerberus.client.auth.aws.InstanceRoleVaultCredentialsProvider.buildRoleArn; -import static com.nike.cerberus.client.auth.aws.StaticIamRoleVaultCredentialsProvider.IAM_ROLE_ARN_FORMAT; +import static com.nike.cerberus.client.auth.aws.InstanceRoleCerberusCredentialsProvider.buildIamRoleArns; +import static com.nike.cerberus.client.auth.aws.InstanceRoleCerberusCredentialsProvider.buildRoleArn; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.mockito.PowerMockito.whenNew; /** - * Tests the InstanceRoleVaultCredentialsProvider class + * Tests the InstanceRoleCerberusCredentialsProvider class */ @RunWith(PowerMockRunner.class) @PrepareForTest({AWSKMSClient.class, - EC2MetadataUtils.class, InstanceRoleVaultCredentialsProvider.class}) + EC2MetadataUtils.class, InstanceRoleCerberusCredentialsProvider.class}) @PowerMockIgnore({"javax.management.*","javax.net.*"}) -public class InstanceRoleVaultCredentialsProviderTest extends BaseCredentialsProviderTest { +public class InstanceRoleCerberusCredentialsProviderTest extends BaseCredentialsProviderTest { private static final String GOOD_INSTANCE_PROFILE_ARN = "arn:aws:iam::107274433934:instance-profile/rawr"; @@ -70,13 +67,13 @@ public class InstanceRoleVaultCredentialsProviderTest extends BaseCredentialsPro private AWSKMSClient kmsClient; - private InstanceRoleVaultCredentialsProvider provider; + private InstanceRoleCerberusCredentialsProvider provider; @Before public void setup() throws Exception { kmsClient = mock(AWSKMSClient.class); urlResolver = mock(UrlResolver.class); - provider = new InstanceRoleVaultCredentialsProvider(urlResolver); + provider = new InstanceRoleCerberusCredentialsProvider(urlResolver); whenNew(AWSKMSClient.class).withAnyArguments().thenReturn(kmsClient); mockStatic(EC2MetadataUtils.class); @@ -98,12 +95,12 @@ public void getCredentials_returns_valid_credentials() throws IOException { System.setProperty(DefaultCerberusUrlResolver.CERBERUS_ADDR_SYS_PROPERTY, vaultUrl); mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(AUTH_RESPONSE)); - VaultCredentials credentials = provider.getCredentials(); + CerberusCredentials credentials = provider.getCredentials(); assertThat(credentials.getToken()).isEqualTo(AUTH_TOKEN); } - @Test(expected = VaultClientException.class) + @Test(expected = CerberusClientException.class) public void getCredentials_throws_client_exception_when_accountId_missing() { mockGetIamSecurityCredentials(DEFAULT_ROLE); mockGetIamInstanceProfileInfo("arn:aws:iam:instance-profile/rawr"); @@ -111,7 +108,7 @@ public void getCredentials_throws_client_exception_when_accountId_missing() { provider.getCredentials(); } - @Test(expected = VaultClientException.class) + @Test(expected = CerberusClientException.class) public void getCredentials_throws_client_exception_when_no_roles_are_set() { when(EC2MetadataUtils.getIAMSecurityCredentials()) .thenReturn(Collections.emptyMap()); @@ -120,14 +117,14 @@ public void getCredentials_throws_client_exception_when_no_roles_are_set() { provider.getCredentials(); } - @Test(expected = VaultClientException.class) + @Test(expected = CerberusClientException.class) public void getCredentials_throws_client_exception_when_not_running_on_ec2_instance() { when(EC2MetadataUtils.getIAMSecurityCredentials()).thenThrow(new AmazonClientException("BAD")); provider.getCredentials(); } - @Test(expected = VaultClientException.class) + @Test(expected = CerberusClientException.class) public void getCredentials_thorws_client_exception_when_no_instance_profile_assigned() { when(EC2MetadataUtils.getIAMInstanceProfileInfo()).thenReturn(null); @@ -186,7 +183,7 @@ public void test_buildIamRoleArns_CloudFormation_style_names_with_paths() { @Test public void test_parseInstanceProfileArn_with_path() { String instanceProfileArn = "arn:aws:iam::1234567890123:instance-profile/brewmaster/foo/brewmaster-foo-cerberus"; - InstanceRoleVaultCredentialsProvider.InstanceProfileInfo info = InstanceRoleVaultCredentialsProvider.parseInstanceProfileArn(instanceProfileArn); + InstanceRoleCerberusCredentialsProvider.InstanceProfileInfo info = InstanceRoleCerberusCredentialsProvider.parseInstanceProfileArn(instanceProfileArn); assertEquals("1234567890123", info.accountId); assertEquals("brewmaster/foo/brewmaster-foo-cerberus", info.profileName); } @@ -194,7 +191,7 @@ public void test_parseInstanceProfileArn_with_path() { @Test public void test_parseInstanceProfileArn_without_path() { String instanceProfileArn = "arn:aws:iam::1234567890123:instance-profile/foo-cerberus"; - InstanceRoleVaultCredentialsProvider.InstanceProfileInfo info = InstanceRoleVaultCredentialsProvider.parseInstanceProfileArn(instanceProfileArn); + InstanceRoleCerberusCredentialsProvider.InstanceProfileInfo info = InstanceRoleCerberusCredentialsProvider.parseInstanceProfileArn(instanceProfileArn); assertEquals("1234567890123", info.accountId); assertEquals("foo-cerberus", info.profileName); } @@ -202,7 +199,7 @@ public void test_parseInstanceProfileArn_without_path() { @Test public void test_parsePathFromInstanceProfileName() { String instanceProfileName = "brewmaster/foo/brewmaster-foo-cerberus"; - String path = InstanceRoleVaultCredentialsProvider.parsePathFromInstanceProfileName(instanceProfileName); + String path = InstanceRoleCerberusCredentialsProvider.parsePathFromInstanceProfileName(instanceProfileName); assertEquals("brewmaster/foo", path); } diff --git a/src/test/java/com/nike/cerberus/client/auth/aws/LambdaRoleVaultCredentialsProviderTest.java b/src/test/java/com/nike/cerberus/client/auth/aws/LambdaRoleCerberusCredentialsProviderTest.java similarity index 73% rename from src/test/java/com/nike/cerberus/client/auth/aws/LambdaRoleVaultCredentialsProviderTest.java rename to src/test/java/com/nike/cerberus/client/auth/aws/LambdaRoleCerberusCredentialsProviderTest.java index d20ff76..891c358 100644 --- a/src/test/java/com/nike/cerberus/client/auth/aws/LambdaRoleVaultCredentialsProviderTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/aws/LambdaRoleCerberusCredentialsProviderTest.java @@ -22,10 +22,10 @@ import com.amazonaws.services.lambda.AWSLambdaClient; import com.amazonaws.services.lambda.model.GetFunctionConfigurationRequest; import com.amazonaws.services.lambda.model.GetFunctionConfigurationResult; +import com.nike.cerberus.client.CerberusClientException; import com.nike.cerberus.client.DefaultCerberusUrlResolver; -import com.nike.vault.client.UrlResolver; -import com.nike.vault.client.VaultClientException; -import com.nike.vault.client.auth.VaultCredentials; +import com.nike.cerberus.client.UrlResolver; +import com.nike.cerberus.client.auth.CerberusCredentials; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.After; @@ -38,15 +38,18 @@ import org.powermock.modules.junit4.PowerMockRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.*; +import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; +import static org.powermock.api.mockito.PowerMockito.whenNew; @RunWith(PowerMockRunner.class) -@PrepareForTest({AWSKMSClient.class, Regions.class, AWSLambdaClient.class, LambdaRoleVaultCredentialsProvider.class}) +@PrepareForTest({AWSKMSClient.class, Regions.class, AWSLambdaClient.class, LambdaRoleCerberusCredentialsProvider.class}) @PowerMockIgnore({"javax.management.*", "javax.net.*"}) -public class LambdaRoleVaultCredentialsProviderTest extends BaseCredentialsProviderTest { +public class LambdaRoleCerberusCredentialsProviderTest extends BaseCredentialsProviderTest { private static final String VALID_LAMBDA_ARN = "arn:aws:lambda:us-west-2:123456789012:function:lambda-test:1.1.0"; private static final String VALID_LAMBDA_ARN_NO_QUALIFIER = "arn:aws:lambda:us-west-2:012345678912:function:lambda-test"; private static final String VALID_IAM_ARN = "arn:aws:iam::123456789012:role/cerberus-role"; @@ -56,7 +59,7 @@ public class LambdaRoleVaultCredentialsProviderTest extends BaseCredentialsProvi private UrlResolver urlResolver; private AWSLambdaClient lambdaClient; private MockWebServer mockWebServer; - private String vaultUrl; + private String cerberusUrl; @Before public void setup() throws Exception { @@ -66,9 +69,9 @@ public void setup() throws Exception { mockWebServer = new MockWebServer(); mockWebServer.start(); - vaultUrl = "http://localhost:" + mockWebServer.getPort(); + cerberusUrl = "http://localhost:" + mockWebServer.getPort(); - when(urlResolver.resolve()).thenReturn(vaultUrl); + when(urlResolver.resolve()).thenReturn(cerberusUrl); mockStatic(Regions.class); @@ -80,41 +83,41 @@ public void setup() throws Exception { @Test(expected = IllegalArgumentException.class) public void provider_creation_fails_on_invalid_arn() { - LambdaRoleVaultCredentialsProvider provider = new LambdaRoleVaultCredentialsProvider(urlResolver, "invalid-lambda-arn"); + LambdaRoleCerberusCredentialsProvider provider = new LambdaRoleCerberusCredentialsProvider(urlResolver, "invalid-lambda-arn"); } @Test public void valid_arn_and_no_qualifier_matched_properly_on_provider_creation() { - LambdaRoleVaultCredentialsProvider provider = new LambdaRoleVaultCredentialsProvider(urlResolver, VALID_LAMBDA_ARN_NO_QUALIFIER); + LambdaRoleCerberusCredentialsProvider provider = new LambdaRoleCerberusCredentialsProvider(urlResolver, VALID_LAMBDA_ARN_NO_QUALIFIER); } @Test public void getCredentials_returns_valid_creds() throws Exception { - final LambdaRoleVaultCredentialsProvider provider = PowerMockito.spy(new LambdaRoleVaultCredentialsProvider(urlResolver, VALID_LAMBDA_ARN)); + final LambdaRoleCerberusCredentialsProvider provider = PowerMockito.spy(new LambdaRoleCerberusCredentialsProvider(urlResolver, VALID_LAMBDA_ARN)); final GetFunctionConfigurationRequest request = new GetFunctionConfigurationRequest().withFunctionName("lambda-test").withQualifier("1.1.0"); - when(urlResolver.resolve()).thenReturn(vaultUrl); + when(urlResolver.resolve()).thenReturn(cerberusUrl); - System.setProperty(DefaultCerberusUrlResolver.CERBERUS_ADDR_SYS_PROPERTY, vaultUrl); + System.setProperty(DefaultCerberusUrlResolver.CERBERUS_ADDR_SYS_PROPERTY, cerberusUrl); mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(AUTH_RESPONSE)); mockDecrypt(kmsClient, DECODED_AUTH_DATA); when(lambdaClient.getFunctionConfiguration(request)).thenReturn(new GetFunctionConfigurationResult().withRole(VALID_IAM_ARN)); - final VaultCredentials credentials = provider.getCredentials(); + final CerberusCredentials credentials = provider.getCredentials(); assertThat(credentials.getToken()).isEqualTo(AUTH_TOKEN); verify(lambdaClient, times(1)).getFunctionConfiguration(request); } - @Test(expected = VaultClientException.class) - public void VaultClientException_thrown_when_bad_json_returned() throws Exception { - final LambdaRoleVaultCredentialsProvider provider = PowerMockito.spy(new LambdaRoleVaultCredentialsProvider(urlResolver, VALID_LAMBDA_ARN)); + @Test(expected = CerberusClientException.class) + public void CerberusClientException_thrown_when_bad_json_returned() throws Exception { + final LambdaRoleCerberusCredentialsProvider provider = PowerMockito.spy(new LambdaRoleCerberusCredentialsProvider(urlResolver, VALID_LAMBDA_ARN)); final GetFunctionConfigurationRequest request = new GetFunctionConfigurationRequest().withFunctionName("lambda-test").withQualifier("1.1.0"); - System.setProperty(DefaultCerberusUrlResolver.CERBERUS_ADDR_SYS_PROPERTY, vaultUrl); + System.setProperty(DefaultCerberusUrlResolver.CERBERUS_ADDR_SYS_PROPERTY, cerberusUrl); mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(BAD_AUTH_RESPONSE_JSON)); mockDecrypt(kmsClient, DECODED_AUTH_DATA); @@ -126,7 +129,7 @@ public void VaultClientException_thrown_when_bad_json_returned() throws Exceptio @Test(expected = IllegalStateException.class) public void authenticate_fails_when_lambda_has_invalid_assigned_role() throws Exception { - final LambdaRoleVaultCredentialsProvider provider = new LambdaRoleVaultCredentialsProvider(urlResolver, VALID_LAMBDA_ARN); + final LambdaRoleCerberusCredentialsProvider provider = new LambdaRoleCerberusCredentialsProvider(urlResolver, VALID_LAMBDA_ARN); final GetFunctionConfigurationRequest request = new GetFunctionConfigurationRequest().withFunctionName("lambda-test").withQualifier("1.1.0"); when(lambdaClient.getFunctionConfiguration(request)).thenReturn(new GetFunctionConfigurationResult().withRole(INVALID_ARN)); @@ -137,7 +140,7 @@ public void authenticate_fails_when_lambda_has_invalid_assigned_role() throws Ex @Test(expected = IllegalStateException.class) public void authenticate_fails_when_lambda_has_no_assigned_role() throws Exception { - final LambdaRoleVaultCredentialsProvider provider = new LambdaRoleVaultCredentialsProvider(urlResolver, VALID_LAMBDA_ARN); + final LambdaRoleCerberusCredentialsProvider provider = new LambdaRoleCerberusCredentialsProvider(urlResolver, VALID_LAMBDA_ARN); final GetFunctionConfigurationRequest request = new GetFunctionConfigurationRequest().withFunctionName("lambda-test").withQualifier("1.1.0"); when(lambdaClient.getFunctionConfiguration(request)).thenReturn(new GetFunctionConfigurationResult().withRole("")); diff --git a/src/test/java/com/nike/cerberus/client/auth/aws/StaticIamRoleVaultCredentialsProviderTest.java b/src/test/java/com/nike/cerberus/client/auth/aws/StaticIamRoleCerberusCredentialsProviderTest.java similarity index 72% rename from src/test/java/com/nike/cerberus/client/auth/aws/StaticIamRoleVaultCredentialsProviderTest.java rename to src/test/java/com/nike/cerberus/client/auth/aws/StaticIamRoleCerberusCredentialsProviderTest.java index de66089..c0cf478 100644 --- a/src/test/java/com/nike/cerberus/client/auth/aws/StaticIamRoleVaultCredentialsProviderTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/aws/StaticIamRoleCerberusCredentialsProviderTest.java @@ -18,12 +18,12 @@ import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; -import com.nike.vault.client.StaticVaultUrlResolver; +import com.nike.cerberus.client.StaticCerberusUrlResolver; import org.junit.Test; import static org.junit.Assert.assertEquals; -public class StaticIamRoleVaultCredentialsProviderTest { +public class StaticIamRoleCerberusCredentialsProviderTest { private static final String ACCOUNT_ID = "1234"; private static final String ROLE_NAME = "foo/base/bar"; @@ -33,8 +33,8 @@ public class StaticIamRoleVaultCredentialsProviderTest { @Test public void test_constructor_1() { - StaticIamRoleVaultCredentialsProvider provider = new StaticIamRoleVaultCredentialsProvider( - new StaticVaultUrlResolver("foo"), + StaticIamRoleCerberusCredentialsProvider provider = new StaticIamRoleCerberusCredentialsProvider( + new StaticCerberusUrlResolver("foo"), ACCOUNT_ID, ROLE_NAME, REGION_STRING @@ -46,7 +46,7 @@ public void test_constructor_1() { @Test public void test_constructor_2() { - StaticIamRoleVaultCredentialsProvider provider = new StaticIamRoleVaultCredentialsProvider( + StaticIamRoleCerberusCredentialsProvider provider = new StaticIamRoleCerberusCredentialsProvider( "foo", ACCOUNT_ID, ROLE_NAME, @@ -59,8 +59,8 @@ public void test_constructor_2() { @Test public void test_constructor_3() { - StaticIamRoleVaultCredentialsProvider provider = new StaticIamRoleVaultCredentialsProvider( - new StaticVaultUrlResolver("foo"), + StaticIamRoleCerberusCredentialsProvider provider = new StaticIamRoleCerberusCredentialsProvider( + new StaticCerberusUrlResolver("foo"), ACCOUNT_ID, ROLE_NAME, REGION @@ -72,7 +72,7 @@ public void test_constructor_3() { @Test public void test_constructor_4() { - StaticIamRoleVaultCredentialsProvider provider = new StaticIamRoleVaultCredentialsProvider( + StaticIamRoleCerberusCredentialsProvider provider = new StaticIamRoleCerberusCredentialsProvider( "foo", ACCOUNT_ID, ROLE_NAME, @@ -85,8 +85,8 @@ public void test_constructor_4() { @Test public void test_constructor_5() { - StaticIamRoleVaultCredentialsProvider provider = new StaticIamRoleVaultCredentialsProvider( - new StaticVaultUrlResolver("foo"), + StaticIamRoleCerberusCredentialsProvider provider = new StaticIamRoleCerberusCredentialsProvider( + new StaticCerberusUrlResolver("foo"), ROLE_ARN, REGION_STRING ); @@ -97,7 +97,7 @@ public void test_constructor_5() { @Test public void test_constructor_6() { - StaticIamRoleVaultCredentialsProvider provider = new StaticIamRoleVaultCredentialsProvider( + StaticIamRoleCerberusCredentialsProvider provider = new StaticIamRoleCerberusCredentialsProvider( "foo", ROLE_ARN, REGION_STRING @@ -109,8 +109,8 @@ public void test_constructor_6() { @Test public void test_constructor_7() { - StaticIamRoleVaultCredentialsProvider provider = new StaticIamRoleVaultCredentialsProvider( - new StaticVaultUrlResolver("foo"), + StaticIamRoleCerberusCredentialsProvider provider = new StaticIamRoleCerberusCredentialsProvider( + new StaticCerberusUrlResolver("foo"), ROLE_ARN, REGION ); @@ -121,7 +121,7 @@ public void test_constructor_7() { @Test public void test_constructor_8() { - StaticIamRoleVaultCredentialsProvider provider = new StaticIamRoleVaultCredentialsProvider( + StaticIamRoleCerberusCredentialsProvider provider = new StaticIamRoleCerberusCredentialsProvider( "foo", ROLE_ARN, REGION diff --git a/src/test/resources/com/nike/cerberus/client/auth.json b/src/test/resources/com/nike/cerberus/client/auth.json new file mode 100644 index 0000000..2524075 --- /dev/null +++ b/src/test/resources/com/nike/cerberus/client/auth.json @@ -0,0 +1,14 @@ +{ + "auth": { + "client_token": "ABCD", + "policies": [ + "web", + "stage" + ], + "metadata": { + "user": "armon" + }, + "lease_duration": 3600, + "renewable": true + } +} \ No newline at end of file diff --git a/src/test/resources/com/nike/cerberus/client/error.json b/src/test/resources/com/nike/cerberus/client/error.json new file mode 100644 index 0000000..e35c726 --- /dev/null +++ b/src/test/resources/com/nike/cerberus/client/error.json @@ -0,0 +1,6 @@ +{ + "errors": [ + "message", + "oh noes" + ] +} \ No newline at end of file diff --git a/src/test/resources/com/nike/cerberus/client/list.json b/src/test/resources/com/nike/cerberus/client/list.json new file mode 100644 index 0000000..22954c3 --- /dev/null +++ b/src/test/resources/com/nike/cerberus/client/list.json @@ -0,0 +1,9 @@ +{ + "auth": null, + "data": { + "keys": ["foo", "foo/"] + }, + "lease_duration": 2592000, + "lease_id": "", + "renewable": false +} \ No newline at end of file diff --git a/src/test/resources/com/nike/cerberus/client/secret.json b/src/test/resources/com/nike/cerberus/client/secret.json new file mode 100644 index 0000000..cfe426a --- /dev/null +++ b/src/test/resources/com/nike/cerberus/client/secret.json @@ -0,0 +1,9 @@ +{ + "lease_id": "", + "renewable": false, + "lease_duration": 2592000, + "data": { + "value": "world" + }, + "auth": null +} \ No newline at end of file From c38f90f0e33c98f7d5f4a42ab4265086cd3761d0 Mon Sep 17 00:00:00 2001 From: Shaun Ford Date: Mon, 23 Apr 2018 15:46:07 -0700 Subject: [PATCH 2/3] Update copyrights --- .../client/auth/aws/CerberusClientTest.java | 2 +- .../com/nike/cerberus/client/CerberusClient.java | 16 ++++++++++++++++ .../cerberus/client/CerberusClientException.java | 16 ++++++++++++++++ .../cerberus/client/CerberusClientFactory.java | 2 +- .../cerberus/client/CerberusServerException.java | 16 ++++++++++++++++ .../com/nike/cerberus/client/ClientVersion.java | 2 +- .../client/DefaultCerberusClientFactory.java | 2 +- .../client/DefaultCerberusUrlResolver.java | 2 +- .../client/StaticCerberusUrlResolver.java | 2 +- .../com/nike/cerberus/client/UrlResolver.java | 16 ++++++++++++++++ .../client/auth/CerberusCredentials.java | 16 ++++++++++++++++ .../client/auth/CerberusCredentialsProvider.java | 16 ++++++++++++++++ .../auth/CerberusCredentialsProviderChain.java | 16 ++++++++++++++++ .../DefaultCerberusCredentialsProviderChain.java | 2 +- .../EnvironmentCerberusCredentialsProvider.java | 2 +- ...ystemPropertyCerberusCredentialsProvider.java | 2 +- .../client/auth/TokenCerberusCredentials.java | 16 ++++++++++++++++ .../auth/aws/BaseAwsCredentialsProvider.java | 2 +- .../InstanceRoleCerberusCredentialsProvider.java | 2 +- .../LambdaRoleCerberusCredentialsProvider.java | 2 +- ...StaticIamRoleCerberusCredentialsProvider.java | 2 +- .../nike/cerberus/client/http/HttpHeader.java | 16 ++++++++++++++++ .../nike/cerberus/client/http/HttpMethod.java | 2 +- .../nike/cerberus/client/http/HttpStatus.java | 2 +- .../client/model/CerberusAuthResponse.java | 2 +- .../model/CerberusClientTokenResponse.java | 2 +- .../client/model/CerberusListResponse.java | 2 +- .../cerberus/client/model/CerberusResponse.java | 2 +- .../client/CerberusClientFactoryTest.java | 2 +- .../nike/cerberus/client/CerberusClientTest.java | 2 +- .../nike/cerberus/client/ClientVersionTest.java | 2 +- .../client/DefaultCerberusClientFactoryTest.java | 2 +- .../client/DefaultCerberusUrlResolverTest.java | 2 +- .../client/StaticCerberusUrlResolverTest.java | 2 +- .../CerberusCredentialsProviderChainTest.java | 2 +- ...aultCerberusCredentialsProviderChainTest.java | 2 +- ...vironmentCerberusCredentialsProviderTest.java | 2 +- ...mPropertyCerberusCredentialsProviderTest.java | 2 +- .../auth/TokenCerberusCredentialsTest.java | 2 +- .../auth/aws/BaseAwsCredentialsProviderTest.java | 2 +- .../auth/aws/BaseCredentialsProviderTest.java | 2 +- ...tanceRoleCerberusCredentialsProviderTest.java | 2 +- ...ambdaRoleCerberusCredentialsProviderTest.java | 2 +- ...icIamRoleCerberusCredentialsProviderTest.java | 2 +- 44 files changed, 179 insertions(+), 35 deletions(-) diff --git a/src/integration/java/com/nike/cerberus/client/auth/aws/CerberusClientTest.java b/src/integration/java/com/nike/cerberus/client/auth/aws/CerberusClientTest.java index 1d2ad03..8f53d40 100644 --- a/src/integration/java/com/nike/cerberus/client/auth/aws/CerberusClientTest.java +++ b/src/integration/java/com/nike/cerberus/client/auth/aws/CerberusClientTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/CerberusClient.java b/src/main/java/com/nike/cerberus/client/CerberusClient.java index 21d3930..3836969 100644 --- a/src/main/java/com/nike/cerberus/client/CerberusClient.java +++ b/src/main/java/com/nike/cerberus/client/CerberusClient.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2018 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.nike.cerberus.client; import com.google.gson.FieldNamingPolicy; diff --git a/src/main/java/com/nike/cerberus/client/CerberusClientException.java b/src/main/java/com/nike/cerberus/client/CerberusClientException.java index f484f68..08c66d6 100644 --- a/src/main/java/com/nike/cerberus/client/CerberusClientException.java +++ b/src/main/java/com/nike/cerberus/client/CerberusClientException.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2018 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.nike.cerberus.client; public class CerberusClientException extends RuntimeException { diff --git a/src/main/java/com/nike/cerberus/client/CerberusClientFactory.java b/src/main/java/com/nike/cerberus/client/CerberusClientFactory.java index dacf2a9..52b8acf 100644 --- a/src/main/java/com/nike/cerberus/client/CerberusClientFactory.java +++ b/src/main/java/com/nike/cerberus/client/CerberusClientFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/CerberusServerException.java b/src/main/java/com/nike/cerberus/client/CerberusServerException.java index e7a3c07..16755f7 100644 --- a/src/main/java/com/nike/cerberus/client/CerberusServerException.java +++ b/src/main/java/com/nike/cerberus/client/CerberusServerException.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2018 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.nike.cerberus.client; import org.apache.commons.lang3.StringUtils; diff --git a/src/main/java/com/nike/cerberus/client/ClientVersion.java b/src/main/java/com/nike/cerberus/client/ClientVersion.java index 8e237b2..cc03539 100644 --- a/src/main/java/com/nike/cerberus/client/ClientVersion.java +++ b/src/main/java/com/nike/cerberus/client/ClientVersion.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/DefaultCerberusClientFactory.java b/src/main/java/com/nike/cerberus/client/DefaultCerberusClientFactory.java index a98f086..93a4533 100644 --- a/src/main/java/com/nike/cerberus/client/DefaultCerberusClientFactory.java +++ b/src/main/java/com/nike/cerberus/client/DefaultCerberusClientFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/DefaultCerberusUrlResolver.java b/src/main/java/com/nike/cerberus/client/DefaultCerberusUrlResolver.java index ac0e710..01b62bc 100644 --- a/src/main/java/com/nike/cerberus/client/DefaultCerberusUrlResolver.java +++ b/src/main/java/com/nike/cerberus/client/DefaultCerberusUrlResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/StaticCerberusUrlResolver.java b/src/main/java/com/nike/cerberus/client/StaticCerberusUrlResolver.java index ecc1945..0e751de 100644 --- a/src/main/java/com/nike/cerberus/client/StaticCerberusUrlResolver.java +++ b/src/main/java/com/nike/cerberus/client/StaticCerberusUrlResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/UrlResolver.java b/src/main/java/com/nike/cerberus/client/UrlResolver.java index d597d24..dae0971 100644 --- a/src/main/java/com/nike/cerberus/client/UrlResolver.java +++ b/src/main/java/com/nike/cerberus/client/UrlResolver.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2018 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.nike.cerberus.client; public interface UrlResolver { diff --git a/src/main/java/com/nike/cerberus/client/auth/CerberusCredentials.java b/src/main/java/com/nike/cerberus/client/auth/CerberusCredentials.java index 9574366..3012c21 100644 --- a/src/main/java/com/nike/cerberus/client/auth/CerberusCredentials.java +++ b/src/main/java/com/nike/cerberus/client/auth/CerberusCredentials.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2018 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.nike.cerberus.client.auth; public interface CerberusCredentials { diff --git a/src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProvider.java b/src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProvider.java index fda708e..081b85b 100644 --- a/src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProvider.java +++ b/src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProvider.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2018 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.nike.cerberus.client.auth; diff --git a/src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChain.java b/src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChain.java index 4da2d4d..42ccbfc 100644 --- a/src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChain.java +++ b/src/main/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChain.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2018 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.nike.cerberus.client.auth; import com.nike.cerberus.client.CerberusClientException; diff --git a/src/main/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChain.java b/src/main/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChain.java index fd846e9..b513ae6 100644 --- a/src/main/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChain.java +++ b/src/main/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChain.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProvider.java b/src/main/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProvider.java index b762528..72bccb6 100644 --- a/src/main/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProvider.java +++ b/src/main/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProvider.java b/src/main/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProvider.java index d663609..27e0c90 100644 --- a/src/main/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProvider.java +++ b/src/main/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/auth/TokenCerberusCredentials.java b/src/main/java/com/nike/cerberus/client/auth/TokenCerberusCredentials.java index 36d330f..3847c32 100644 --- a/src/main/java/com/nike/cerberus/client/auth/TokenCerberusCredentials.java +++ b/src/main/java/com/nike/cerberus/client/auth/TokenCerberusCredentials.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2018 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.nike.cerberus.client.auth; public class TokenCerberusCredentials implements CerberusCredentials { diff --git a/src/main/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProvider.java b/src/main/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProvider.java index cde474e..2825f50 100644 --- a/src/main/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProvider.java +++ b/src/main/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProvider.java b/src/main/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProvider.java index 345ba43..4238faf 100644 --- a/src/main/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProvider.java +++ b/src/main/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/auth/aws/LambdaRoleCerberusCredentialsProvider.java b/src/main/java/com/nike/cerberus/client/auth/aws/LambdaRoleCerberusCredentialsProvider.java index 817d0fa..74ea550 100644 --- a/src/main/java/com/nike/cerberus/client/auth/aws/LambdaRoleCerberusCredentialsProvider.java +++ b/src/main/java/com/nike/cerberus/client/auth/aws/LambdaRoleCerberusCredentialsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/auth/aws/StaticIamRoleCerberusCredentialsProvider.java b/src/main/java/com/nike/cerberus/client/auth/aws/StaticIamRoleCerberusCredentialsProvider.java index e0656d9..fb0130f 100644 --- a/src/main/java/com/nike/cerberus/client/auth/aws/StaticIamRoleCerberusCredentialsProvider.java +++ b/src/main/java/com/nike/cerberus/client/auth/aws/StaticIamRoleCerberusCredentialsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/http/HttpHeader.java b/src/main/java/com/nike/cerberus/client/http/HttpHeader.java index cea087e..ee5152f 100644 --- a/src/main/java/com/nike/cerberus/client/http/HttpHeader.java +++ b/src/main/java/com/nike/cerberus/client/http/HttpHeader.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2018 Nike, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.nike.cerberus.client.http; public class HttpHeader { diff --git a/src/main/java/com/nike/cerberus/client/http/HttpMethod.java b/src/main/java/com/nike/cerberus/client/http/HttpMethod.java index 2cfb92f..876b77b 100644 --- a/src/main/java/com/nike/cerberus/client/http/HttpMethod.java +++ b/src/main/java/com/nike/cerberus/client/http/HttpMethod.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/http/HttpStatus.java b/src/main/java/com/nike/cerberus/client/http/HttpStatus.java index d3dc91f..607930b 100644 --- a/src/main/java/com/nike/cerberus/client/http/HttpStatus.java +++ b/src/main/java/com/nike/cerberus/client/http/HttpStatus.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/model/CerberusAuthResponse.java b/src/main/java/com/nike/cerberus/client/model/CerberusAuthResponse.java index cda40e6..22bbedd 100644 --- a/src/main/java/com/nike/cerberus/client/model/CerberusAuthResponse.java +++ b/src/main/java/com/nike/cerberus/client/model/CerberusAuthResponse.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/model/CerberusClientTokenResponse.java b/src/main/java/com/nike/cerberus/client/model/CerberusClientTokenResponse.java index 396c330..e461832 100644 --- a/src/main/java/com/nike/cerberus/client/model/CerberusClientTokenResponse.java +++ b/src/main/java/com/nike/cerberus/client/model/CerberusClientTokenResponse.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/model/CerberusListResponse.java b/src/main/java/com/nike/cerberus/client/model/CerberusListResponse.java index 0f0fa3d..56b5bd3 100644 --- a/src/main/java/com/nike/cerberus/client/model/CerberusListResponse.java +++ b/src/main/java/com/nike/cerberus/client/model/CerberusListResponse.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/com/nike/cerberus/client/model/CerberusResponse.java b/src/main/java/com/nike/cerberus/client/model/CerberusResponse.java index ad8fd4b..6ed1423 100644 --- a/src/main/java/com/nike/cerberus/client/model/CerberusResponse.java +++ b/src/main/java/com/nike/cerberus/client/model/CerberusResponse.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/CerberusClientFactoryTest.java b/src/test/java/com/nike/cerberus/client/CerberusClientFactoryTest.java index 8915c2c..7a33dc0 100644 --- a/src/test/java/com/nike/cerberus/client/CerberusClientFactoryTest.java +++ b/src/test/java/com/nike/cerberus/client/CerberusClientFactoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/CerberusClientTest.java b/src/test/java/com/nike/cerberus/client/CerberusClientTest.java index 7bab335..2aa8fb3 100644 --- a/src/test/java/com/nike/cerberus/client/CerberusClientTest.java +++ b/src/test/java/com/nike/cerberus/client/CerberusClientTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/ClientVersionTest.java b/src/test/java/com/nike/cerberus/client/ClientVersionTest.java index 9619171..ddc009f 100644 --- a/src/test/java/com/nike/cerberus/client/ClientVersionTest.java +++ b/src/test/java/com/nike/cerberus/client/ClientVersionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/DefaultCerberusClientFactoryTest.java b/src/test/java/com/nike/cerberus/client/DefaultCerberusClientFactoryTest.java index 9a48443..12aa93e 100644 --- a/src/test/java/com/nike/cerberus/client/DefaultCerberusClientFactoryTest.java +++ b/src/test/java/com/nike/cerberus/client/DefaultCerberusClientFactoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/DefaultCerberusUrlResolverTest.java b/src/test/java/com/nike/cerberus/client/DefaultCerberusUrlResolverTest.java index 9ea0fd5..fc7012f 100644 --- a/src/test/java/com/nike/cerberus/client/DefaultCerberusUrlResolverTest.java +++ b/src/test/java/com/nike/cerberus/client/DefaultCerberusUrlResolverTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/StaticCerberusUrlResolverTest.java b/src/test/java/com/nike/cerberus/client/StaticCerberusUrlResolverTest.java index 269c2fb..d735f9c 100644 --- a/src/test/java/com/nike/cerberus/client/StaticCerberusUrlResolverTest.java +++ b/src/test/java/com/nike/cerberus/client/StaticCerberusUrlResolverTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChainTest.java b/src/test/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChainTest.java index 5fc0425..23be2dd 100644 --- a/src/test/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChainTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/CerberusCredentialsProviderChainTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChainTest.java b/src/test/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChainTest.java index 70f508d..13e8cd7 100644 --- a/src/test/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChainTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/DefaultCerberusCredentialsProviderChainTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProviderTest.java b/src/test/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProviderTest.java index d37d5fc..dace1eb 100644 --- a/src/test/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProviderTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/EnvironmentCerberusCredentialsProviderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProviderTest.java b/src/test/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProviderTest.java index ac742d2..61adcac 100644 --- a/src/test/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProviderTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/SystemPropertyCerberusCredentialsProviderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/auth/TokenCerberusCredentialsTest.java b/src/test/java/com/nike/cerberus/client/auth/TokenCerberusCredentialsTest.java index e174861..11b3d9d 100644 --- a/src/test/java/com/nike/cerberus/client/auth/TokenCerberusCredentialsTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/TokenCerberusCredentialsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProviderTest.java b/src/test/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProviderTest.java index fe89fba..ee012d1 100644 --- a/src/test/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProviderTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProviderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/auth/aws/BaseCredentialsProviderTest.java b/src/test/java/com/nike/cerberus/client/auth/aws/BaseCredentialsProviderTest.java index 760a35b..87d1ed9 100644 --- a/src/test/java/com/nike/cerberus/client/auth/aws/BaseCredentialsProviderTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/aws/BaseCredentialsProviderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProviderTest.java b/src/test/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProviderTest.java index 21a1464..1d03f21 100644 --- a/src/test/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProviderTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProviderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/auth/aws/LambdaRoleCerberusCredentialsProviderTest.java b/src/test/java/com/nike/cerberus/client/auth/aws/LambdaRoleCerberusCredentialsProviderTest.java index 891c358..86534da 100644 --- a/src/test/java/com/nike/cerberus/client/auth/aws/LambdaRoleCerberusCredentialsProviderTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/aws/LambdaRoleCerberusCredentialsProviderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/test/java/com/nike/cerberus/client/auth/aws/StaticIamRoleCerberusCredentialsProviderTest.java b/src/test/java/com/nike/cerberus/client/auth/aws/StaticIamRoleCerberusCredentialsProviderTest.java index c0cf478..b728173 100644 --- a/src/test/java/com/nike/cerberus/client/auth/aws/StaticIamRoleCerberusCredentialsProviderTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/aws/StaticIamRoleCerberusCredentialsProviderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Nike, Inc. + * Copyright (c) 2018 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. From d79c58e6863ab2647d57592ca451cb06783545ea Mon Sep 17 00:00:00 2001 From: Shaun Ford Date: Mon, 23 Apr 2018 15:52:36 -0700 Subject: [PATCH 3/3] Update README and variable names --- README.md | 18 +++++++++--------- .../client/DefaultCerberusUrlResolverTest.java | 6 +++--- .../client/StaticCerberusUrlResolverTest.java | 2 +- .../aws/BaseAwsCredentialsProviderTest.java | 14 +++++++------- ...nceRoleCerberusCredentialsProviderTest.java | 6 +++--- 5 files changed, 23 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 0f564fc..da709f0 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,9 @@ [![Coverage Status](https://coveralls.io/repos/github/Nike-Inc/cerberus-java-client/badge.svg?branch=master)](https://coveralls.io/github/Nike-Inc/cerberus-java-client) [![][license img]][license] -A java based client library for Cerberus that's built on top of Nike's Vault client. +A java based client library for Cerberus that's built on top of Nike's Cerberus client. -This library acts as a wrapper around the Nike developed Vault client by configuring the client to be Cerberus compatible. +This library acts as a wrapper around the Nike developed Cerberus client by configuring the client to be Cerberus compatible. To learn more about Cerberus, please see the [Cerberus website](http://engineering.nike.com/cerberus/). @@ -17,14 +17,14 @@ To learn more about Cerberus, please see the [Cerberus website](http://engineeri 2. Add the [Cerberus client dependency](https://bintray.com/nike/maven/cerberus-client) to your build (e.g. Maven, Gradle) 3. Provide an authentication mechanism. - For local development it is easiest to export a `CERBERUS_TOKEN` that you copied from the Cerberus dashboard. - When running in AWS, your application will not need this environmetal variable, instead it will automatically + When running in AWS, your application will not need this environment variable, instead it will automatically authenticate using its IAM role. Alternatively, set a `cerberus.token` System property. - If you would like to test IAM authentication locally, you can do that by [assuming a role](http://docs.aws.amazon.com/cli/latest/userguide/cli-roles.html). 4. Access secrets from Cerberus using Java ``` java String cerberusUrl = "https://cerberus.example.com"; - VaultClient vaultClient = DefaultCerberusClientFactory.getClient(cerberusUrl); - Map secrets = vaultClient.read("/app/my-sdb-name").getData(); + CerberusClient cerberusClient = DefaultCerberusClientFactory.getClient(cerberusUrl); + Map secrets = cerberusClient.read("/app/my-sdb-name").getData(); ``` ## Lambdas @@ -68,8 +68,8 @@ Setup the CERBERUS_ADDR environmental variable and access Cerberus using Java: ``` java String invokedFunctionArn = context.getInvokedFunctionArn(); - VaultClient vaultClient = DefaultCerberusClientFactory.getClientForLambda(invokedFunctionArn); - Map secrets = vaultClient.read("/app/my-sdb-name").getData(); + CerberusClient cerberusClient = DefaultCerberusClientFactory.getClientForLambda(invokedFunctionArn); + Map secrets = cerberusClient.read("/app/my-sdb-name").getData(); ``` ## More Configuration Options @@ -83,8 +83,8 @@ Provide the URL directly using the factory method `DefaultCerberusClientFactory. and then use the factory method that does not require a URL: ``` java - final VaultClient vaultClient = DefaultCerberusClientFactory.getClient(); - Map secrets = vaultClient.read("/app/my-sdb-name").getData(); + final CerberusClient cerberusClient = DefaultCerberusClientFactory.getClient(); + Map secrets = cerberusClient.read("/app/my-sdb-name").getData(); ``` ### Configuring Credentials diff --git a/src/test/java/com/nike/cerberus/client/DefaultCerberusUrlResolverTest.java b/src/test/java/com/nike/cerberus/client/DefaultCerberusUrlResolverTest.java index fc7012f..8194a9f 100644 --- a/src/test/java/com/nike/cerberus/client/DefaultCerberusUrlResolverTest.java +++ b/src/test/java/com/nike/cerberus/client/DefaultCerberusUrlResolverTest.java @@ -45,21 +45,21 @@ public void setup() { } @Test - public void lookupVaultUrl_returns_url_if_env_variable_is_set() { + public void lookupCerberusUrl_returns_url_if_env_variable_is_set() { when(System.getenv(DefaultCerberusUrlResolver.CERBERUS_ADDR_ENV_PROPERTY)).thenReturn(url); assertThat(subject.resolve()).isEqualTo(url); } @Test - public void lookupVaultUrl_returns_url_if_sys_property_is_set() { + public void lookupCerberusUrl_returns_url_if_sys_property_is_set() { when(System.getProperty(DefaultCerberusUrlResolver.CERBERUS_ADDR_SYS_PROPERTY)).thenReturn(url); assertThat(subject.resolve()).isEqualTo(url); } @Test - public void lookupVaultUrl_returns_null_if_env_and_sys_not_set() { + public void lookupCerberusUrl_returns_null_if_env_and_sys_not_set() { assertThat(subject.resolve()).isNull(); } } diff --git a/src/test/java/com/nike/cerberus/client/StaticCerberusUrlResolverTest.java b/src/test/java/com/nike/cerberus/client/StaticCerberusUrlResolverTest.java index d735f9c..6d48689 100644 --- a/src/test/java/com/nike/cerberus/client/StaticCerberusUrlResolverTest.java +++ b/src/test/java/com/nike/cerberus/client/StaticCerberusUrlResolverTest.java @@ -28,7 +28,7 @@ public class StaticCerberusUrlResolverTest { private final String testUrl = "https://localhost"; @Test(expected = IllegalArgumentException.class) - public void test_constructor_throws_error_if_vault_url_is_blank() { + public void test_constructor_throws_error_if_cerberus_url_is_blank() { new StaticCerberusUrlResolver(" "); } diff --git a/src/test/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProviderTest.java b/src/test/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProviderTest.java index ee012d1..0d1b2fd 100644 --- a/src/test/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProviderTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/aws/BaseAwsCredentialsProviderTest.java @@ -38,14 +38,14 @@ public class BaseAwsCredentialsProviderTest extends BaseCredentialsProviderTest{ public static final Region REGION = RegionUtils.getRegion("us-west-2"); public static final String CERBERUS_TEST_ARN = "arn:aws:iam::123456789012:role/cerberus-test-role"; - public static final String ERROR_RESPONSE = "Error calling vault"; + public static final String ERROR_RESPONSE = "Error calling cerberus"; protected static final String MISSING_AUTH_DATA = "{}"; private BaseAwsCredentialsProvider provider; private UrlResolver urlResolver; - private String vaultUrl; + private String cerberusUrl; private MockWebServer mockWebServer; @Before @@ -57,7 +57,7 @@ public void setUp() throws Exception { mockWebServer = new MockWebServer(); mockWebServer.start(); - vaultUrl = "http://localhost:" + mockWebServer.getPort(); + cerberusUrl = "http://localhost:" + mockWebServer.getPort(); } @After @@ -79,9 +79,9 @@ public void decryptToken_throws_exception_when_non_encrypted_data_provided() { @Test(expected = CerberusServerException.class) public void getEncryptedAuthData_throws_exception_on_bad_response_code() throws IOException { - when(urlResolver.resolve()).thenReturn(vaultUrl); + when(urlResolver.resolve()).thenReturn(cerberusUrl); - System.setProperty(DefaultCerberusUrlResolver.CERBERUS_ADDR_SYS_PROPERTY, vaultUrl); + System.setProperty(DefaultCerberusUrlResolver.CERBERUS_ADDR_SYS_PROPERTY, cerberusUrl); mockWebServer.enqueue(new MockResponse().setResponseCode(400).setBody(ERROR_RESPONSE)); provider.getEncryptedAuthData(CERBERUS_TEST_ARN, REGION); @@ -89,9 +89,9 @@ public void getEncryptedAuthData_throws_exception_on_bad_response_code() throws @Test(expected = CerberusClientException.class) public void getEncryptedAuthData_throws_exception_on_missing_auth_data() throws IOException { - when(urlResolver.resolve()).thenReturn(vaultUrl); + when(urlResolver.resolve()).thenReturn(cerberusUrl); - System.setProperty(DefaultCerberusUrlResolver.CERBERUS_ADDR_SYS_PROPERTY, vaultUrl); + System.setProperty(DefaultCerberusUrlResolver.CERBERUS_ADDR_SYS_PROPERTY, cerberusUrl); mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(MISSING_AUTH_DATA)); provider.getEncryptedAuthData(CERBERUS_TEST_ARN, REGION); diff --git a/src/test/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProviderTest.java b/src/test/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProviderTest.java index 1d03f21..ab99926 100644 --- a/src/test/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProviderTest.java +++ b/src/test/java/com/nike/cerberus/client/auth/aws/InstanceRoleCerberusCredentialsProviderTest.java @@ -85,14 +85,14 @@ public void getCredentials_returns_valid_credentials() throws IOException { MockWebServer mockWebServer = new MockWebServer(); mockWebServer.start(); - final String vaultUrl = "http://localhost:" + mockWebServer.getPort(); + final String cerberusUrl = "http://localhost:" + mockWebServer.getPort(); mockGetIamSecurityCredentials(DEFAULT_ROLE); mockGetIamInstanceProfileInfo(GOOD_INSTANCE_PROFILE_ARN); mockDecrypt(kmsClient, DECODED_AUTH_DATA); - when(urlResolver.resolve()).thenReturn(vaultUrl); + when(urlResolver.resolve()).thenReturn(cerberusUrl); - System.setProperty(DefaultCerberusUrlResolver.CERBERUS_ADDR_SYS_PROPERTY, vaultUrl); + System.setProperty(DefaultCerberusUrlResolver.CERBERUS_ADDR_SYS_PROPERTY, cerberusUrl); mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(AUTH_RESPONSE)); CerberusCredentials credentials = provider.getCredentials();