com.microsoft.azure.keyvault.models.SecretBundle Java Examples

The following examples show how to use com.microsoft.azure.keyvault.models.SecretBundle. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AzureKeyVaultService.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Override
public String getSecret(AzureGetSecretData azureGetSecretData) {
    SecretBundle secretBundle;

    if (azureGetSecretData.getSecretVersion() != null) {
        secretBundle = azureKeyVaultClientDelegate.getSecret(vaultUrl, azureGetSecretData.getSecretName(), azureGetSecretData.getSecretVersion());
    } else {
        secretBundle = azureKeyVaultClientDelegate.getSecret(vaultUrl, azureGetSecretData.getSecretName());
    }

    if (secretBundle == null) {
        throw new VaultSecretNotFoundException("Azure Key Vault secret " + azureGetSecretData.getSecretName() + " was not found in vault " + vaultUrl);
    }

    return secretBundle.value();
}
 
Example #2
Source File: SecretImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public Observable<Secret> updateResourceAsync() {
    Observable<Secret> set = Observable.just((Secret) this);
    if (setSecretRequest != null) {
        set = createResourceAsync();
    }
    return set.flatMap(new Func1<Secret, Observable<SecretBundle>>() {
        @Override
        public Observable<SecretBundle> call(Secret secret) {
            return Observable.from(vault.client().updateSecretAsync(updateSecretRequest.build(), null));
        }
    }).flatMap(new Func1<SecretBundle, Observable<Secret>>() {
        @Override
        public Observable<Secret> call(SecretBundle secretBundle) {
            return refreshAsync();
        }
    }).doOnCompleted(new Action0() {
        @Override
        public void call() {
            setSecretRequest = null;
            updateSecretRequest = new UpdateSecretRequest.Builder(vault.vaultUri(), name());
        }
    });
}
 
Example #3
Source File: SecretOperationsTest.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
private static void validateSecret(SecretBundle secret, String vault, String name, String value, String contentType,
		Attributes attributes) throws Exception {
	String prefix = vault + "/secrets/" + name + "/";
	String id = secret.id();
	Assert.assertTrue( //
			String.format("\"id\" should start with \"%s\", but instead the value is \"%s\".", prefix, id), //
			id.startsWith(prefix));
	Assert.assertEquals(value, secret.value());
	if (contentType != null) {
		Assert.assertEquals(contentType, secret.contentType());
	}
	Assert.assertNotNull("\"created\" should not be null.", secret.attributes().created());
	Assert.assertNotNull("\"updated\" should not be null.", secret.attributes().updated());
	DeletionRecoveryLevel deletionRecoveryLevel = secret.attributes().recoveryLevel();
	Assert.assertNotNull(deletionRecoveryLevel);

	Assert.assertTrue(secret.managed() == null || secret.managed() == false);
}
 
Example #4
Source File: AzureKeyVaultStore.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
@Override
public AppCredentials getAppCredentials(String keyName, String secretName) throws IOException {
  String normalizedKey = normalize(keyName);
  SecretBundle keyBundle = vaultClient.getSecret(vaultUrl, normalizedKey);
  if (keyBundle == null) {
    throw new IOException(("Key not found: " + secretName));
  }
  String keyValue = keyBundle.value();

  String normalizedSecret = normalize(secretName);
  SecretBundle secretBundle = vaultClient.getSecret(vaultUrl, normalizedSecret);
  if (secretBundle == null) {
    throw new IOException(("Key not found: " + secretName));
  }
  String secretValue = secretBundle.value();

  return new AppCredentials(keyValue, secretValue);
}
 
Example #5
Source File: AzureKeyVaultServiceTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void getSecretGetsSpecificVersionOfSecretIfVersionProvided() {
    String secretName = "name";
    String secretVersion = "version";

    AzureGetSecretData getSecretData = mock(AzureGetSecretData.class);
    when(getSecretData.getSecretName()).thenReturn(secretName);
    when(getSecretData.getSecretVersion()).thenReturn(secretVersion);

    SecretBundle secretBundle = mock(SecretBundle.class);
    when(azureKeyVaultClientDelegate.getSecret(anyString(), anyString(), anyString())).thenReturn(secretBundle);
    when(secretBundle.value()).thenReturn("value");

    keyVaultService.getSecret(getSecretData);

    verify(azureKeyVaultClientDelegate).getSecret(vaultUrl, secretName, secretVersion);
}
 
