github.com/liamawhite/cli-with-i18n@v6.32.1-0.20171122084555-dede0a5c3448+incompatible/util/ui/sanitize_json.go (about)

     1  package ui
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"regexp"
     7  )
     8  
     9  var keysToSanitize = regexp.MustCompile("(?i).*(?:token|password).*")
    10  
    11  const tokenEndpoint = "token_endpoint"
    12  
    13  func SanitizeJSON(raw []byte) (map[string]interface{}, error) {
    14  	var result map[string]interface{}
    15  	decoder := json.NewDecoder(bytes.NewBuffer(raw))
    16  	decoder.UseNumber()
    17  	err := decoder.Decode(&result)
    18  	if err != nil {
    19  		return nil, err
    20  	}
    21  
    22  	return iterateAndRedact(result), nil
    23  }
    24  
    25  func iterateAndRedact(blob map[string]interface{}) map[string]interface{} {
    26  	for key, value := range blob {
    27  		switch v := value.(type) {
    28  		case string:
    29  			if keysToSanitize.Match([]byte(key)) && key != tokenEndpoint {
    30  				blob[key] = RedactedValue
    31  			}
    32  		case map[string]interface{}:
    33  			blob[key] = iterateAndRedact(v)
    34  		}
    35  	}
    36  
    37  	return blob
    38  }