예제 #1
0
        public void ClientSecretCredentialWithOptionsFailureTest(string tenantId, string clientId, string clientSecret, bool useHostString)
        {
            var options    = AzureOauthTokenAuthentication.GetOptions(useHostString ? AzureOauthTokenAuthentication.DefaultAuthorityHost : null);
            var credential = AzureOauthTokenAuthentication.GetOauthTokenCredentialFromClientSecret(tenantId, clientId, clientSecret, options);

            Assert.IsNotNull(credential, "Credential should not be null");
        }
예제 #2
0
        public void ManagedIdentityBaseWithOptionsTest(bool useHostString)
        {
            var options    = AzureOauthTokenAuthentication.GetOptions(useHostString ? AzureOauthTokenAuthentication.DefaultAuthorityHost : null);
            var credential = AzureOauthTokenAuthentication.GetOauthTokenCredentialFromManagedIdentity(options);

            Assert.IsNotNull(credential, "Credential should not be null");
        }
예제 #3
0
        public static KeyVaultSecrets GetSecretsClient(ILogger logger)
        {
            var keyVaultName     = Environment.GetEnvironmentVariable("KeyVaultName");
            var hubSecretName    = Environment.GetEnvironmentVariable("HubSecretName");
            var identityClientId = Environment.GetEnvironmentVariable("IdentityClientId");
            var tenantId         = Environment.GetEnvironmentVariable("TenantId");
            var clientId         = Environment.GetEnvironmentVariable("ClientId");
            var clientSecret     = Environment.GetEnvironmentVariable("ClientSecret");

            logger.LogInformation("Retrieving secrets from vault named: {valueName} and a hub secret named: {hubSecretName}", keyVaultName, hubSecretName);

            TokenCredential tokenProvider;

            if (string.IsNullOrWhiteSpace(clientSecret))
            {
                tokenProvider = string.IsNullOrWhiteSpace(identityClientId) ? AzureOauthTokenAuthentication.GetOauthTokenCredentialFromManagedIdentity() : AzureOauthTokenAuthentication.GetOauthTokenCredentialFromManagedIdentity(identityClientId);
            }
            else
            {
                tokenProvider = AzureOauthTokenAuthentication.GetOauthTokenCredentialFromClientSecret(tenantId, clientId, clientSecret);
            }

            logger.LogInformation("Completed creation of token provider");

            var vault = new KeyVault(keyVaultName, tokenProvider, 3, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(10));

            logger.LogInformation("Created key vault");

            return(vault.GetSecretsClient());
        }
