github.com/olli-ai/jx/v2@v2.0.400-0.20210921045218-14731b4dd448/pkg/secreturl/helpers.go (about) 1 package secreturl 2 3 import ( 4 "fmt" 5 "regexp" 6 "strings" 7 8 "github.com/olli-ai/jx/v2/pkg/util" 9 "github.com/pkg/errors" 10 ) 11 12 // ReplaceURIs will replace any URIs with the given regular expression and scheme using the secret URL client 13 func ReplaceURIs(s string, client Client, r *regexp.Regexp, schemePrefix string) (string, error) { 14 if !strings.HasSuffix(schemePrefix, ":") { 15 return s, fmt.Errorf("the scheme prefix should end with ':' but was %s", schemePrefix) 16 } 17 var err error 18 answer := r.ReplaceAllStringFunc(s, func(found string) string { 19 // Stop once we have an error 20 if err == nil { 21 prefix, found := trimBeforePrefix(found, schemePrefix) 22 pathAndKey := strings.Trim(strings.TrimPrefix(found, schemePrefix), "\"") 23 parts := strings.Split(pathAndKey, ":") 24 if len(parts) != 2 { 25 err = errors.Errorf("cannot parse %q as path:key", pathAndKey) 26 return "" 27 } 28 secret, err1 := client.Read(parts[0]) 29 if err1 != nil { 30 err = errors.Wrapf(err1, "reading %q from vault", parts[0]) 31 return "" 32 } 33 v, ok := secret[parts[1]] 34 if !ok { 35 err = errors.Errorf("unable to find %q in secret at %q", parts[1], parts[0]) 36 return "" 37 } 38 result, err1 := util.AsString(v) 39 if err1 != nil { 40 err = errors.Wrapf(err1, "converting %v to string", v) 41 return "" 42 } 43 return prefix + result 44 } 45 return found 46 }) 47 if err != nil { 48 return "", errors.Wrapf(err, "replacing vault paths in %s", s) 49 } 50 return answer, nil 51 } 52 53 // trimBeforePrefix remove any chars before the given prefix 54 func trimBeforePrefix(s string, prefix string) (string, string) { 55 i := strings.Index(s, prefix) 56 return s[:i], s[i:] 57 } 58 59 // ToURI constructs a vault: URI for the given path and key 60 func ToURI(path string, key string, scheme string) string { 61 return fmt.Sprintf("%s:%s:%s", scheme, path, key) 62 }