diff --git a/main.go b/main.go index 0a83a2c..81fbd5d 100644 --- a/main.go +++ b/main.go @@ -1,11 +1,11 @@ package main import ( + "go.mozilla.org/sops/v3" "io/ioutil" "log" "os" - "go.mozilla.org/sops/v3/aes" sopsYAML "go.mozilla.org/sops/v3/stores/yaml" coreV1 "k8s.io/api/core/v1" metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -20,12 +20,7 @@ func main() { log.Panic(filePath, ": ", err) } - decryptedData, err := decrypt(encryptedData) - if err != nil { - log.Panic(filePath, ": ", err) - } - - secret, err := makeSecret(decryptedData) + secret, err := toSecret(encryptedData) if err != nil { log.Panic(filePath, ": ", err) } @@ -35,37 +30,71 @@ func main() { } } -func decrypt(data []byte) ([]byte, error) { - // Initialize a Sops JSON store +func toSecret(data []byte) ([]byte, error) { store := &sopsYAML.Store{} - - // Load SOPS file and access the data key tree, err := store.LoadEncryptedFile(data) if err != nil { return nil, err } - key, err := tree.Metadata.GetDataKey() - if err != nil { - return nil, err - } - - // Decrypt the tree - if _, err := tree.Decrypt(key, aes.NewCipher()); err != nil { - return nil, err - } - return store.EmitPlainFile(tree.Branches) -} - -func makeSecret(data []byte) ([]byte, error) { secret := coreV1.Secret{} - if err := yaml.Unmarshal(data, &secret); err != nil { - return nil, err - } secret.TypeMeta = metaV1.TypeMeta{ APIVersion: "v1", Kind: "Secret", } - + secret.Data = getData(tree.Branches) + secret.StringData = getStringData(tree.Branches) + + metadata := getMetadata(tree.Branches) + secret.ObjectMeta.Name = metadata["name"] + secret.ObjectMeta.Namespace = metadata["namespace"] + return yaml.Marshal(secret) } + +func getData(branches sops.TreeBranches) map[string][]byte { + for _, item := range branches[0] { + if item.Key == "data" { + var result = make(map[string][]byte) + dataFields := item.Value.(sops.TreeBranch) + for _, df := range dataFields { + result[df.Key.(string)] = []byte("no-decrypt") + } + return result + } + } + return nil +} + +func getStringData(branches sops.TreeBranches) map[string]string { + for _, item := range branches[0] { + if item.Key == "stringData" { + var result = make(map[string]string) + stringData := item.Value.(sops.TreeBranch) + for _, df := range stringData { + result[df.Key.(string)] = "no-decrypt" + } + return result + } + } + return nil +} + +func getMetadata(branches sops.TreeBranches) map[string]string { + for _, item := range branches[0] { + if item.Key == "metadata" { + var result = make(map[string]string) + + metadata := item.Value.(sops.TreeBranch) + for _, mdta := range metadata { + if mdta.Key.(string) == "name" { + result["name"] = mdta.Value.(string) + } else if mdta.Key.(string) == "namespace" { + result["namespace"] = mdta.Value.(string) + } + } + return result + } + } + return nil +}