예제 #4
0
        public void GetCertificateWithVersion()
        {
            const string VaultName     = "fakevault1";
            const string SecretName    = "secretname1";
            const string SecretVersion = "1aaaaaaa1aa11a1111aaaa11111a1111";
            //           const string SecretValue = "This is the value fake";
            const string TenantId     = "11111111-1111-1111-aa1a-a1a11a111111";
            const string ClientId     = "11111111-1111-1111-aa1a-a1a11a111111";
            const string ClientSecret = "a.u8w3FFgwy9v_-5R_5gsT~qf96T~a7e6y";
            //           var getCertificateInvoked = false;
            //     string key = null;
            var path              = ContainerEnvironment.IsLinux ? Path.Combine(Environment.CurrentDirectory, "my_contoso_local.pfx") : Path.Combine(Environment.CurrentDirectory, "TestValidationCertificate.pfx");
            var certificate       = new X509Certificate2(path, "abc123");
            var certificateString = Convert.ToBase64String(certificate.RawData);

            using (var context = ShimsContext.Create())
            {
                ShimKeyVaultCertificate.AllInstances.CerGet = new FakesDelegates.Func <KeyVaultCertificate, byte[]>((vaultCert) => certificate.RawData);

                var fakeCertificate = new ShimKeyVaultCertificate()
                {
                    NameGet       = new FakesDelegates.Func <string>(() => "FakeCert1"),
                    IdGet         = new FakesDelegates.Func <Uri>(() => new Uri("cert://FakeCert1")),
                    PropertiesGet = new FakesDelegates.Func <CertificateProperties>(() =>
                    {
                        return(new ShimCertificateProperties()
                        {
                            VersionGet = new FakesDelegates.Func <string>(() => SecretVersion),
                            NameGet = new FakesDelegates.Func <string>(() => SecretName),
                            IdGet = new FakesDelegates.Func <Uri>(() => new Uri("cert://FakeCert1"))
                        });
                    })
                };

                ShimCertificateClient.AllInstances.GetCertificateVersionAsyncStringStringCancellationToken = new FakesDelegates.Func <CertificateClient, string, string, CancellationToken, Task <Response <KeyVaultCertificate> > >((client, name, version, cancellationToken) =>
                {
                    var keyVaultFakeCertificateResponse = new FakeResponse <KeyVaultCertificate>(fakeCertificate, 200, "OK", null);

                    return(Task.FromResult(keyVaultFakeCertificateResponse as Response <KeyVaultCertificate>));
                });

                var secret = new ShimKeyVaultCertificateWithPolicy();


                var response = new FakeResponse <KeyVaultCertificate>(secret, 200, "OK", null);

                SetupSecretClientConstructorFakes();
                var vault            = new KeyVault(VaultName, AzureOauthTokenAuthentication.GetOauthTokenCredentialFromClientSecret(TenantId, ClientId, ClientSecret), 3, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(10));
                var client           = vault.GetCertificatesClient(CertificateClientOptions.ServiceVersion.V7_1);
                var certificateValue = client.GetAsync(SecretName, SecretVersion).GetAwaiter().GetResult();

                Assert.IsNotNull(certificateValue, "Certificate failed to retrieve");
                Assert.IsTrue(string.Equals(certificateValue.Id.AbsoluteUri, "cert://fakecert1/", StringComparison.Ordinal), "Id not expected");
                Assert.IsTrue(string.Equals(certificateValue.Name, "FakeCert1", StringComparison.Ordinal), "Name not expected");
                Assert.IsTrue(string.Equals(certificateValue.Version, SecretVersion, StringComparison.Ordinal), "Version not expected");
                Assert.IsNull(certificateValue.Policy, "Policy not expected");
            }
        }
예제 #5
0
        public void ConfigureOptionRetries()
        {
            var options = AzureOauthTokenAuthentication.GetOptions();

            AzureOauthTokenAuthentication.ConfigureRetries(options, Azure.Core.RetryMode.Exponential, 100, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2));

            Assert.IsTrue(options.Retry.Delay == TimeSpan.FromSeconds(5), "Delay is not expected");
            Assert.IsTrue(options.Retry.MaxDelay == TimeSpan.FromMinutes(1), "MaximumDelay is not expected");
            Assert.IsTrue(options.Retry.NetworkTimeout == TimeSpan.FromMinutes(2), "Network Timeout is not expected");
            Assert.IsTrue(options.Retry.MaxRetries == 100, "Maximum retries is not expected");
        }
