|
| 1 | +package acskms |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/base64" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "regexp" |
| 8 | + "strings" |
| 9 | + "time" |
| 10 | + |
| 11 | + openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" |
| 12 | + kmssdk "github.com/alibabacloud-go/kms-20160120/v3/client" |
| 13 | + "github.com/alibabacloud-go/tea/tea" |
| 14 | + "github.com/aliyun/credentials-go/credentials" |
| 15 | + "github.com/getsops/sops/v3/keys" |
| 16 | + "github.com/getsops/sops/v3/logging" |
| 17 | + "github.com/sirupsen/logrus" |
| 18 | +) |
| 19 | + |
| 20 | +const ( |
| 21 | + // arnRegex matches an ACS ARN, for example: |
| 22 | + // "acs:kms:cn-shanghai:1234567890:key/key-idxxxxx". |
| 23 | + arnRegex = `^acs:kms:(.+):[0-9]+:key/(.+)$` |
| 24 | + // kmsTTL is the duration after which a MasterKey requires rotation. |
| 25 | + kmsTTL = time.Hour |
| 26 | + // KeyTypeIdentifier is the string used to identify an ACS KMS MasterKey. |
| 27 | + KeyTypeIdentifier = "acs_kms" |
| 28 | +) |
| 29 | + |
| 30 | +var ( |
| 31 | + // log is the global logger for any Alibaba Cloud KMS MasterKey. |
| 32 | + log *logrus.Logger |
| 33 | +) |
| 34 | + |
| 35 | +func init() { |
| 36 | + log = logging.NewLogger("ACSKMS") |
| 37 | +} |
| 38 | + |
| 39 | +// MasterKey is an Alibaba Cloud KMS key used to encrypt and decrypt SOPS' data key. |
| 40 | +type MasterKey struct { |
| 41 | + // Arn is the full key identifier in format "region:key-id" or an ARN |
| 42 | + Arn string |
| 43 | + // Region is the Alibaba Cloud region (e.g., "cn-hangzhou") |
| 44 | + Region string |
| 45 | + // EncryptedKey stores the data key in its encrypted form. |
| 46 | + EncryptedKey string |
| 47 | + // CreationDate is when this MasterKey was created. |
| 48 | + CreationDate time.Time |
| 49 | +} |
| 50 | + |
| 51 | +// NewMasterKey creates a new MasterKey from a key arn string, setting |
| 52 | +// the creation date to the current date. |
| 53 | +func NewMasterKey(arn string) (*MasterKey, error) { |
| 54 | + region, err := parseKeyArn(arn) |
| 55 | + if err != nil { |
| 56 | + return nil, err |
| 57 | + } |
| 58 | + return &MasterKey{ |
| 59 | + Arn: arn, |
| 60 | + Region: region, |
| 61 | + CreationDate: time.Now().UTC(), |
| 62 | + }, nil |
| 63 | +} |
| 64 | + |
| 65 | +// NewMasterKeyFromKeyIDString takes a comma separated list of Alibaba Cloud KMS |
| 66 | +// key ARNs, and returns a slice of new MasterKeys. |
| 67 | +func NewMasterKeyFromKeyIDString(keyArn string) ([]*MasterKey, error) { |
| 68 | + var keys []*MasterKey |
| 69 | + if keyArn == "" { |
| 70 | + return keys, nil |
| 71 | + } |
| 72 | + for _, s := range strings.Split(keyArn, ",") { |
| 73 | + s = strings.TrimSpace(s) |
| 74 | + if s == "" { |
| 75 | + continue |
| 76 | + } |
| 77 | + k, err := NewMasterKey(s) |
| 78 | + if err != nil { |
| 79 | + return nil, err |
| 80 | + } |
| 81 | + keys = append(keys, k) |
| 82 | + } |
| 83 | + return keys, nil |
| 84 | +} |
| 85 | + |
| 86 | +// parseKeyArn parse an Alibaba Cloud KMS key identifier, which can be a full ARN. |
| 87 | +func parseKeyArn(arn string) (string, error) { |
| 88 | + re := regexp.MustCompile(arnRegex) |
| 89 | + matches := re.FindStringSubmatch(arn) |
| 90 | + if len(matches) != 3 { |
| 91 | + return "", fmt.Errorf("invalid ACS KMS key ARN: %s", arn) |
| 92 | + } |
| 93 | + |
| 94 | + return matches[1], nil |
| 95 | +} |
| 96 | + |
| 97 | +// Encrypt encrypts the data key using Alibaba Cloud KMS. |
| 98 | +func (key *MasterKey) Encrypt(dataKey []byte) error { |
| 99 | + client, err := key.getClient() |
| 100 | + if err != nil { |
| 101 | + return err |
| 102 | + } |
| 103 | + |
| 104 | + request := &kmssdk.EncryptRequest{ |
| 105 | + KeyId: tea.String(key.Arn), |
| 106 | + Plaintext: tea.String(base64.StdEncoding.EncodeToString(dataKey)), |
| 107 | + } |
| 108 | + |
| 109 | + resp, err := client.Encrypt(request) |
| 110 | + if err != nil { |
| 111 | + return fmt.Errorf("acskms encrypt error: %v", err) |
| 112 | + } |
| 113 | + |
| 114 | + key.EncryptedKey = *resp.Body.CiphertextBlob |
| 115 | + return nil |
| 116 | +} |
| 117 | + |
| 118 | +// Decrypt decrypts the data key using Alibaba Cloud KMS. |
| 119 | +func (key *MasterKey) Decrypt() ([]byte, error) { |
| 120 | + client, err := key.getClient() |
| 121 | + if err != nil { |
| 122 | + return nil, err |
| 123 | + } |
| 124 | + |
| 125 | + request := &kmssdk.DecryptRequest{ |
| 126 | + CiphertextBlob: tea.String(key.EncryptedKey), |
| 127 | + } |
| 128 | + // If an endpoint is manually set (e.g. KMS Instance), we might need to rely on the SDK's behavior. |
| 129 | + // The standard SDK usually works fine with CiphertextBlob. |
| 130 | + |
| 131 | + resp, err := client.Decrypt(request) |
| 132 | + if err != nil { |
| 133 | + return nil, fmt.Errorf("acskms decrypt error: %v", err) |
| 134 | + } |
| 135 | + |
| 136 | + return base64.StdEncoding.DecodeString(*resp.Body.Plaintext) |
| 137 | +} |
| 138 | + |
| 139 | +// EncryptIfNeeded encrypts the data key if it's not already encrypted. |
| 140 | +func (key *MasterKey) EncryptIfNeeded(dataKey []byte) error { |
| 141 | + if key.EncryptedKey == "" { |
| 142 | + return key.Encrypt(dataKey) |
| 143 | + } |
| 144 | + return nil |
| 145 | +} |
| 146 | + |
| 147 | +// EncryptedDataKey returns the encrypted data key. |
| 148 | +func (key *MasterKey) EncryptedDataKey() []byte { |
| 149 | + return []byte(key.EncryptedKey) |
| 150 | +} |
| 151 | + |
| 152 | +// SetEncryptedDataKey sets the encrypted data key. |
| 153 | +func (key *MasterKey) SetEncryptedDataKey(enc []byte) { |
| 154 | + key.EncryptedKey = string(enc) |
| 155 | +} |
| 156 | + |
| 157 | +// NeedsRotation checks if the key needs rotation. |
| 158 | +func (key *MasterKey) NeedsRotation() bool { |
| 159 | + return false |
| 160 | +} |
| 161 | + |
| 162 | +// ToString returns the string representation of the key. |
| 163 | +func (key *MasterKey) ToString() string { |
| 164 | + return key.Arn |
| 165 | +} |
| 166 | + |
| 167 | +// ToMap returns the map representation of the key. |
| 168 | +func (key *MasterKey) ToMap() map[string]interface{} { |
| 169 | + return map[string]interface{}{ |
| 170 | + "arn": key.Arn, |
| 171 | + "created_at": key.CreationDate.UTC().Format(time.RFC3339), |
| 172 | + "enc": key.EncryptedKey, |
| 173 | + } |
| 174 | +} |
| 175 | + |
| 176 | +// TypeToIdentifier returns the type identifier of the key. |
| 177 | +func (key *MasterKey) TypeToIdentifier() string { |
| 178 | + return KeyTypeIdentifier |
| 179 | +} |
| 180 | + |
| 181 | +// getClient returns a new Alibaba Cloud KMS client. |
| 182 | +func (key *MasterKey) getClient() (*kmssdk.Client, error) { |
| 183 | + cred, err := credentials.NewCredential(nil) |
| 184 | + if err != nil { |
| 185 | + return nil, fmt.Errorf("acskms credential error: %v", err) |
| 186 | + } |
| 187 | + |
| 188 | + config := &openapi.Config{ |
| 189 | + Credential: cred, |
| 190 | + RegionId: tea.String(key.Region), |
| 191 | + } |
| 192 | + |
| 193 | + if endpoint := os.Getenv("SOPS_ACSKMS_INSTANCE_ENDPOINT"); endpoint != "" { |
| 194 | + config.Endpoint = tea.String(endpoint) |
| 195 | + } else if key.Region != "" { |
| 196 | + config.Endpoint = tea.String(fmt.Sprintf("kms.%s.aliyuncs.com", key.Region)) |
| 197 | + } |
| 198 | + |
| 199 | + if caFile := os.Getenv("SOPS_ACSKMS_CA_FILE"); caFile != "" { |
| 200 | + caContent, err := os.ReadFile(caFile) |
| 201 | + if err == nil { |
| 202 | + config.Ca = tea.String(string(caContent)) |
| 203 | + } else { |
| 204 | + log.Warnf("Failed to read CA file %s: %v", caFile, err) |
| 205 | + } |
| 206 | + } |
| 207 | + |
| 208 | + client, err := kmssdk.NewClient(config) |
| 209 | + if err != nil { |
| 210 | + return nil, fmt.Errorf("acskms client error: %v", err) |
| 211 | + } |
| 212 | + return client, nil |
| 213 | +} |
| 214 | + |
| 215 | +// ApplyToMasterKey applies the key parameters to the MasterKey. |
| 216 | +// Helper to reconstruct key from map. |
| 217 | +func (key *MasterKey) ApplyToMasterKey(k keys.MasterKey) { |
| 218 | + // Not strictly needed for basic interface but good to have parity |
| 219 | +} |
0 commit comments