github.com/nak3/source-to-image@v1.1.10-0.20180319140719-2ed55639898d/pkg/util/env.go (about)

     1  package util
     2  
     3  import (
     4  	"bufio"
     5  	"fmt"
     6  	"net/url"
     7  	"os"
     8  	"regexp"
     9  	"strings"
    10  )
    11  
    12  // ReadEnvironmentFile reads the content for a file that contains a list of
    13  // environment variables and values. The key-pairs are separated by a new line
    14  // character. The file can also have comments (both '#' and '//' are supported).
    15  func ReadEnvironmentFile(path string) (map[string]string, error) {
    16  	f, err := os.Open(path)
    17  	if err != nil {
    18  		return nil, err
    19  	}
    20  	defer f.Close()
    21  
    22  	result := map[string]string{}
    23  
    24  	scanner := bufio.NewScanner(f)
    25  	for scanner.Scan() {
    26  		s := strings.TrimSpace(scanner.Text())
    27  		// Allow for comments in environment file
    28  		if strings.HasPrefix(s, "#") || strings.HasPrefix(s, "//") {
    29  			continue
    30  		}
    31  		parts := strings.SplitN(s, "=", 2)
    32  		if len(parts) != 2 {
    33  			continue
    34  		}
    35  		result[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
    36  	}
    37  
    38  	return result, scanner.Err()
    39  }
    40  
    41  // SafeForLoggingEnv attempts to strip sensitive information from proxy
    42  // environment variable strings in key=value form.
    43  func SafeForLoggingEnv(env []string) []string {
    44  	// case insensitively match all key=value variables containing the word "proxy"
    45  	proxyRegex := regexp.MustCompile("(?i).*proxy.*")
    46  	newEnv := make([]string, len(env))
    47  	copy(newEnv, env)
    48  	for i, entry := range newEnv {
    49  		parts := strings.SplitN(entry, "=", 2)
    50  		if !proxyRegex.MatchString(parts[0]) {
    51  			continue
    52  		}
    53  		newVal, _ := SafeForLoggingURL(parts[1])
    54  		newEnv[i] = fmt.Sprintf("%s=%s", parts[0], newVal)
    55  	}
    56  	return newEnv
    57  }
    58  
    59  // SafeForLoggingURL removes the user:password section of
    60  // a url if present.  If not present or the value is unparseable,
    61  // the value is returned unchanged.
    62  func SafeForLoggingURL(input string) (string, error) {
    63  	u, err := url.Parse(input)
    64  	if err != nil {
    65  		return input, err
    66  	}
    67  	// wipe out the user info from the url.
    68  	u.User = url.User("redacted")
    69  	return u.String(), nil
    70  }