예제 #6
0
        public void ConfigureOptionDiagnostics()
        {
            var options = AzureOauthTokenAuthentication.GetOptions();

            AzureOauthTokenAuthentication.ConfigureDiagnostics(options, "app1", true, true, true, true, 5000);

            Assert.IsTrue(options.Diagnostics.ApplicationId == "app1", "Application Id is not expected");
            Assert.IsTrue(options.Diagnostics.IsDistributedTracingEnabled, "DistributedTracingEnabled is not expected");
            Assert.IsTrue(options.Diagnostics.IsLoggingContentEnabled, "LoggingContentEnabled is not expected");
            Assert.IsTrue(options.Diagnostics.IsLoggingEnabled, "LoggingEnabled is not expected");
            Assert.IsTrue(options.Diagnostics.IsTelemetryEnabled, "LoggingEnabled is not expected");
            Assert.IsTrue(options.Diagnostics.LoggedContentSizeLimit == 5000, "LoggedContentSizeLimit is not expected");
            Assert.IsTrue(options.Diagnostics.LoggedHeaderNames.Count > 0, "LoggedHeaderNames is not expected");
            Assert.IsTrue(options.Diagnostics.LoggedQueryParameters.Count == 0, "LoggedQueryParameters is not expected");
        }
        public void GetCertificate()
        {
            const string TenantId           = @"11a111aa-11a1-11aa-11aa-1a1aa111aa11";
            const string ClientId           = @"11a111aa-11a1-11aa-11aa-1a1aa111aa11";
            const string ClientSecret       = @"someclientsecret";
            const string CertificateName    = @"democert123";
            const string CertificateVersion = @"11a111aa11a111aa11aa1a1aa111aa11";

            var manager  = new KeyVaultSecretManager("cgcvault1", AzureOauthTokenAuthentication.GetOauthTokenCredentialFromClientSecret(TenantId, ClientId, ClientSecret), 3, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(10));
            var response = manager.GetCertificateAsync(CertificateName, CertificateVersion, CancellationToken.None).GetAwaiter().GetResult();

            Assert.IsNotNull(response, "Response is null");
            Assert.IsTrue(response.IsSuccessCode, "Success code unexpected");
            Assert.IsTrue(response.StatusCode == 200, "Status code unexpected");
        }
        public void GetCertificateWithVersion()
        {
            const string VaultName     = "fakevault1";
            const string SecretName    = "secretname1";
            const string SecretVersion = "1aaaaaaa1aa11a1111aaaa11111a1111";
            const string TenantId      = "11111111-1111-1111-aa1a-a1a11a111111";
            const string ClientId      = "11111111-1111-1111-aa1a-a1a11a111111";
            const string ClientSecret  = "a.u8w3FFgwy9v_-5R_5gsT~qf96T~a7e6y";

            var algorithm = ECDsa.Create();
            //     string key = null;
            var path              = Path.Combine(Environment.CurrentDirectory, "TestValidationCertificate.pfx");
            var certificate       = new X509Certificate2(path, "abc123");
            var certificateString = Convert.ToBase64String(certificate.RawData);

            using (var context = ShimsContext.Create())
            {
                ShimKeyVaultKey.AllInstances.KeyGet = new FakesDelegates.Func <KeyVaultKey, JsonWebKey>((key) =>
                {
                    return(new JsonWebKey(algorithm));
                });

                var fakeKey = new ShimKeyVaultKey()
                {
                };

                ShimKeyClient.AllInstances.GetKeyAsyncStringStringCancellationToken = new FakesDelegates.Func <KeyClient, string, string, CancellationToken, Task <Response <KeyVaultKey> > >((client, name, version, cancellationToken) =>
                {
                    var keyVaultFakeKeyResponse = new FakeResponse <KeyVaultKey>(fakeKey, 200, "OK", null);

                    return(Task.FromResult(keyVaultFakeKeyResponse as Response <KeyVaultKey>));
                });


                var testKey  = new ShimKeyVaultKey();
                var response = new FakeResponse <KeyVaultKey>(testKey, 200, "OK", null);

                SetupSecretClientConstructorFakes();
                var vault    = new KeyVault(VaultName, AzureOauthTokenAuthentication.GetOauthTokenCredentialFromClientSecret(TenantId, ClientId, ClientSecret), 3, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(10));
                var client   = vault.GetKeysClient(KeyClientOptions.ServiceVersion.V7_1);
                var keyValue = client.GetAsync(SecretName, SecretVersion).GetAwaiter().GetResult();

                Assert.IsNotNull(keyValue, "Certificate failed to retrieve");
                var webKey = (JsonWebKey)keyValue;

                Assert.IsNotNull(webKey, "Web key not expected");
            }
        }
        public void GetCertificateSecret()
        {
            const string VaultName     = "fakevault1";
            const string SecretName    = "secretname1";
            const string SecretVersion = "1aaaaaaa1aa11a1111aaaa11111a1111";
            const string TenantId      = "11111111-1111-1111-aa1a-a1a11a111111";
            const string ClientId      = "11111111-1111-1111-aa1a-a1a11a111111";
            const string ClientSecret  = "a.u8w3FFgwy9v_-5R_5gsT~qf96T~a7e6y";

            var getSecretInvoked = false;
            X509Certificate2 certificateSecret = null;

            using (var context = ShimsContext.Create())
            {
                var path              = Path.Combine(Environment.CurrentDirectory, "TestValidationCertificate.pfx");
                var certificate       = new X509Certificate2(path, "abc123");
                var certificateString = Convert.ToBase64String(certificate.RawData);
                var secret            = new KeyVaultSecretFake($"{VaultName}.vault.azure.net", SecretName, SecretVersion, certificateString);
                var response          = new FakeResponse <KeyVaultSecret>(secret, 200, "OK", null);

                SetupSecretClientConstructorFakes();
                ShimSecretClient.AllInstances.GetSecretAsyncStringStringCancellationToken = new FakesDelegates.Func <SecretClient, string, string, CancellationToken, Task <Response <KeyVaultSecret> > >((client, name, version, cancellationToken) =>
                {
                    getSecretInvoked = true;

                    var fakeResponse = response as Response <KeyVaultSecret>;
                    return(Task.FromResult(fakeResponse));
                });

                var vault       = new KeyVault(VaultName, AzureOauthTokenAuthentication.GetOauthTokenCredentialFromClientSecret(TenantId, ClientId, ClientSecret), 3, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(10));
                var client      = vault.GetSecretsClient(SecretClientOptions.ServiceVersion.V7_1);
                var secretValue = client.GetCertificateAsync(SecretName, SecretVersion, CancellationToken.None).GetAwaiter().GetResult();

                certificateSecret = secretValue.Value;
            }

            Assert.IsTrue(getSecretInvoked, "The fake should be used");
            Assert.IsNotNull(certificateSecret, "Certificate is null");
            Assert.IsTrue(string.Equals(certificateSecret.Thumbprint, "A449811985D59FC72303860F51CB95F5D3257141", StringComparison.Ordinal), "Certificate thumbprint not expected");
            Assert.IsTrue(string.Equals(certificateSecret.Subject, "CN=Joe Smith, OU=UserAccounts, DC=corp, DC=praxicloud, DC=com", StringComparison.Ordinal), "Certificate subject not expected");
            Assert.IsTrue(string.Equals(certificateSecret.Issuer, "CN=Joe Smith, OU=UserAccounts, DC=corp, DC=praxicloud, DC=com", StringComparison.Ordinal), "Certificate issuer not expected");
            Assert.IsTrue(string.Equals(certificateSecret.SerialNumber, "67EA381F988D5AA94B1569B978062CFB", StringComparison.Ordinal), "Certificate serial number not expected");
            Assert.IsTrue(certificateSecret.NotBefore == DateTime.Parse("2020-09-09 9:42:40 AM"), "Certificate not before not expected");
            Assert.IsTrue(certificateSecret.NotAfter == DateTime.Parse("2070-09-09 9:52:40 AM"), "Certificate not after not expected");
        }
        public void GetSet()
        {
            const string VaultName    = "fakevault1";
            const string TenantId     = "11111111-1111-1111-aa1a-a1a11a111111";
            const string ClientId     = "11111111-1111-1111-aa1a-a1a11a111111";
            const string ClientSecret = "a.u8w3FFgwy9v_-5R_5gsT~qf96T~a7e6y";

            var vault = new KeyVault(VaultName, AzureOauthTokenAuthentication.GetOauthTokenCredentialFromClientSecret(TenantId, ClientId, ClientSecret), 3, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(10));

            Assert.IsTrue(string.Equals(vault.Name, VaultName, StringComparison.Ordinal), "Vault name is not expected");
            Assert.IsTrue(string.Equals(vault.FullyQualifiedName, $"{ VaultName }.vault.azure.net", StringComparison.Ordinal), "Fully qualified name is not expected");
            Assert.IsTrue(string.Equals(vault.Uri.AbsoluteUri, $"https://{ VaultName }.vault.azure.net/", StringComparison.Ordinal), "Uri not expected");
            Assert.IsFalse(vault.EnableDiagnostics, "Enable diagnostics not expected");
            Assert.IsTrue(vault.MaximumDelay == TimeSpan.FromSeconds(15), "Maximum delay not expected");
            Assert.IsTrue(vault.NetworkTimeout == TimeSpan.FromSeconds(10), "Network timeout not expected");
            Assert.IsTrue(vault.Delay == TimeSpan.FromSeconds(2), "Delay not expected");
            Assert.IsTrue(vault.MaximumRetries == 3, "Maximum retries not expected");
            Assert.IsNull(vault.DiagnosticsApplicationId, "Diagnostics application id not expected");
        }
        public void GetSecretWithVersion()
        {
            const string VaultName     = "fakevault1";
            const string SecretName    = "secretname1";
            const string SecretVersion = "1aaaaaaa1aa11a1111aaaa11111a1111";
            const string SecretValue   = "This is the value fake";
            const string TenantId      = "11111111-1111-1111-aa1a-a1a11a111111";
            const string ClientId      = "11111111-1111-1111-aa1a-a1a11a111111";
            const string ClientSecret  = "a.u8w3FFgwy9v_-5R_5gsT~qf96T~a7e6y";

            var    getSecretInvoked = false;
            string key = null;

            using (var context = ShimsContext.Create())
            {
                var secret   = new KeyVaultSecretFake($"{VaultName}.vault.azure.net", SecretName, SecretVersion, SecretValue);
                var response = new FakeResponse <KeyVaultSecret>(secret, 200, "OK", null);

                SetupSecretClientConstructorFakes();
                ShimSecretClient.AllInstances.GetSecretAsyncStringStringCancellationToken = new FakesDelegates.Func <SecretClient, string, string, CancellationToken, Task <Response <KeyVaultSecret> > >((client, name, version, cancellationToken) =>
                {
                    getSecretInvoked = true;

                    var fakeResponse = response as Response <KeyVaultSecret>;
                    return(Task.FromResult(fakeResponse));
                });



                var vault       = new KeyVault(VaultName, AzureOauthTokenAuthentication.GetOauthTokenCredentialFromClientSecret(TenantId, ClientId, ClientSecret), 3, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(10));
                var client      = vault.GetSecretsClient(SecretClientOptions.ServiceVersion.V7_1);
                var secretValue = client.GetAsync(SecretName, SecretVersion).GetAwaiter().GetResult();

                key = secretValue.Value.SecureStringToString();
            }

            Assert.IsTrue(getSecretInvoked, "The fake should be used");
            Assert.IsTrue(string.Equals(key, SecretValue, StringComparison.Ordinal), "Value not expected");
        }
예제 #12
0
        public void ManagedIdentityCredentialTest(string clientId)
        {
            var credential = AzureOauthTokenAuthentication.GetOauthTokenCredentialFromManagedIdentity(clientId);

            Assert.IsNotNull(credential, "Credential should not be null");
        }
예제 #13
0
        public void ClientSecretCredentialTest(string tenantId, string clientId, string clientSecret)
        {
            var credential = AzureOauthTokenAuthentication.GetOauthTokenCredentialFromClientSecret(tenantId, clientId, clientSecret);

            Assert.IsNotNull(credential, "Credential should not be null");
        }
예제 #14
0
 public void ManagedIdentityCredential1FailureTest(string clientId)
 {
     var credential = AzureOauthTokenAuthentication.GetOauthTokenCredentialFromManagedIdentity(clientId);
 }