public async Task ProcessRunnerSucceeded([Values(true, false)] bool logPII)
        {
            var output   = "Test output";
            var fileName = "someFileName.exe";
            var args     = "arg1 arg2";
            var pi       = new ProcessStartInfo(fileName, args);
            var process  = new TestProcess {
                StartInfo = pi, Output = output
            };
            string result;
            string log = string.Empty;

            using AzureEventSourceListener listener = new AzureEventSourceListener((args, s) =>
            {
                log = $"{args.EventName} {s}";
            }, EventLevel.Verbose);
            using var runner = new ProcessRunner(process, TimeSpan.FromSeconds(30), logPII, default);
            result           = await Run(runner);

            Assert.AreEqual(output, result);
            if (logPII)
            {
                Assert.That(log, Contains.Substring(fileName));
                Assert.That(log, Contains.Substring(args));
                Assert.That(log, Contains.Substring(nameof(AzureIdentityEventSource.ProcessRunnerInformational)));
            }
            else
            {
                Assert.That(log, Does.Not.Contain(fileName));
                Assert.That(log, Does.Not.Contain(args));
                Assert.That(log, Does.Not.Contain(nameof(AzureIdentityEventSource.ProcessRunnerInformational)));
            }
        }
        public void ProcessRunnerFailedWithErrorMessage([Values(true, false)] bool logPII)
        {
            string log = string.Empty;

            using AzureEventSourceListener listener = new AzureEventSourceListener((args, s) =>
            {
                log = $"{args.EventName} {s}";
            }, EventLevel.Verbose);
            var error   = "Test error";
            var process = new TestProcess {
                Error = error
            };

            using var runner = new ProcessRunner(process, TimeSpan.FromSeconds(30), logPII, default);

            var exception = Assert.CatchAsync <InvalidOperationException>(async() => await Run(runner));

            Assert.AreEqual(error, exception.Message);
            if (logPII)
            {
                Assert.That(log, Contains.Substring(error));
                Assert.That(log, Contains.Substring(nameof(AzureIdentityEventSource.ProcessRunnerError)));
            }
            else
            {
                Assert.That(log, Does.Not.Contain(error));
                Assert.That(log, Does.Not.Contain(nameof(AzureIdentityEventSource.ProcessRunnerError)));
            }
        }
Example #3
0
        public async Task DefaultAzureCredential_UseAzureCliCredential()
        {
            var options = Recording.InstrumentClientOptions(new DefaultAzureCredentialOptions
            {
                ExcludeEnvironmentCredential        = true,
                ExcludeInteractiveBrowserCredential = true,
                ExcludeSharedTokenCacheCredential   = true,
                VisualStudioCodeTenantId            = TestEnvironment.TestTenantId
            });

            var(expectedToken, expectedExpiresOn, processOutput) = CredentialTestHelpers.CreateTokenForAzureCli();
            var testProcess = new TestProcess {
                Output = processOutput
            };
            var vscAdapter = new TestVscAdapter(ExpectedServiceName, "Azure", null);
            var fileSystem = CredentialTestHelpers.CreateFileSystemForVisualStudioCode(TestEnvironment);

            var factory    = new TestDefaultAzureCredentialFactory(options, fileSystem, new TestProcessService(testProcess), vscAdapter);
            var credential = InstrumentClient(new DefaultAzureCredential(factory, options));

            AccessToken token = await credential.GetTokenAsync(new TokenRequestContext(new[] { "https://vault.azure.net/.default" }), CancellationToken.None);

            Assert.AreEqual(token.Token, expectedToken);
            Assert.AreEqual(token.ExpiresOn, expectedExpiresOn);
        }
Example #4
0
        public async Task AuthenticateWithCliCredential(
            [Values(null, TenantIdHint)] string tenantId,
            [Values(true)] bool allowMultiTenantAuthentication,
            [Values(null, TenantId)] string explicitTenantId)
        {
            var context = new TokenRequestContext(new[] { Scope }, tenantId: tenantId);
            var options = new AzureCliCredentialOptions {
                TenantId = explicitTenantId, AllowMultiTenantAuthentication = allowMultiTenantAuthentication
            };
            string expectedTenantId = TenantIdResolver.Resolve(explicitTenantId, context, options.AllowMultiTenantAuthentication);

            var(expectedToken, expectedExpiresOn, processOutput) = CredentialTestHelpers.CreateTokenForAzureCli();

            var testProcess = new TestProcess {
                Output = processOutput
            };
            AzureCliCredential credential =
                InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess, true), options));
            AccessToken actualToken = await credential.GetTokenAsync(context);

            Assert.AreEqual(expectedToken, actualToken.Token);
            Assert.AreEqual(expectedExpiresOn, actualToken.ExpiresOn);

            var expectTenantId = expectedTenantId != null;

            if (expectTenantId)
            {
                Assert.That(testProcess.StartInfo.Arguments, Does.Contain($"-tenant {expectedTenantId}"));
            }
            else
            {
                Assert.That(testProcess.StartInfo.Arguments, Does.Not.Contain("-tenant"));
            }
        }
