Skip to content

Commit a15b09f

Browse files
committed
Fix regression in STS endpoint for SOPS decryption with AWS KMS
Signed-off-by: Matheus Pimenta <matheuscscp@gmail.com>
1 parent 124402b commit a15b09f

2 files changed

Lines changed: 45 additions & 9 deletions

File tree

internal/sops/awskms/region.go

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,27 @@ limitations under the License.
1717
package awskms
1818

1919
import (
20-
"strings"
20+
"regexp"
2121
)
2222

23+
// arnRegex matches an AWS ARN, for example:
24+
// "arn:aws:kms:us-west-2:107501996527:key/612d5f0p-p1l3-45e6-aca6-a5b005693a48".
25+
// The regex matches both KMS keys and aliases, and supports different AWS partition names (aws, aws-cn, aws-us-gov).
26+
//
27+
// Copied from SOPS:
28+
// https://github.com/getsops/sops/blob/b2edaade23453c8774fc28ec491ddbe2b9a4c994/kms/keysource.go#L30-L32
29+
//
30+
// ref:
31+
// https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html
32+
const arnPattern = `^arn:aws[\w-]*:kms:(.+):[0-9]+:(key|alias)/.+$`
33+
34+
var arnRegex = regexp.MustCompile(arnPattern)
35+
2336
// GetRegionFromKMSARN extracts the region from a KMS ARN.
2437
func GetRegionFromKMSARN(arn string) string {
25-
arn = strings.TrimPrefix(arn, "arn:aws:kms:")
26-
return strings.SplitN(arn, ":", 2)[0]
38+
m := arnRegex.FindStringSubmatch(arn)
39+
if m == nil {
40+
return ""
41+
}
42+
return m[1]
2743
}

internal/sops/awskms/region_test.go

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,30 @@ import (
2525
)
2626

2727
func TestGetRegionFromKMSARN(t *testing.T) {
28-
g := NewWithT(t)
29-
30-
arn := "arn:aws:kms:us-east-1:211125720409:key/mrk-3179bb7e88bc42ffb1a27d5038ceea25"
31-
32-
region := awskms.GetRegionFromKMSARN(arn)
33-
g.Expect(region).To(Equal("us-east-1"))
28+
for _, tc := range []struct {
29+
arn string
30+
expected string
31+
}{
32+
{
33+
arn: "arn:aws:kms:us-west-2:107501996527:key/612d5f0p-p1l3-45e6-aca6-a5b005693a48",
34+
expected: "us-west-2",
35+
},
36+
{
37+
arn: "arn:aws-cn:kms:cn-north-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab",
38+
expected: "cn-north-1",
39+
},
40+
{
41+
arn: "arn:aws-us-gov:kms:us-gov-west-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab",
42+
expected: "us-gov-west-1",
43+
},
44+
{
45+
arn: "arn:aws:kms:us-west-2:107501996527:alias/my-key-alias",
46+
expected: "us-west-2",
47+
},
48+
} {
49+
t.Run(tc.arn, func(t *testing.T) {
50+
g := NewWithT(t)
51+
g.Expect(awskms.GetRegionFromKMSARN(tc.arn)).To(Equal(tc.expected))
52+
})
53+
}
3454
}

0 commit comments

Comments
 (0)