Example #6
Source File: AzureKeyVaultServiceTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void getSecretGetsLatestVersionOfSecretIfNoVersionProvided() {
    String secretName = "name";

    AzureGetSecretData getSecretData = mock(AzureGetSecretData.class);
    when(getSecretData.getSecretName()).thenReturn(secretName);
    when(getSecretData.getSecretVersion()).thenReturn(null);

    SecretBundle secretBundle = mock(SecretBundle.class);
    when(azureKeyVaultClientDelegate.getSecret(anyString(), anyString())).thenReturn(secretBundle);
    when(secretBundle.value()).thenReturn("value");

    keyVaultService.getSecret(getSecretData);

    verify(azureKeyVaultClientDelegate).getSecret(vaultUrl, secretName);
}
 
Example #7
Source File: TestAzureKeyVaultCredentialStore.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testAzureKeyVaultCredentialValueOptions() throws StageException {
  AzureKeyVaultCredentialStore store = new AzureKeyVaultCredentialStore();
  CredentialStore.Context context = Mockito.mock(CredentialStore.Context.class);
  store = Mockito.spy(store);

  KeyVaultClient keyVaultClient = PowerMockito.mock(KeyVaultClient.class);
  Mockito.doReturn(keyVaultClient).when(store).createClient();
  Mockito.when(keyVaultClient.getSecret(Mockito.any(), Mockito.any())).thenReturn(new SecretBundle());

  Mockito.when(context.getConfig(Mockito.any())).thenReturn("test");

  Configuration configuration = Mockito.mock(Configuration.class);
  Mockito.doReturn(configuration).when(store).getConfiguration();
  Mockito.when(configuration.get(AzureKeyVaultCredentialStore.CREDENTIAL_REFRESH_PROP,
      AzureKeyVaultCredentialStore.CREDENTIAL_REFRESH_DEFAULT
  ))
         .thenReturn(AzureKeyVaultCredentialStore.CREDENTIAL_REFRESH_DEFAULT);

  Mockito.when(configuration.get(AzureKeyVaultCredentialStore.CREDENTIAL_RETRY_PROP,
      AzureKeyVaultCredentialStore.CREDENTIAL_RETRY_DEFAULT
  ))
         .thenReturn(AzureKeyVaultCredentialStore.CREDENTIAL_RETRY_DEFAULT);

  Mockito.when(context.getConfig(store.CACHE_EXPIRATION_PROP)).thenReturn(null);

  Assert.assertTrue(store.init(context).isEmpty());

  CredentialValue c = store.get("g", "n", "refresh=1,retry=2");
  Assert.assertNotNull(c);
  AzureKeyVaultCredentialStore.AzureKeyVaultCredentialValue
      cc
      = (AzureKeyVaultCredentialStore.AzureKeyVaultCredentialValue) c;
  Assert.assertEquals(1L, cc.getRefreshMillis());
  Assert.assertEquals(2L, cc.getRetryMillis());

  store.destroy();
}
 
Example #8
Source File: TestAzureKeyVaultCredentialStore.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testInit_noIssues() {
  AzureKeyVaultCredentialStore store = new AzureKeyVaultCredentialStore();
  CredentialStore.Context context = Mockito.mock(CredentialStore.Context.class);
  store = Mockito.spy(store);

  KeyVaultClient keyVaultClient = PowerMockito.mock(KeyVaultClient.class);
  Mockito.doReturn(keyVaultClient).when(store).createClient();
  Mockito.when(keyVaultClient.getSecret(Mockito.any(), Mockito.any())).thenReturn(new SecretBundle());

  Mockito.when(context.getConfig(Mockito.any())).thenReturn("test");

  Configuration configuration = Mockito.mock(Configuration.class);
  Mockito.doReturn(configuration).when(store).getConfiguration();
  Mockito.when(configuration.get(AzureKeyVaultCredentialStore.CREDENTIAL_REFRESH_PROP,
      AzureKeyVaultCredentialStore.CREDENTIAL_REFRESH_DEFAULT
  ))
         .thenReturn(AzureKeyVaultCredentialStore.CREDENTIAL_REFRESH_DEFAULT);

  Mockito.when(configuration.get(AzureKeyVaultCredentialStore.CREDENTIAL_RETRY_PROP,
      AzureKeyVaultCredentialStore.CREDENTIAL_RETRY_DEFAULT
  ))
         .thenReturn(AzureKeyVaultCredentialStore.CREDENTIAL_RETRY_DEFAULT);

  Mockito.when(context.getConfig(store.CACHE_EXPIRATION_PROP)).thenReturn(null);

  Assert.assertEquals(0, store.init(context).size());
}
 