Example #5
0
        public async Task HandlesAlternateDateTimeFormats([Values("en-US", "nl-NL")] string culture)
        {
            CultureInfo curCulture = CultureInfo.CurrentCulture;

            CultureInfo.CurrentCulture = new CultureInfo(culture);
            try
            {
                var(expectedToken, expectedExpiresOn, processOutput) = CredentialTestHelpers.CreateTokenForAzurePowerShell(TimeSpan.FromSeconds(30));
                TestContext.WriteLine(processOutput);
                var testProcess = new TestProcess
                {
                    Output = processOutput,
                };
                AzurePowerShellCredential credential = InstrumentClient(
                    new AzurePowerShellCredential(
                        new AzurePowerShellCredentialOptions(),
                        CredentialPipeline.GetInstance(null),
                        new TestProcessService(testProcess, true)));
                await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default));
            }
            finally
            {
                CultureInfo.CurrentCulture = new CultureInfo(curCulture.Name);
            }
        }
Example #6
0
        [RunOnlyOnPlatforms(Windows = true, OSX = true)] // Comment this attribute to run this tests on Linux with Libsecret enabled
        public async Task DefaultAzureCredential_UseVisualStudioCodeCredential()
        {
            var options = Recording.InstrumentClientOptions(new DefaultAzureCredentialOptions
            {
                ExcludeEnvironmentCredential        = true,
                ExcludeInteractiveBrowserCredential = true,
                ExcludeSharedTokenCacheCredential   = true,
                VisualStudioCodeTenantId            = TestEnvironment.TestTenantId
            });

            var cloudName  = Guid.NewGuid().ToString();
            var fileSystem = CredentialTestHelpers.CreateFileSystemForVisualStudioCode(TestEnvironment, cloudName);
            var process    = new TestProcess {
                Error = "Error"
            };

            var factory    = new TestDefaultAzureCredentialFactory(options, fileSystem, new TestProcessService(process), default);
            var credential = InstrumentClient(new DefaultAzureCredential(factory, options));

            AccessToken token;

            using (await CredentialTestHelpers.CreateRefreshTokenFixtureAsync(TestEnvironment, Mode, ExpectedServiceName, cloudName))
            {
                token = await credential.GetTokenAsync(new TokenRequestContext(new[] { "https://vault.azure.net/.default" }), CancellationToken.None);
            }

            Assert.IsNotNull(token.Token);
        }
        public async Task FallsBackToLegacyPowershell()
        {
            bool fellBackToPowerShell = false;
            //var testProcess = new TestProcess { Output = "'pwsh' is not recognized as an internal or external command," };
            var testProcess = new TestProcess
            {
                Output = "'pwsh' is not recognized as an internal or external command,",
                ExceptionOnStartHandler = (p) =>
                {
                    if (p.StartInfo.Arguments.Contains("pwsh"))
                    {
                        p.Output             = tokenXML;
                        fellBackToPowerShell = true;
                    }
                }
            };
            AzurePowerShellCredential credential = InstrumentClient(
                new AzurePowerShellCredential(
                    new AzurePowerShellCredentialOptions(),
                    CredentialPipeline.GetInstance(null),
                    new TestProcessService(testProcess, true)));
            await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default));

            Assert.IsTrue(fellBackToPowerShell);
        }
        public void AuthenticateWithCliCredential_InvalidJsonOutput([Values("", "{}", "{\"Some\": false}", "{\"accessToken\": \"token\"}", "{\"expiresOn\" : \"1900-01-01 00:00:00.123456\"}")] string jsonContent)
        {
            var testProcess = new TestProcess {
                Output = jsonContent
            };
            AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));

            Assert.CatchAsync <AuthenticationFailedException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));
        }
        public void ProcessRunnerProcessFailsToStart()
        {
            var process = new TestProcess {
                FailedToStart = true
            };
            var runner = new ProcessRunner(process, TimeSpan.FromSeconds(30), default);

            Assert.CatchAsync <InvalidOperationException>(async() => await Run(runner));
        }
        public async Task AuthenticateWithVsCredential()
        {
            var fileSystem = CredentialTestHelpers.CreateFileSystemForVisualStudio();

            var(expectedToken, expectedExpiresOn, processOutput) = CredentialTestHelpers.CreateTokenForVisualStudio();
            var testProcess = new TestProcess {
                Output = processOutput
            };
            var credential = InstrumentClient(new VisualStudioCredential(default, default, fileSystem, new TestProcessService(testProcess)));
Example #11
0
        public void ProcessRunnerCreatedOnCanceled()
        {
            var process = new TestProcess {
                Output = "Test output", Timeout = 5000
            };
            var cancellationToken = new CancellationToken(true);
            var runner            = new ProcessRunner(process, TimeSpan.FromMilliseconds(5000), cancellationToken);

            Assert.CatchAsync <OperationCanceledException>(async() => await Run(runner));
        }
Example #12
0
        public void ProcessRunnerCanceledByTimeout()
        {
            var cts     = new CancellationTokenSource();
            var process = new TestProcess {
                Output = "Test output", Timeout = 5000
            };
            var runner = new ProcessRunner(process, TimeSpan.FromMilliseconds(100), cts.Token);

            Assert.CatchAsync <OperationCanceledException>(async() => await Run(runner));
        }
        public void AuthenticateWithAzurePowerShellCredential_AzurePowerShellModuleNotInstalled([Values("NoAzAccountModule")] string message)
        {
            var testProcess = new TestProcess {
                Output = message
            };
            AzurePowerShellCredential credential = InstrumentClient(new AzurePowerShellCredential(new AzurePowerShellCredentialOptions(), CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            var ex = Assert.ThrowsAsync <CredentialUnavailableException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));

            Assert.AreEqual(AzurePowerShellCredential.AzurePowerShellModuleNotInstalledError, ex.Message);
        }
        public void AuthenticateWithAzurePowerShellCredential_PwshNotInstalled([Values("'pwsh' is not recognized", "pwsh: command not found", "pwsh: not found")] string errorMessage)
        {
            var testProcess = new TestProcess {
                Error = errorMessage
            };
            AzurePowerShellCredential credential = InstrumentClient(new AzurePowerShellCredential(new AzurePowerShellCredentialOptions(), CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            var ex = Assert.ThrowsAsync <CredentialUnavailableException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));

            Assert.AreEqual(AzurePowerShellCredential.PowerShellNotInstalledError, ex.Message);
        }
Example #15
0
        public async Task AuthenticateWithVsCredential([Values(null, TenantIdHint)] string tenantId, [Values(true)] bool allowMultiTenantAuthentication)
        {
            var fileSystem = CredentialTestHelpers.CreateFileSystemForVisualStudio();

            var(expectedToken, expectedExpiresOn, processOutput) = CredentialTestHelpers.CreateTokenForVisualStudio();
            var testProcess = new TestProcess {
                Output = processOutput
            };
            var options    = new VisualStudioCredentialOptions();
            var credential = InstrumentClient(new VisualStudioCredential(TenantId, default, fileSystem, new TestProcessService(testProcess, true), options));
        public void AuthenticateWithCliCredential_AzureCliUnknownError()
        {
            string mockResult  = "mock-result";
            var    testProcess = new TestProcess {
                Error = mockResult
            };
            AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));

            Assert.ThrowsAsync <AuthenticationFailedException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));
        }
