"Fossies" - the Fresh Open Source Software Archive

Member "cli-1.1280.1/cliv2/internal/proxy/proxy_test.go" (20 Feb 2024, 6925 Bytes) of package /linux/misc/snyk-cli-1.1280.1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Go source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 package proxy_test
    2 
    3 import (
    4     "crypto/tls"
    5     "crypto/x509"
    6     "encoding/base64"
    7     "fmt"
    8     "io/ioutil"
    9     "log"
   10     "net/http"
   11     "net/url"
   12     "os"
   13     "testing"
   14 
   15     "github.com/snyk/go-application-framework/pkg/configuration"
   16     "github.com/snyk/go-application-framework/pkg/networking/certs"
   17     "github.com/snyk/go-httpauth/pkg/httpauth"
   18 
   19     "github.com/snyk/cli/cliv2/internal/constants"
   20     "github.com/snyk/cli/cliv2/internal/proxy"
   21     "github.com/snyk/cli/cliv2/internal/utils"
   22 
   23     "github.com/stretchr/testify/assert"
   24 )
   25 
   26 var debugLogger *log.Logger = log.New(os.Stderr, "", log.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile)
   27 
   28 func helper_getHttpClient(gateway *proxy.WrapperProxy, useProxyAuth bool) (*http.Client, error) {
   29     rootCAs, _ := x509.SystemCertPool()
   30     if rootCAs == nil {
   31         rootCAs = x509.NewCertPool()
   32     }
   33 
   34     proxyCertBytes, err := ioutil.ReadFile(gateway.CertificateLocation)
   35     if err != nil {
   36         return nil, err
   37     }
   38 
   39     ok := rootCAs.AppendCertsFromPEM(proxyCertBytes)
   40     if ok == false {
   41         return nil, fmt.Errorf("failed to append proxy cert")
   42     }
   43 
   44     config := &tls.Config{
   45         InsecureSkipVerify: false,
   46         RootCAs:            rootCAs,
   47     }
   48 
   49     var proxyUrl *url.URL
   50     proxyInfo := gateway.ProxyInfo()
   51     if useProxyAuth {
   52         proxyUrl, err = url.Parse(fmt.Sprintf("http://%s:%s@127.0.0.1:%d", proxy.PROXY_USERNAME, proxyInfo.Password, proxyInfo.Port))
   53     } else {
   54         proxyUrl, err = url.Parse(fmt.Sprintf("http://127.0.0.1:%d", proxyInfo.Port))
   55     }
   56 
   57     if err != nil {
   58         return nil, err
   59     }
   60 
   61     proxiedClient := &http.Client{Transport: &http.Transport{
   62         Proxy:           http.ProxyURL(proxyUrl),
   63         TLSClientConfig: config,
   64     }}
   65 
   66     return proxiedClient, nil
   67 }
   68 
   69 func setup(t *testing.T, baseCache string, version string) {
   70     err := utils.CreateAllDirectories(baseCache, version)
   71     assert.Nil(t, err)
   72 }
   73 
   74 func teardown(t *testing.T, baseCache string) {
   75     err := os.RemoveAll(baseCache)
   76     assert.Nil(t, err)
   77 }
   78 
   79 func Test_closingProxyDeletesTempCert(t *testing.T) {
   80     basecache := "testcache"
   81     version := "1.1.1"
   82     setup(t, basecache, version)
   83     defer teardown(t, basecache)
   84 
   85     config := configuration.NewInMemory()
   86     config.Set(configuration.CACHE_PATH, basecache)
   87     config.Set(configuration.INSECURE_HTTPS, false)
   88 
   89     wp, err := proxy.NewWrapperProxy(config, version, debugLogger)
   90     assert.Nil(t, err)
   91 
   92     err = wp.Start()
   93     t.Log("proxy port:", wp.ProxyInfo().Port)
   94     assert.Nil(t, err)
   95 
   96     wp.Close()
   97 
   98     // assert cert file is deleted
   99     _, err = os.Stat(wp.CertificateLocation)
  100     assert.NotNil(t, err) // this means the file is gone
  101 }
  102 
  103 func basicAuthValue(username string, password string) string {
  104     return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  105 }
  106 
  107 func Test_canGoThroughProxy(t *testing.T) {
  108     basecache := "testcache"
  109     version := "1.1.1"
  110     config := configuration.NewInMemory()
  111     config.Set(configuration.CACHE_PATH, basecache)
  112     config.Set(configuration.INSECURE_HTTPS, false)
  113 
  114     setup(t, basecache, version)
  115     defer teardown(t, basecache)
  116 
  117     wp, err := proxy.NewWrapperProxy(config, version, debugLogger)
  118     assert.Nil(t, err)
  119 
  120     err = wp.Start()
  121     assert.Nil(t, err)
  122 
  123     useProxyAuth := true
  124     proxiedClient, err := helper_getHttpClient(wp, useProxyAuth)
  125     assert.Nil(t, err)
  126 
  127     res, err := proxiedClient.Get("https://static.snyk.io/cli/latest/version")
  128     if err != nil {
  129         t.Fatal(err)
  130     }
  131     assert.Equal(t, 200, res.StatusCode)
  132 
  133     wp.Close()
  134 
  135     // assert cert file is deleted on Close
  136     _, err = os.Stat(wp.CertificateLocation)
  137     assert.NotNil(t, err) // this means the file is gone
  138 }
  139 
  140 func Test_proxyRejectsWithoutBasicAuthHeader(t *testing.T) {
  141     basecache := "testcache"
  142     version := "1.1.1"
  143     config := configuration.NewInMemory()
  144     config.Set(configuration.CACHE_PATH, basecache)
  145     config.Set(configuration.INSECURE_HTTPS, false)
  146 
  147     setup(t, basecache, version)
  148     defer teardown(t, basecache)
  149 
  150     wp, err := proxy.NewWrapperProxy(config, version, debugLogger)
  151     assert.Nil(t, err)
  152 
  153     err = wp.Start()
  154     assert.Nil(t, err)
  155 
  156     useProxyAuth := false
  157     proxiedClient, err := helper_getHttpClient(wp, useProxyAuth)
  158     assert.Nil(t, err)
  159 
  160     res, err := proxiedClient.Get("https://static.snyk.io/cli/latest/version")
  161     assert.Nil(t, res)
  162     assert.NotNil(t, err)
  163     assert.Contains(t, err.Error(), "Proxy Authentication Required")
  164 
  165     wp.Close()
  166 
  167     // assert cert file is deleted on Close
  168     _, err = os.Stat(wp.CertificateLocation)
  169     assert.NotNil(t, err) // this means the file is gone
  170 }
  171 
  172 func Test_SetUpstreamProxy(t *testing.T) {
  173     basecache := "testcache"
  174     version := "1.1.1"
  175     config := configuration.NewInMemory()
  176     config.Set(configuration.CACHE_PATH, basecache)
  177     config.Set(configuration.INSECURE_HTTPS, false)
  178 
  179     setup(t, basecache, version)
  180     defer teardown(t, basecache)
  181 
  182     var err error
  183     var objectUnderTest *proxy.WrapperProxy
  184 
  185     testUrl, _ := url.Parse("http://www.snyk.io")
  186     testRequest := http.Request{URL: testUrl}
  187 
  188     upstreanProxyUrlAsString := "http://localhost:3128"
  189     expectedUpstreamProxyUrl, _ := url.Parse(upstreanProxyUrlAsString)
  190 
  191     // using different cases to determine whether the proxy actually switches the mode authentication mode
  192     testCaseList := []httpauth.AuthenticationMechanism{
  193         httpauth.Negotiate,
  194         httpauth.AnyAuth,
  195         httpauth.NoAuth,
  196         httpauth.UnknownMechanism,
  197     }
  198 
  199     objectUnderTest, err = proxy.NewWrapperProxy(config, version, debugLogger)
  200     assert.Nil(t, err)
  201 
  202     // running different cases
  203     for i := range testCaseList {
  204         currentMechanism := testCaseList[i]
  205         t.Logf(" - using %s", httpauth.StringFromAuthenticationMechanism(currentMechanism))
  206 
  207         objectUnderTest.SetUpstreamProxyAuthentication(currentMechanism)
  208         objectUnderTest.SetUpstreamProxyFromUrl(upstreanProxyUrlAsString)
  209         transport := objectUnderTest.Transport()
  210         proxyFunc := objectUnderTest.UpstreamProxy()
  211 
  212         assert.NotNil(t, proxyFunc)
  213         actualUrl, err := proxyFunc(&testRequest)
  214         assert.Nil(t, err)
  215         assert.Equal(t, expectedUpstreamProxyUrl, actualUrl)
  216 
  217         // check transport and thereby authenticator configuration
  218         if httpauth.IsSupportedMechanism(currentMechanism) {
  219             assert.NotNil(t, transport.DialContext)
  220             assert.Nil(t, transport.Proxy)
  221         } else {
  222             assert.Nil(t, transport.DialContext)
  223             assert.NotNil(t, transport.Proxy)
  224         }
  225     }
  226 }
  227 
  228 func Test_appendExtraCaCert(t *testing.T) {
  229     basecache := "testcache"
  230     version := "1.1.1"
  231     config := configuration.NewInMemory()
  232     config.Set(configuration.CACHE_PATH, basecache)
  233     config.Set(configuration.INSECURE_HTTPS, false)
  234 
  235     setup(t, basecache, version)
  236     defer teardown(t, basecache)
  237 
  238     certPem, _, _ := certs.MakeSelfSignedCert("mycert", []string{"dns"}, debugLogger)
  239     file, _ := os.CreateTemp("", "")
  240     file.Write(certPem)
  241 
  242     os.Setenv(constants.SNYK_CA_CERTIFICATE_LOCATION_ENV, file.Name())
  243 
  244     wp, err := proxy.NewWrapperProxy(config, version, debugLogger)
  245     assert.Nil(t, err)
  246 
  247     certsPem, err := os.ReadFile(wp.CertificateLocation)
  248     assert.Nil(t, err)
  249 
  250     certsList, err := certs.GetAllCerts(certsPem)
  251     assert.Nil(t, err)
  252     assert.Equal(t, 2, len(certsList))
  253 
  254     // cleanup
  255     os.Unsetenv(constants.SNYK_CA_CERTIFICATE_LOCATION_ENV)
  256     os.Remove(file.Name())
  257 }