Example #9
Source File: SecretOperationsTest.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
private void compareSecrets(SecretBundle expected, SecretBundle actual) {
	Assert.assertEquals(expected.contentType(), actual.contentType());
	Assert.assertEquals(expected.id(), actual.id());
	Assert.assertEquals(expected.value(), actual.value());
	Assert.assertEquals(expected.attributes().enabled(), actual.attributes().enabled());
	if (expected.tags() != null || actual.tags() != null)
		Assert.assertTrue(expected.tags().equals(actual.tags()));

}
 
Example #10
Source File: SecretsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public ServiceFuture<Secret> getByIdAsync(final String id, final ServiceCallback<Secret> callback) {
    return new KeyVaultFutures.ServiceFutureConverter<SecretBundle, Secret>() {

        @Override
        protected ServiceFuture<SecretBundle> callAsync() {
            return inner.getSecretAsync(id, null);
        }

        @Override
        protected Secret wrapModel(SecretBundle secretBundle) {
            return SecretsImpl.this.wrapModel(secretBundle);
        }
    }.toFuture(callback);
}
 
Example #11
Source File: SecretsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
protected SecretImpl wrapModel(SecretBundle inner) {
    if (inner == null) {
        return null;
    }
    return new SecretImpl(inner.secretIdentifier().name(), inner, vault);
}
 
Example #12
Source File: SecretsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
private SecretImpl wrapModel(SecretItem inner) {
    if (inner == null) {
        return null;
    }
    SerializerAdapter<?> serializer = vault.manager().inner().restClient().serializerAdapter();
    try {
        return wrapModel(serializer.<SecretBundle>deserialize(serializer.serialize(inner), SecretBundle.class));
    } catch (IOException e) {
        return null;
    }
}
 
Example #13
Source File: SecretsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<Secret> getByNameAsync(final String name) {
    return new KeyVaultFutures.ServiceFutureConverter<SecretBundle, Secret>() {

        @Override
        ServiceFuture<SecretBundle> callAsync() {
            return inner.getSecretAsync(vault.vaultUri(), name, null);
        }

        @Override
        Secret wrapModel(SecretBundle o) {
            return null;
        }
    }.toObservable();
}
 
Example #14
Source File: SecretsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<Secret> getByNameAndVersionAsync(final String name, final String version) {
    return new KeyVaultFutures.ServiceFutureConverter<SecretBundle, Secret>() {

        @Override
        ServiceFuture<SecretBundle> callAsync() {
            return inner.getSecretAsync(vault.vaultUri(), name, version, null);
        }

        @Override
        Secret wrapModel(SecretBundle o) {
            return null;
        }
    }.toObservable();
}
 
Example #15
Source File: KeyVaultKeyResolver.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
@Override
public IKey apply(SecretBundle secretBundle) {

    if (secretBundle != null && secretBundle.contentType().equalsIgnoreCase("application/octet-stream")) {
        byte[] keyBytes = BASE64.decode(secretBundle.value());

        if (keyBytes != null) {
            return new SymmetricKey(secretBundle.id(), keyBytes, provider);
        }
    }

    return null;
}
 
Example #16
Source File: CertificateOperationsTest.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
private void validatePem(CertificateBundle certificateBundle, String subjectName) throws CertificateException, IOException, KeyVaultErrorException, IllegalArgumentException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    // Load the CER part into X509Certificate object
    X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle);

    Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName));
    Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName));
    
    // Retrieve the secret backing the certificate
    SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier();
    SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier());
    Assert.assertTrue(secret.managed());
    String secretValue = secret.value();

    // Extract private key from PEM
    PrivateKey secretPrivateKey = extractPrivateKeyFromPemContents(secretValue);
    Assert.assertNotNull(secretPrivateKey);

    // Extract certificates from PEM
    List<X509Certificate> certificates = extractCertificatesFromPemContents(secretValue);
    Assert.assertNotNull(certificates);
    Assert.assertTrue(certificates.size() == 1);

    // has the public key corresponding to the private key.
    X509Certificate secretCertificate = certificates.get(0);
    Assert.assertNotNull(secretCertificate);
    Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName()
            .equals(x509Certificate.getSubjectX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName()
            .equals(x509Certificate.getIssuerX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber()));

    // Create a KeyPair with the private key from the KeyStore and public
    // key from the certificate to verify they match
    KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey);
    Assert.assertNotNull(keyPair);
    verifyRSAKeyPair(keyPair);
}
 
