From 5fe7910ab82b70c722384f3b66539c63467d43b5 Mon Sep 17 00:00:00 2001 From: Boris Kreitchman Date: Sat, 10 Sep 2022 15:36:07 +0300 Subject: [PATCH] Sort masterkeys so offline decrypt methods are tried first Signed-off-by: Boris Kreitchman --- controllers/kustomization_decryptor.go | 8 ++++++++ internal/sops/keyservice/keyservice.go | 23 +++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 internal/sops/keyservice/keyservice.go diff --git a/controllers/kustomization_decryptor.go b/controllers/kustomization_decryptor.go index 7365b60c..ffdc4768 100644 --- a/controllers/kustomization_decryptor.go +++ b/controllers/kustomization_decryptor.go @@ -25,6 +25,7 @@ import ( "io/fs" "os" "path/filepath" + "sort" "strings" "sync" "time" @@ -280,6 +281,13 @@ func (d *KustomizeDecryptor) SopsDecryptWithFormat(data []byte, inputFormat, out return nil, sopsUserErr(fmt.Sprintf("failed to load encrypted %s data", sopsFormatToString[inputFormat]), err) } + for _, group := range tree.Metadata.KeyGroups { + // Sort MasterKeys in the group so offline ones are tried first + sort.SliceStable(group, func(i, j int) bool { + return intkeyservice.IsOfflineMethod(group[i]) && !intkeyservice.IsOfflineMethod(group[j]) + }) + } + metadataKey, err := tree.Metadata.GetDataKeyWithKeyServices(d.keyServiceServer()) if err != nil { return nil, sopsUserErr("cannot get sops data key", err) diff --git a/internal/sops/keyservice/keyservice.go b/internal/sops/keyservice/keyservice.go new file mode 100644 index 00000000..4d2dda56 --- /dev/null +++ b/internal/sops/keyservice/keyservice.go @@ -0,0 +1,23 @@ +// Copyright (C) 2022 The Flux authors +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +package keyservice + +import ( + "go.mozilla.org/sops/v3/age" + "go.mozilla.org/sops/v3/keys" + "go.mozilla.org/sops/v3/pgp" +) + +// IsOfflineMethod returns true for offline decrypt methods or false otherwise +func IsOfflineMethod(mk keys.MasterKey) bool { + switch mk.(type) { + case *pgp.MasterKey, *age.MasterKey: + return true + default: + return false + } +}