Example #17
0
        public void AuthenticateWithCliCredential_ExceptionScenarios(string errorMessage, string expectedMessage, Type exceptionType)
        {
            var testProcess = new TestProcess {
                Error = errorMessage
            };
            AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            var ex = Assert.ThrowsAsync(exceptionType, async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));

            Assert.AreEqual(expectedMessage, ex.Message);
        }
Example #18
0
        public void AuthenticateWithAzurePowerShellCredential_ErrorScenarios(string errorMessage, string expectedError)
        {
            var testProcess = new TestProcess {
                Error = errorMessage
            };
            AzurePowerShellCredential credential = InstrumentClient(
                new AzurePowerShellCredential(new AzurePowerShellCredentialOptions(), CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            var ex = Assert.ThrowsAsync <CredentialUnavailableException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));

            Assert.AreEqual(expectedError, ex.Message);
        }
        public void AuthenticateWithCliCredential_AzNotLogIn()
        {
            string expectedExMessage = $"Please run 'az login' to set up account";
            var    testProcess       = new TestProcess {
                Error = "Please run 'az login'"
            };
            AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            var ex = Assert.ThrowsAsync <CredentialUnavailableException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));

            Assert.AreEqual(expectedExMessage, ex.Message);
        }
        public void AuthenticateWithCliCredential_AzureCliNotInstalled([Values("'az' is not recognized", "az: command not found", "az: not found")] string errorMessage)
        {
            string expectedMessage = "Azure CLI not installed";
            var    testProcess     = new TestProcess {
                Error = errorMessage
            };
            AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            var ex = Assert.ThrowsAsync <CredentialUnavailableException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));

            Assert.AreEqual(expectedMessage, ex.Message);
        }
