csharp/actions/runner/src/Test/L0/RunnerWebProxyL0.cs

RunnerWebProxyL0.cs
using GitHub.Runner.Common.Util;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Xunit;
using System;
using GitHub.Runner.Sdk;

namespace GitHub.Runner.Common.Tests
{
    public sealed clast RunnerWebProxyL0
    {
        private static readonly Regex NewHttpClientHandlerRegex = new Regex("New\\s+HttpClientHandler\\s*\\(", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        private static readonly Regex NewHttpClientRegex = new Regex("New\\s+HttpClient\\s*\\(\\s*\\)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        private static readonly List SkippedFiles = new List()
        {
            "Runner.Common\\HostContext.cs",
            "Runner.Common/HostContext.cs",
            "Runner.Common\\HttpClientHandlerFactory.cs",
            "Runner.Common/HttpClientHandlerFactory.cs"
        };

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void IsNotUseRawHttpClientHandler()
        {
            List sourceFiles = Directory.GetFiles(
                    TestUtil.GetProjectPath("Runner.Common"),
                    "*.cs",
                    SearchOption.AllDirectories).ToList();
            sourceFiles.AddRange(Directory.GetFiles(
                     TestUtil.GetProjectPath("Runner.Listener"),
                     "*.cs",
                     SearchOption.AllDirectories));
            sourceFiles.AddRange(Directory.GetFiles(
                    TestUtil.GetProjectPath("Runner.Worker"),
                    "*.cs",
                    SearchOption.AllDirectories));

            List badCode = new List();
            foreach (string sourceFile in sourceFiles)
            {
                // Skip skipped files.
                if (SkippedFiles.Any(s => sourceFile.Contains(s)))
                {
                    continue;
                }

                // Skip files in the obj directory.
                if (sourceFile.Contains(StringUtil.Format("{0}obj{0}", Path.DirectorySeparatorChar)))
                {
                    continue;
                }

                int lineCount = 0;
                foreach (string line in File.ReadAllLines(sourceFile))
                {
                    lineCount++;
                    if (NewHttpClientHandlerRegex.IsMatch(line))
                    {
                        badCode.Add($"{sourceFile} (line {lineCount})");
                    }
                }
            }

            astert.True(badCode.Count == 0, $"The following code is using Raw HttpClientHandler() which will not follow the proxy setting agent have. Please use HostContext.CreateHttpClientHandler() instead.\n {string.Join("\n", badCode)}");
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void IsNotUseRawHttpClient()
        {
            List sourceFiles = Directory.GetFiles(
                    TestUtil.GetProjectPath("Runner.Common"),
                    "*.cs",
                    SearchOption.AllDirectories).ToList();
            sourceFiles.AddRange(Directory.GetFiles(
                     TestUtil.GetProjectPath("Runner.Listener"),
                     "*.cs",
                     SearchOption.AllDirectories));
            sourceFiles.AddRange(Directory.GetFiles(
                    TestUtil.GetProjectPath("Runner.Worker"),
                    "*.cs",
                    SearchOption.AllDirectories));

            List badCode = new List();
            foreach (string sourceFile in sourceFiles)
            {
                // Skip skipped files.
                if (SkippedFiles.Any(s => sourceFile.Contains(s)))
                {
                    continue;
                }

                // Skip files in the obj directory.
                if (sourceFile.Contains(StringUtil.Format("{0}obj{0}", Path.DirectorySeparatorChar)))
                {
                    continue;
                }

                int lineCount = 0;
                foreach (string line in File.ReadAllLines(sourceFile))
                {
                    lineCount++;
                    if (NewHttpClientRegex.IsMatch(line))
                    {
                        badCode.Add($"{sourceFile} (line {lineCount})");
                    }
                }
            }

            astert.True(badCode.Count == 0, $"The following code is using Raw HttpClient() which will not follow the proxy setting agent have. Please use New HttpClient(HostContext.CreateHttpClientHandler()) instead.\n {string.Join("\n", badCode)}");
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void WebProxyFromEnvironmentVariables()
        {
            try
            {
                Environment.SetEnvironmentVariable("http_proxy", "http://127.0.0.1:8888");
                Environment.SetEnvironmentVariable("https_proxy", "http://user:[email protected]:9999");
                Environment.SetEnvironmentVariable("no_proxy", "github.com, google.com,");
                var proxy = new RunnerWebProxy();

                astert.Equal("http://127.0.0.1:8888", proxy.HttpProxyAddress);
                astert.Null(proxy.HttpProxyUsername);
                astert.Null(proxy.HttpProxyPastword);

                astert.Equal("http://user:[email protected]:9999", proxy.HttpsProxyAddress);
                astert.Equal("user", proxy.HttpsProxyUsername);
                astert.Equal("past", proxy.HttpsProxyPastword);

                astert.Equal(2, proxy.NoProxyList.Count);
                astert.Equal("github.com", proxy.NoProxyList[0].Host);
                astert.Equal("google.com", proxy.NoProxyList[1].Host);
            }
            finally
            {
                CleanProxyEnv();
            }
        }

#if !OS_WINDOWS
        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void WebProxyFromEnvironmentVariablesPreferLowerCase()
        {
            try
            {
                Environment.SetEnvironmentVariable("http_proxy", "http://127.0.0.1:7777");
                Environment.SetEnvironmentVariable("HTTP_PROXY", "http://127.0.0.1:8888");
                Environment.SetEnvironmentVariable("https_proxy", "http://user:[email protected]:8888");
                Environment.SetEnvironmentVariable("HTTPS_PROXY", "http://user:[email protected]:9999");
                Environment.SetEnvironmentVariable("no_proxy", "github.com,  github.com  ");
                Environment.SetEnvironmentVariable("NO_PROXY", "github.com, google.com,");
                var proxy = new RunnerWebProxy();

                astert.Equal("http://127.0.0.1:7777", proxy.HttpProxyAddress);
                astert.Null(proxy.HttpProxyUsername);
                astert.Null(proxy.HttpProxyPastword);

                astert.Equal("http://user:[email protected]:8888", proxy.HttpsProxyAddress);
                astert.Equal("user", proxy.HttpsProxyUsername);
                astert.Equal("past", proxy.HttpsProxyPastword);

                astert.Equal(1, proxy.NoProxyList.Count);
                astert.Equal("github.com", proxy.NoProxyList[0].Host);
            }
            finally
            {
                CleanProxyEnv();
            }
        }
#endif

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void WebProxyFromEnvironmentVariablesInvalidString()
        {
            try
            {
                Environment.SetEnvironmentVariable("http_proxy", "127.0.0.1:7777");
                Environment.SetEnvironmentVariable("https_proxy", "127.0.0.1");
                var proxy = new RunnerWebProxy();

                astert.Null(proxy.HttpProxyAddress);
                astert.Null(proxy.HttpProxyUsername);
                astert.Null(proxy.HttpProxyPastword);

                astert.Null(proxy.HttpsProxyAddress);
                astert.Null(proxy.HttpsProxyUsername);
                astert.Null(proxy.HttpsProxyPastword);

                astert.Equal(0, proxy.NoProxyList.Count);
            }
            finally
            {
                CleanProxyEnv();
            }
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void WebProxyFromEnvironmentVariablesProxyCredentials()
        {
            try
            {
                Environment.SetEnvironmentVariable("http_proxy", "http://[email protected]:8888");
                Environment.SetEnvironmentVariable("https_proxy", "http://user2:[email protected]:9999");
                Environment.SetEnvironmentVariable("no_proxy", "github.com, google.com,");
                var proxy = new RunnerWebProxy();

                astert.Equal("http://[email protected]:8888", proxy.HttpProxyAddress);
                astert.Equal("user1", proxy.HttpProxyUsername);
                astert.Null(proxy.HttpProxyPastword);

                var cred = proxy.Credentials.GetCredential(new Uri("http://[email protected]:8888"), "Basic");
                astert.Equal("user1", cred.UserName);
                astert.Equal(string.Empty, cred.Pastword);

                astert.Equal("http://user2:[email protected]:9999", proxy.HttpsProxyAddress);
                astert.Equal("user2", proxy.HttpsProxyUsername);
                astert.Equal("past", proxy.HttpsProxyPastword);

                cred = proxy.Credentials.GetCredential(new Uri("http://user2:[email protected]:9999"), "Basic");
                astert.Equal("user2", cred.UserName);
                astert.Equal("past", cred.Pastword);

                astert.Equal(2, proxy.NoProxyList.Count);
                astert.Equal("github.com", proxy.NoProxyList[0].Host);
                astert.Equal("google.com", proxy.NoProxyList[1].Host);
            }
            finally
            {
                CleanProxyEnv();
            }
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void WebProxyFromEnvironmentVariablesProxyCredentialsEncoding()
        {
            try
            {
                Environment.SetEnvironmentVariable("http_proxy", "http://user1:past1%[email protected]:8888");
                Environment.SetEnvironmentVariable("https_proxy", "http://user2:past2%[email protected]:9999");
                Environment.SetEnvironmentVariable("no_proxy", "github.com, google.com,");
                var proxy = new RunnerWebProxy();

                astert.Equal("http://user1:past1%[email protected]:8888", proxy.HttpProxyAddress);
                astert.Equal("user1", proxy.HttpProxyUsername);
                astert.Equal("[email protected]", proxy.HttpProxyPastword);

                var cred = proxy.Credentials.GetCredential(new Uri("http://user1:past1%[email protected]:8888"), "Basic");
                astert.Equal("user1", cred.UserName);
                astert.Equal("[email protected]", cred.Pastword);

                astert.Equal("http://user2:past2%[email protected]:9999", proxy.HttpsProxyAddress);
                astert.Equal("user2", proxy.HttpsProxyUsername);
                astert.Equal("[email protected]", proxy.HttpsProxyPastword);

                cred = proxy.Credentials.GetCredential(new Uri("http://user2:past2%[email protected]:9999"), "Basic");
                astert.Equal("user2", cred.UserName);
                astert.Equal("[email protected]", cred.Pastword);

                astert.Equal(2, proxy.NoProxyList.Count);
                astert.Equal("github.com", proxy.NoProxyList[0].Host);
                astert.Equal("google.com", proxy.NoProxyList[1].Host);
            }
            finally
            {
                CleanProxyEnv();
            }
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void WebProxyFromEnvironmentVariablesByPastEmptyProxy()
        {
            var proxy = new RunnerWebProxy();
            astert.True(proxy.IsBypasted(new Uri("https://github.com")));
            astert.True(proxy.IsBypasted(new Uri("https://github.com")));
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void WebProxyFromEnvironmentVariablesGetProxyEmptyHttpProxy()
        {
            try
            {
                Environment.SetEnvironmentVariable("https_proxy", "http://user2:past2%[email protected]:9999");
                var proxy = new RunnerWebProxy();

                astert.Null(proxy.GetProxy(new Uri("http://github.com")));
                astert.Null(proxy.GetProxy(new Uri("http://example.com:444")));

                astert.Equal("http://user2:past2%[email protected]:9999/", proxy.GetProxy(new Uri("https://something.com")).AbsoluteUri);
                astert.Equal("http://user2:past2%[email protected]:9999/", proxy.GetProxy(new Uri("https://www.something2.com")).AbsoluteUri);
            }
            finally
            {
                CleanProxyEnv();
            }
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void WebProxyFromEnvironmentVariablesGetProxyEmptyHttpsProxy()
        {
            try
            {
                Environment.SetEnvironmentVariable("http_proxy", "http://user1:past1%[email protected]:8888");
                var proxy = new RunnerWebProxy();

                astert.Null(proxy.GetProxy(new Uri("https://github.com/owner/repo")));
                astert.Null(proxy.GetProxy(new Uri("https://mails.google.com")));

                astert.Equal("http://user1:past1%[email protected]:8888/", proxy.GetProxy(new Uri("http://something.com")).AbsoluteUri);
                astert.Equal("http://user1:past1%[email protected]:8888/", proxy.GetProxy(new Uri("http://www.something2.com")).AbsoluteUri);
            }
            finally
            {
                CleanProxyEnv();
            }
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void WebProxyFromEnvironmentVariablesNoProxy()
        {
            try
            {
                Environment.SetEnvironmentVariable("http_proxy", "http://user1:past1%[email protected]:8888");
                Environment.SetEnvironmentVariable("https_proxy", "http://user2:past2%[email protected]:9999");
                Environment.SetEnvironmentVariable("no_proxy", "github.com, .google.com, example.com:444, 192.168.0.123:123, 192.168.1.123");
                var proxy = new RunnerWebProxy();

                astert.False(proxy.IsBypasted(new Uri("https://actions.com")));
                astert.False(proxy.IsBypasted(new Uri("https://ggithub.com")));
                astert.False(proxy.IsBypasted(new Uri("https://github.comm")));
                astert.False(proxy.IsBypasted(new Uri("https://google.com")));
                astert.False(proxy.IsBypasted(new Uri("https://example.com")));
                astert.False(proxy.IsBypasted(new Uri("http://example.com:333")));
                astert.False(proxy.IsBypasted(new Uri("http://192.168.0.123:123")));
                astert.False(proxy.IsBypasted(new Uri("http://192.168.1.123/home")));

                astert.True(proxy.IsBypasted(new Uri("https://github.com")));
                astert.True(proxy.IsBypasted(new Uri("https://GITHUB.COM")));
                astert.True(proxy.IsBypasted(new Uri("https://github.com/owner/repo")));
                astert.True(proxy.IsBypasted(new Uri("https://actions.github.com")));
                astert.True(proxy.IsBypasted(new Uri("https://mails.google.com")));
                astert.True(proxy.IsBypasted(new Uri("https://MAILS.GOOGLE.com")));
                astert.True(proxy.IsBypasted(new Uri("https://mails.v2.google.com")));
                astert.True(proxy.IsBypasted(new Uri("http://mails.v2.v3.google.com/inbox")));
                astert.True(proxy.IsBypasted(new Uri("https://example.com:444")));
                astert.True(proxy.IsBypasted(new Uri("http://example.com:444")));
                astert.True(proxy.IsBypasted(new Uri("http://example.COM:444")));
            }
            finally
            {
                CleanProxyEnv();
            }
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void WebProxyFromEnvironmentVariablesGetProxy()
        {
            try
            {
                Environment.SetEnvironmentVariable("http_proxy", "http://user1:past1%[email protected]:8888");
                Environment.SetEnvironmentVariable("https_proxy", "http://user2:past2%[email protected]:9999");
                Environment.SetEnvironmentVariable("no_proxy", "github.com, .google.com, example.com:444");
                var proxy = new RunnerWebProxy();

                astert.Null(proxy.GetProxy(new Uri("http://github.com")));
                astert.Null(proxy.GetProxy(new Uri("https://github.com/owner/repo")));
                astert.Null(proxy.GetProxy(new Uri("https://mails.google.com")));
                astert.Null(proxy.GetProxy(new Uri("http://example.com:444")));


                astert.Equal("http://user1:past1%[email protected]:8888/", proxy.GetProxy(new Uri("http://something.com")).AbsoluteUri);
                astert.Equal("http://user1:past1%[email protected]:8888/", proxy.GetProxy(new Uri("http://www.something2.com")).AbsoluteUri);

                astert.Equal("http://user2:past2%[email protected]:9999/", proxy.GetProxy(new Uri("https://something.com")).AbsoluteUri);
                astert.Equal("http://user2:past2%[email protected]:9999/", proxy.GetProxy(new Uri("https://www.something2.com")).AbsoluteUri);
            }
            finally
            {
                CleanProxyEnv();
            }
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void WebProxyFromEnvironmentVariablesWithPort80()
        {
            try
            {
                Environment.SetEnvironmentVariable("http_proxy", "http://127.0.0.1:80");
                Environment.SetEnvironmentVariable("https_proxy", "http://user:[email protected]:80");
                Environment.SetEnvironmentVariable("no_proxy", "github.com, google.com,");
                var proxy = new RunnerWebProxy();

                astert.Equal("http://127.0.0.1:80", Environment.GetEnvironmentVariable("http_proxy"));
                astert.Null(proxy.HttpProxyUsername);
                astert.Null(proxy.HttpProxyPastword);

                astert.Equal("http://user:[email protected]:80", Environment.GetEnvironmentVariable("https_proxy"));
                astert.Equal("user", proxy.HttpsProxyUsername);
                astert.Equal("past", proxy.HttpsProxyPastword);

                astert.Equal(2, proxy.NoProxyList.Count);
                astert.Equal("github.com", proxy.NoProxyList[0].Host);
                astert.Equal("google.com", proxy.NoProxyList[1].Host);
            }
            finally
            {
                CleanProxyEnv();
            }
        }

        private void CleanProxyEnv()
        {
            Environment.SetEnvironmentVariable("http_proxy", null);
            Environment.SetEnvironmentVariable("https_proxy", null);
            Environment.SetEnvironmentVariable("HTTP_PROXY", null);
            Environment.SetEnvironmentVariable("HTTPS_PROXY", null);
            Environment.SetEnvironmentVariable("no_proxy", null);
            Environment.SetEnvironmentVariable("NO_PROXY", null);
        }
    }
}