github.com/microsoft/moc@v0.17.1/pkg/validations/proxy_validation.go (about) 1 // Copyright (c) Microsoft Corporation. All rights reserved. 2 // Licensed under the Apache v2.0 license. 3 4 package validations 5 6 import ( 7 "crypto/tls" 8 "crypto/x509" 9 "fmt" 10 "net/http" 11 "net/url" 12 13 "github.com/microsoft/moc/pkg/errors" 14 commonproto "github.com/microsoft/moc/rpc/common" 15 ) 16 17 func ValidateProxyURL(proxyURL string) (*url.URL, error) { 18 parsedURL, err := url.ParseRequestURI(proxyURL) 19 20 if err != nil { 21 return nil, errors.Wrapf(errors.InvalidInput, err.Error()) 22 } 23 24 // Check if url scheme is http or https 25 if parsedURL.Scheme != "http" && parsedURL.Scheme != "https" { 26 return nil, errors.Wrapf(errors.InvalidInput, "Invalid proxy URL. The URL scheme should be http or https") 27 } 28 29 return parsedURL, nil 30 } 31 32 func TestProxyUrlConnection(parsedURL *url.URL, certContent string, getRequestUrl string) error { 33 // Create a certificate pool 34 caCertPool := x509.NewCertPool() 35 caCertPool.AppendCertsFromPEM([]byte(certContent)) 36 37 // Create a transport 38 transport := &http.Transport{ 39 Proxy: http.ProxyURL(parsedURL), 40 TLSClientConfig: &tls.Config{ 41 RootCAs: caCertPool, 42 }, 43 } 44 45 // Create a client 46 client := &http.Client{ 47 Transport: transport, 48 } 49 50 if getRequestUrl == "" { 51 getRequestUrl = "https://mcr.microsoft.com" 52 } 53 54 // Test the HTTP GET request 55 response, err := client.Get(getRequestUrl) 56 if err != nil { 57 return errors.Wrapf(errors.InvalidInput, err.Error()) 58 } else { 59 defer response.Body.Close() 60 fmt.Println("Connected successfully to the proxy server") 61 } 62 63 return nil 64 } 65 66 func ValidateProxyParameters(proxyConfig *commonproto.ProxyConfiguration) error { 67 if proxyConfig == nil { 68 return nil 69 } 70 // Validations for proxy parameters 71 if len(proxyConfig.HttpProxy) > 0 { 72 _, err := ValidateProxyURL(proxyConfig.HttpProxy) 73 if err != nil { 74 return err 75 } 76 } 77 78 if len(proxyConfig.HttpsProxy) > 0 { 79 _, err := ValidateProxyURL(proxyConfig.HttpsProxy) 80 if err != nil { 81 return err 82 } 83 } 84 85 return nil 86 }