Example #21
0
        public async Task AuthenticateWithCliCredential()
        {
            var expectedToken = "mock-cli-access-token";
            var testProcess   = new TestProcess {
                Output = $"{{ \"accessToken\": \"{expectedToken}\", \"expiresOn\": \"1900-01-01 00:00:00.123456\" }}"
            };
            AzureCliCredential credential  = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            AccessToken        actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default));

            Assert.AreEqual(expectedToken, actualToken.Token);
        }
Example #22
0
        public async Task ProcessRunnerSucceeded()
        {
            var output  = "Test output";
            var process = new TestProcess {
                Output = output
            };
            var runner = new ProcessRunner(process, TimeSpan.FromSeconds(30), default);
            var result = await Run(runner);

            Assert.AreEqual(output, result);
        }
        public void AuthenticateWithCliCredential_CanceledByUser()
        {
            var cts         = new CancellationTokenSource();
            var testProcess = new TestProcess {
                Timeout = 10000
            };

            testProcess.Started += (o, e) => cts.Cancel();
            AzureCliCredential credential = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));

            Assert.CatchAsync <OperationCanceledException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default), cts.Token));
        }
        public void AuthenticateWithAzurePowerShellCredential_RunConnectAzAccount([Values("Run Connect-AzAccount to login")] string errorMessage)
        {
            var testProcess = new TestProcess {
                Error = errorMessage
            };
            AzurePowerShellCredential credential = InstrumentClient(new AzurePowerShellCredential(new AzurePowerShellCredentialOptions {
                UseLegacyPowerShell = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
            }, CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            var ex = Assert.ThrowsAsync <CredentialUnavailableException>(async() => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));

            Assert.AreEqual(AzurePowerShellCredential.AzurePowerShellNotLogInError, ex.Message);
        }
Example #25
0
        public void ProcessRunnerFailedWithErrorMessage()
        {
            var error   = "Test error";
            var process = new TestProcess {
                Error = error
            };
            var runner = new ProcessRunner(process, TimeSpan.FromSeconds(30), default);

            var exception = Assert.CatchAsync <InvalidOperationException>(async() => await Run(runner));

            Assert.AreEqual(error, exception.Message);
        }
Example #26
0
        public void ProcessRunnerFailedOnKillProcess()
        {
            var output  = "Test output";
            var process = new TestProcess {
                Output = output, ExceptionOnProcessKill = new Win32Exception(1), Timeout = 5000
            };
            var runner = new ProcessRunner(process, TimeSpan.FromMilliseconds(50), default);

            var exception = Assert.CatchAsync <Win32Exception>(async() => await Run(runner));

            Assert.AreEqual(1, exception.NativeErrorCode);
        }
        public async Task ProcessRunnerCanceledFinished()
        {
            var cts     = new CancellationTokenSource();
            var process = new TestProcess {
                Output = "Test output"
            };

            using var runner = new ProcessRunner(process, TimeSpan.FromSeconds(5000), false, cts.Token);
            await Run(runner);

            cts.Cancel();
        }
        public async Task AuthenticateWithCliCredential_ExpiresIn()
        {
            var(expectedToken, expectedExpiresOn, processOutput) = CredentialTestHelpers.CreateTokenForAzureCliExpiresIn(1800);

            var testProcess = new TestProcess {
                Output = processOutput
            };
            AzureCliCredential credential  = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            AccessToken        actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default));

            Assert.AreEqual(expectedToken, actualToken.Token);
            Assert.LessOrEqual(expectedExpiresOn, actualToken.ExpiresOn);
        }
Example #29
0
        public async Task AuthenticateWithCliCredential_ExpiresIn()
        {
            var expectedToken = "mock-cli-access-token";
            var expectedTime  = DateTimeOffset.Now.AddMinutes(30);
            var testProcess   = new TestProcess {
                Output = $"{{ \"accessToken\": \"{expectedToken}\", \"expiresIn\": 1800 }}"
            };
            AzureCliCredential credential  = InstrumentClient(new AzureCliCredential(CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            AccessToken        actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default));

            Assert.AreEqual(expectedToken, actualToken.Token);
            Assert.LessOrEqual(expectedTime, actualToken.ExpiresOn);
        }
        public async Task AuthenticateWithAzurePowerShellCredential()
        {
            var(expectedToken, expectedExpiresOn, processOutput) = CredentialTestHelpers.CreateTokenForAzurePowerShell(TimeSpan.FromSeconds(30));

            var testProcess = new TestProcess {
                Output = processOutput
            };
            AzurePowerShellCredential credential = InstrumentClient(new AzurePowerShellCredential
                                                                        (new AzurePowerShellCredentialOptions(), CredentialPipeline.GetInstance(null), new TestProcessService(testProcess)));
            AccessToken actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default));

            Assert.AreEqual(expectedToken, actualToken.Token);
            Assert.AreEqual(expectedExpiresOn, actualToken.ExpiresOn);
        }