Example #17
Source File: CertificateOperationsTest.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
private KeyStore loadSecretToKeyStore(SecretBundle secret, String secretPassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    ByteArrayInputStream secretStream = new ByteArrayInputStream(_base64.decode(secret.value()));
    KeyStore keyStore = KeyStore.getInstance(PKCS12);
    keyStore.load(secretStream, secretPassword.toCharArray());
    secretStream.close();
    return keyStore;
}
 
Example #18
Source File: AzureKeyVaultClientDelegate.java    From tessera with Apache License 2.0 4 votes vote down vote up
SecretBundle getSecret(String vaultBaseUrl, String secretName) {
    return keyVaultClient.getSecret(vaultBaseUrl, secretName);
}
 
Example #19
Source File: AsyncOperationsTest.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
@Test
public void secretAsyncForAsyncOperationsTest() throws Exception {

	String vault = getVaultUri();
	String secretname = "mySecret";
	String password = "password";

	SetSecretRequest setSecretRequest = new SetSecretRequest.Builder(vault, secretname, password).build();
	SecretBundle secretBundle = keyVaultClient.setSecretAsync(setSecretRequest, null).get();
	Assert.assertNotNull(secretBundle);

	UpdateSecretRequest updateSecretRequest = new UpdateSecretRequest.Builder(secretBundle.id()).build();
	secretBundle = keyVaultClient.updateSecretAsync(updateSecretRequest, null).get();
	Assert.assertNotNull(secretBundle);

	secretBundle = keyVaultClient.getSecretAsync(secretBundle.id(), null).get();
	Assert.assertNotNull(secretBundle);

	List<SecretItem> secretItems = keyVaultClient.listSecretsAsync(vault, 2, null).get();
	Assert.assertNotNull(secretItems);

	List<SecretItem> secretVersionItems = keyVaultClient.listSecretVersionsAsync(vault, secretname, 2, null).get();
	Assert.assertNotNull(secretVersionItems);

	secretBundle = keyVaultClient.deleteSecretAsync(vault, secretname, null).get();
	Assert.assertNotNull(secretBundle);

	try {
		keyVaultClient.deleteSecretAsync(vault, secretname, null).get();

	} catch (ExecutionException ex) {

		Throwable t = ex.getCause();
		if (t instanceof KeyVaultErrorException) {
			Assert.assertEquals("SecretNotFound", ((KeyVaultErrorException) t).body().error().code());
		} else
			throw ex;
	}
	pollOnSecretDeletion(vault, secretname);
	keyVaultClient.purgeDeletedSecretAsync(vault, secretname, null).get();
	Thread.sleep(20000);
}
 
Example #20
Source File: CertificateOperationsTest.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
/**
 * Create a self-signed certificate in PKCS12 format (which includes the
 * private key) certificate.
 * 
 * @throws Exception
 */
