1/*
2Package keyservice implements a gRPC API that can be used by SOPS to encrypt and decrypt the data key using remote
3master keys.
4*/
5package keyservice
6
7import (
8	"fmt"
9
10	"go.mozilla.org/sops/v3/azkv"
11	"go.mozilla.org/sops/v3/gcpkms"
12	"go.mozilla.org/sops/v3/hcvault"
13	"go.mozilla.org/sops/v3/keys"
14	"go.mozilla.org/sops/v3/kms"
15	"go.mozilla.org/sops/v3/pgp"
16)
17
18// KeyFromMasterKey converts a SOPS internal MasterKey to an RPC Key that can be serialized with Protocol Buffers
19func KeyFromMasterKey(mk keys.MasterKey) Key {
20	switch mk := mk.(type) {
21	case *pgp.MasterKey:
22		return Key{
23			KeyType: &Key_PgpKey{
24				PgpKey: &PgpKey{
25					Fingerprint: mk.Fingerprint,
26				},
27			},
28		}
29	case *gcpkms.MasterKey:
30		return Key{
31			KeyType: &Key_GcpKmsKey{
32				GcpKmsKey: &GcpKmsKey{
33					ResourceId: mk.ResourceID,
34				},
35			},
36		}
37	case *hcvault.MasterKey:
38		return Key{
39			KeyType: &Key_VaultKey{
40				VaultKey: &VaultKey{
41					VaultAddress: mk.VaultAddress,
42					EnginePath:   mk.EnginePath,
43					KeyName:      mk.KeyName,
44				},
45			},
46		}
47	case *kms.MasterKey:
48		ctx := make(map[string]string)
49		for k, v := range mk.EncryptionContext {
50			ctx[k] = *v
51		}
52		return Key{
53			KeyType: &Key_KmsKey{
54				KmsKey: &KmsKey{
55					Arn:        mk.Arn,
56					Role:       mk.Role,
57					Context:    ctx,
58					AwsProfile: mk.AwsProfile,
59				},
60			},
61		}
62	case *azkv.MasterKey:
63		return Key{
64			KeyType: &Key_AzureKeyvaultKey{
65				AzureKeyvaultKey: &AzureKeyVaultKey{
66					VaultUrl: mk.VaultURL,
67					Name:     mk.Name,
68					Version:  mk.Version,
69				},
70			},
71		}
72	default:
73		panic(fmt.Sprintf("Tried to convert unknown MasterKey type %T to keyservice.Key", mk))
74	}
75}
76