@Test
public void createSelfSignedCertificatePkcs12ForCertificateOperationsTest() throws Exception {
    // Set content type to indicate the certificate is PKCS12 format.
    SecretProperties secretProperties = new SecretProperties()
                                    .withContentType(MIME_PKCS12);

    String subjectName = "CN=SelfSignedJavaPkcs12";
    X509CertificateProperties x509Properties = new X509CertificateProperties()
                .withSubject(subjectName)
                .withValidityInMonths(12);

    // Set issuer to "Self"
    IssuerParameters issuerParameters = new IssuerParameters()
                .withName(ISSUER_SELF);

    CertificatePolicy certificatePolicy = new CertificatePolicy()
                .withSecretProperties(secretProperties)
                .withIssuerParameters(issuerParameters)
                .withX509CertificateProperties(x509Properties);

    Attributes attribute = new CertificateAttributes()
            .withEnabled(true)
            .withExpires(new DateTime().withYear(2050).withMonthOfYear(1))
            .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1));
    
    String vaultUri = getVaultUri();
    String certificateName = "createSelfSignedJavaPkcs12";
    
    CreateCertificateRequest createCertificateRequest = 
            new CreateCertificateRequest
                .Builder(vaultUri, certificateName)
                    .withPolicy(certificatePolicy)
                    .withAttributes(attribute)
                    .withTags(sTags)
                    .build();
    
    CertificateOperation certificateOperation = keyVaultClient.createCertificate(createCertificateRequest);

    Assert.assertNotNull(certificateOperation);
    Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS));

    CertificateBundle certificateBundle = pollOnCertificateOperation(certificateOperation);
    validateCertificateBundle(certificateBundle, certificatePolicy);
    compareAttributes(attribute, createCertificateRequest.certificateAttributes());

    // Load the CER part into X509Certificate object
    X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle);

    Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName));
    Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName));

    // Retrieve the secret backing the certificate
    SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier();
    SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier());
    Assert.assertTrue(secret.managed());

    // Retrieve the key backing the certificate
    KeyIdentifier keyIdentifier = certificateBundle.keyIdentifier();
    KeyBundle keyBundle = keyVaultClient.getKey(keyIdentifier.baseIdentifier());
    Assert.assertTrue(keyBundle.managed());
    
    // Load the secret into a KeyStore
    String secretPassword = "";
    KeyStore keyStore = loadSecretToKeyStore(secret, secretPassword);

    // Validate the certificate and key in the KeyStore
    validateCertificateKeyInKeyStore(keyStore, x509Certificate, secretPassword);

    CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName);
    Assert.assertNotNull(deletedCertificateBundle);
    
    pollOnCertificateDeletion(getVaultUri(), certificateName);
    try {
        keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier());
    } catch (KeyVaultErrorException e) {
        Assert.assertNotNull(e.body().error());
        Assert.assertEquals("CertificateNotFound", e.body().error().code());
    }
    
    keyVaultClient.purgeDeletedCertificate(getVaultUri(), certificateName);
    Thread.sleep(20000);
}
 
Example #21
Source File: CertificateOperationsTest.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
/**
 * Import a PKCS12 format (which includes the private key) certificate.
 */
@Test
public void importCertificatePkcs12ForCertificateOperationsTest() throws Exception {
    String certificateContent = "MIIJOwIBAzCCC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gIH0ICCAojmRBO+CPfVNUO0s+BVuwhOzikAGNBmQHNChmJ/pyzPbMUbx7tO63eIVSc67iERda2WCEmVwPigaVQkPaumsfp8+L6iV/BMf5RKlyRXcwh0vUdu2Qa7qadD+gFQ2kngf4Dk6vYo2/2HxayuIf6jpwe8vql4ca3ZtWXfuRix2fwgltM0bMz1g59d7x/glTfNqxNlsty0A/rWrPJjNbOPRU2XykLuc3AtlTtYsQ32Zsmu67A7UNBw6tVtkEXlFDqhavEhUEO3dvYqMY+QLxzpZhA0q44ZZ9/ex0X6QAFNK5wuWxCbupHWsgxRwKftrxyszMHsAvNoNcTlqcctee+ecNwTJQa1/MDbnhO6/qHA7cfG1qYDq8Th635vGNMW1w3sVS7l0uEvdayAsBHWTcOC2tlMa5bfHrhY8OEIqj5bN5H9RdFy8G/W239tjDu1OYjBDydiBqzBn8HG1DSj1Pjc0kd/82d4ZU0308KFTC3yGcRad0GnEH0Oi3iEJ9HbriUbfVMbXNHOF+MktWiDVqzndGMKmuJSdfTBKvGFvejAWVO5E4mgLvoaMmbchc3BO7sLeraHnJN5hvMBaLcQI38N86mUfTR8AP6AJ9c2k514KaDLclm4z6J8dMz60nUeo5D3YD09G6BavFHxSvJ8MF0Lu5zOFzEePDRFm9mH8W0N/sFlIaYfD/GWU/w44mQucjaBk95YtqOGRIj58tGDWr8iUdHwaYKGqU24zGeRae9DhFXPzZshV1ZGsBQFRaoYkyLAwdJWIXTi+c37YaC8FRSEnnNmS79Dou1Kc3BvK4EYKAD2KxjtUebrV174gD0Q+9YuJ0GXOTspBvCFd5VT2Rw5zDNrA/J3F5fMCk4wOzAfMAcGBSsOAwIaBBSxgh2xyF+88V4vAffBmZXv8Txt4AQU4O/NX4MjxSodbE7ApNAMIvrtREwCAgfQ";
    String certificatePassword = "123";

    // Set content type to indicate the certificate is PKCS12 format.
    SecretProperties secretProperties = new SecretProperties().withContentType(MIME_PKCS12);
    CertificatePolicy certificatePolicy = new CertificatePolicy().withSecretProperties(secretProperties);
    Attributes attribute = new CertificateAttributes().withEnabled(true);

    String vaultUri = getVaultUri();
    String certificateName = "importCertPkcs";
    CertificateBundle certificateBundle = keyVaultClient.importCertificate(
            new ImportCertificateRequest
                .Builder(vaultUri, certificateName, certificateContent)
                .withPassword(certificatePassword)
                .withPolicy(certificatePolicy)
                .withAttributes(attribute)
                .withTags(sTags)
                .build());

    // Validate the certificate bundle created
    validateCertificateBundle(certificateBundle, certificatePolicy);        
    Assert.assertTrue(toHexString(certificateBundle.x509Thumbprint()).equalsIgnoreCase("7cb8b7539d87ba7215357b9b9049dff2d3fa59ba"));
    Assert.assertEquals(attribute.enabled(), certificateBundle.attributes().enabled());
    
    // Load the CER part into X509Certificate object
    X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle);

    Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals("CN=KeyVaultTest"));
    Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals("CN=Root Agency"));

    // Retrieve the secret backing the certificate
    SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier();
    SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier());
    Assert.assertTrue(secret.managed());
    
    // Load the secret into a KeyStore
    String secretPassword = "";
    KeyStore keyStore = loadSecretToKeyStore(secret, secretPassword);

    // Validate the certificate and key in the KeyStore
    validateCertificateKeyInKeyStore(keyStore, x509Certificate, secretPassword);

    CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(), certificateName);
    pollOnCertificateDeletion(getVaultUri(), certificateName);
    
    try {
        keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier());
    } catch (KeyVaultErrorException e) {
        Assert.assertNotNull(e.body().error());
        Assert.assertEquals("CertificateNotFound", e.body().error().code());
    }
    
    keyVaultClient.purgeDeletedCertificate(getVaultUri(), certificateName);
    Thread.sleep(10000);
}
 
Example #22
Source File: SecretOperationsTest.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
@Test
public void listSecretVersionsForSecretOperationsTest() throws Exception {
	final String listVersionSecretName = "javaSecretVersions";
	HashSet<String> secrets = new HashSet<String>();
	for (int i = 0; i < MAX_SECRETS; ++i) {
		int failureCount = 0;
		for (;;) {
			try {
				SecretBundle secret = keyVaultClient
						.setSecret(new SetSecretRequest.Builder(getVaultUri(), listVersionSecretName, SECRET_VALUE).build());
				secrets.add(secret.id());
				break;
			} catch (KeyVaultErrorException e) {
				++failureCount;
				if (e.body().error().code().equals("Throttled")) {
					System.out.println("Throttled!");
					if (isRecordMode()) {
						Thread.sleep(failureCount * 1500);
					}
					continue;
				}
				throw e;
			}
		}
	}

	PagedList<SecretItem> listResult = keyVaultClient.listSecretVersions(getVaultUri(), listVersionSecretName,
			PAGELIST_MAX_SECRETS);
	Assert.assertTrue(PAGELIST_MAX_SECRETS >= listResult.currentPage().items().size());

	listResult = keyVaultClient.listSecretVersions(getVaultUri(), listVersionSecretName);
	for (SecretItem item : listResult) {
		if (item != null) {
			secrets.remove(item.id());
		}
	}

	Assert.assertEquals(0, secrets.size());

	keyVaultClient.deleteSecret(getVaultUri(), listVersionSecretName);
	pollOnSecretDeletion(getVaultUri(), listVersionSecretName);
	keyVaultClient.purgeDeletedSecret(getVaultUri(), listVersionSecretName);

}
 
Example #23
Source File: TestAzureKeyVaultCredentialStore.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void testCache() throws StageException, InterruptedException {
  AzureKeyVaultCredentialStore store = new AzureKeyVaultCredentialStore();
  CredentialStore.Context context = Mockito.mock(CredentialStore.Context.class);
  store = Mockito.spy(store);

  KeyVaultClient keyVaultClient = PowerMockito.mock(KeyVaultClient.class);
  Mockito.doReturn(keyVaultClient).when(store).createClient();
  SecretBundle secretBundle = Mockito.mock(SecretBundle.class);
  Mockito.when(secretBundle.value()).thenReturn("secret");
  Mockito.when(keyVaultClient.getSecret(Mockito.any(), Mockito.any())).thenReturn(secretBundle);

  Mockito.when(context.getConfig(Mockito.any())).thenReturn("test");

  Configuration configuration = Mockito.mock(Configuration.class);
  Mockito.doReturn(configuration).when(store).getConfiguration();
  Mockito.when(configuration.get(AzureKeyVaultCredentialStore.CREDENTIAL_REFRESH_PROP,
      AzureKeyVaultCredentialStore.CREDENTIAL_REFRESH_DEFAULT
  ))
         .thenReturn(AzureKeyVaultCredentialStore.CREDENTIAL_REFRESH_DEFAULT);

  Mockito.when(configuration.get(AzureKeyVaultCredentialStore.CREDENTIAL_RETRY_PROP,
      AzureKeyVaultCredentialStore.CREDENTIAL_RETRY_DEFAULT
  ))
         .thenReturn(AzureKeyVaultCredentialStore.CREDENTIAL_RETRY_DEFAULT);

  Mockito.when(context.getConfig(store.CACHE_EXPIRATION_PROP)).thenReturn(null);

  Assert.assertTrue(store.init(context).isEmpty());
  CredentialValue credential1 = store.get("g", "n", "a=A,b=B");
  Assert.assertNotNull(credential1);
  Assert.assertEquals("secret", credential1.get());

  //within cache time
  CredentialValue credential2 = store.get("g", "n", "a=A,b=B");
  Assert.assertEquals(((AzureKeyVaultCredentialStore.AzureKeyVaultCredentialValue) credential1).getName(),
      ((AzureKeyVaultCredentialStore.AzureKeyVaultCredentialValue) credential2).getName()
  );
  Assert.assertEquals(((AzureKeyVaultCredentialStore.AzureKeyVaultCredentialValue) credential1).getOptions(),
      ((AzureKeyVaultCredentialStore.AzureKeyVaultCredentialValue) credential2).getOptions()
  );
  Assert.assertEquals(((AzureKeyVaultCredentialStore.AzureKeyVaultCredentialValue) credential1).getGroup(),
      ((AzureKeyVaultCredentialStore.AzureKeyVaultCredentialValue) credential2).getGroup()
  );

  Thread.sleep(201);
  //outside cache time.
  CredentialValue credential3 = store.get("g", "n", "a=A,b=B");
  Assert.assertNotSame(credential1, credential3);

  store.destroy();
}
 
Example #24
Source File: AzureKeyVaultClientDelegate.java    From tessera with Apache License 2.0 4 votes vote down vote up
SecretBundle getSecret(String vaultBaseUrl, String secretName, String secretVersion) {
    return keyVaultClient.getSecret(vaultBaseUrl, secretName, secretVersion);
}
 
Example #25
Source File: AzureKeyVaultClientDelegate.java    From tessera with Apache License 2.0 4 votes vote down vote up
SecretBundle setSecret(SetSecretRequest setSecretRequest) {
    return keyVaultClient.setSecret(setSecretRequest);
}
 
Example #26
Source File: AzureKeyVaultStore.java    From data-transfer-project with Apache License 2.0 4 votes vote down vote up
public String getSecret(String key) {
  String normalizedKey = normalize(key);
  SecretBundle secretBundle = vaultClient.getSecret(vaultUrl, normalizedKey);
  return secretBundle == null ? null : secretBundle.value();
}
 
Example #27
Source File: SecretImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
SecretImpl(String name, SecretBundle innerObject, Vault vault) {
    super(name, innerObject);
    this.vault = vault;
    this.updateSecretRequest = new UpdateSecretRequest.Builder(vault.vaultUri(), name);
}
 
Example #28
Source File: SecretImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
protected Observable<SecretBundle> getInnerAsync() {
    return Observable.from(vault.client().getSecretAsync(id(), null));
}
 
Example #29
Source File: SecretsImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
protected SecretImpl wrapModel(String name) {
    return new SecretImpl(name, new SecretBundle(), vault);
}
 
Example #30
Source File: KeyVaultKeyResolver.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
private ListenableFuture<IKey> resolveKeyFromSecretAsync(String kid) {
    
    ListenableFuture<SecretBundle> futureCall = client.getSecretAsync(kid, null);
    return Futures.transform(futureCall, new FutureKeyFromSecret(), MoreExecutors.directExecutor());
}