Skip to content

Commit dbe229b

Browse files
committed
updated verification to aws sdk go v2
1 parent 10fc564 commit dbe229b

File tree

11 files changed

+222
-209
lines changed

11 files changed

+222
-209
lines changed

cmd/aws-iam-authenticator/root.go

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,12 @@ import (
2020
"errors"
2121
"fmt"
2222
"os"
23+
"slices"
2324
"strings"
2425

2526
"sigs.k8s.io/aws-iam-authenticator/pkg/config"
2627
"sigs.k8s.io/aws-iam-authenticator/pkg/mapper"
2728

28-
"github.com/aws/aws-sdk-go/aws/endpoints"
2929
"github.com/sirupsen/logrus"
3030
"github.com/spf13/cobra"
3131
"github.com/spf13/viper"
@@ -35,6 +35,16 @@ import (
3535

3636
var cfgFile string
3737

38+
var PartitionKeys = []string{
39+
"aws",
40+
"aws-cn",
41+
"aws-us-gov",
42+
"aws-iso",
43+
"aws-iso-b",
44+
"aws-iso-e",
45+
"aws-iso-f",
46+
}
47+
3848
var rootCmd = &cobra.Command{
3949
Use: "aws-iam-authenticator",
4050
Short: "A tool to authenticate to Kubernetes using AWS IAM credentials",
@@ -157,13 +167,7 @@ func getConfig() (config.Config, error) {
157167
return cfg, errors.New("cluster ID cannot be empty")
158168
}
159169

160-
partitionKeys := []string{}
161-
partitionMap := map[string]endpoints.Partition{}
162-
for _, p := range endpoints.DefaultPartitions() {
163-
partitionMap[p.ID()] = p
164-
partitionKeys = append(partitionKeys, p.ID())
165-
}
166-
if _, ok := partitionMap[cfg.PartitionID]; !ok {
170+
if (slices.Contains(PartitionKeys, cfg.PartitionID)) {
167171
return cfg, errors.New("Invalid partition")
168172
}
169173

cmd/aws-iam-authenticator/server.go

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ import (
2929
"sigs.k8s.io/aws-iam-authenticator/pkg/metrics"
3030
"sigs.k8s.io/aws-iam-authenticator/pkg/server"
3131

32-
"github.com/aws/aws-sdk-go/aws/endpoints"
3332
"github.com/prometheus/client_golang/prometheus"
3433
"github.com/sirupsen/logrus"
3534
"github.com/spf13/cobra"
@@ -67,14 +66,8 @@ var serverCmd = &cobra.Command{
6766
}
6867

6968
func init() {
70-
partitionKeys := []string{}
71-
for _, p := range endpoints.DefaultPartitions() {
72-
partitionKeys = append(partitionKeys, p.ID())
73-
}
74-
75-
serverCmd.Flags().String("partition",
76-
endpoints.AwsPartitionID,
77-
fmt.Sprintf("The AWS partition. Must be one of: %v", partitionKeys))
69+
serverCmd.Flags().String("partition", "aws",
70+
fmt.Sprintf("The AWS partition. Must be one of: %v", PartitionKeys))
7871
viper.BindPFlag("server.partition", serverCmd.Flags().Lookup("partition"))
7972

8073
serverCmd.Flags().String("generate-kubeconfig",

cmd/aws-iam-authenticator/verify.go

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,17 @@ limitations under the License.
1919
package main
2020

2121
import (
22+
"context"
2223
"encoding/json"
2324
"fmt"
2425
"os"
2526

2627
"sigs.k8s.io/aws-iam-authenticator/pkg/token"
2728

28-
"github.com/aws/aws-sdk-go/aws/ec2metadata"
29+
"github.com/aws/aws-sdk-go-v2/config"
30+
"github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
31+
"github.com/aws/aws-sdk-go-v2/service/ec2"
2932
"github.com/aws/aws-sdk-go/aws/endpoints"
30-
"github.com/aws/aws-sdk-go/aws/session"
3133
"github.com/spf13/cobra"
3234
"github.com/spf13/viper"
3335
)
@@ -54,14 +56,17 @@ var verifyCmd = &cobra.Command{
5456
os.Exit(1)
5557
}
5658

57-
sess := session.Must(session.NewSession())
58-
ec2metadata := ec2metadata.New(sess)
59-
instanceRegion, err := ec2metadata.Region()
59+
ctx := context.Background()
60+
instanceRegion := getInstanceRegion(ctx)
61+
62+
cfg, err := config.LoadDefaultConfig(ctx)
6063
if err != nil {
61-
fmt.Printf("[Warn] Region not found in instance metadata, err: %v", err)
64+
fmt.Fprintf(os.Stderr, "unable to create sdk client configuration: %v\n", err)
65+
os.Exit(1)
6266
}
67+
ec2Client := ec2.NewFromConfig(cfg)
6368

64-
id, err := token.NewVerifier(clusterID, partition, instanceRegion).Verify(tok)
69+
id, err := token.NewVerifier(ctx, clusterID, partition, instanceRegion, ec2Client).Verify(tok)
6570
if err != nil {
6671
fmt.Fprintf(os.Stderr, "could not verify token: %v\n", err)
6772
os.Exit(1)
@@ -79,6 +84,24 @@ var verifyCmd = &cobra.Command{
7984
},
8085
}
8186

87+
// Uses EC2 metadata to get the region. Returns "" if no region found.
88+
func getInstanceRegion(ctx context.Context) string {
89+
cfg, err := config.LoadDefaultConfig(ctx)
90+
if err != nil {
91+
fmt.Printf("[Warn] Unable to create metadata client, err: %v", err)
92+
return ""
93+
}
94+
95+
imdsClient := imds.NewFromConfig(cfg)
96+
getRegionOutput, err := imdsClient.GetRegion(ctx, &imds.GetRegionInput{})
97+
if err != nil {
98+
fmt.Printf("[Warn] Region not found in instance metadata, err: %v\n", err)
99+
return ""
100+
}
101+
102+
return getRegionOutput.Region
103+
}
104+
82105
func init() {
83106
rootCmd.AddCommand(verifyCmd)
84107
verifyCmd.Flags().StringP("token", "t", "", "Token to verify")

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ require (
88
github.com/aws/aws-sdk-go-v2/config v1.29.17
99
github.com/aws/aws-sdk-go-v2/credentials v1.17.70
1010
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.32
11+
github.com/aws/aws-sdk-go-v2/service/account v1.24.2
1112
github.com/aws/aws-sdk-go-v2/service/ec2 v1.225.2
1213
github.com/aws/aws-sdk-go-v2/service/sts v1.34.0
1314
github.com/aws/smithy-go v1.22.4
@@ -55,7 +56,6 @@ require (
5556
github.com/google/gnostic-models v0.6.9 // indirect
5657
github.com/google/uuid v1.6.0 // indirect
5758
github.com/inconshreveable/mousetrap v1.1.0 // indirect
58-
github.com/jmespath/go-jmespath v0.4.0 // indirect
5959
github.com/josharian/intern v1.0.0 // indirect
6060
github.com/json-iterator/go v1.1.12 // indirect
6161
github.com/mailru/easyjson v0.9.0 // indirect

go.sum

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.36 h1:i2vNHQiXUvKhs3quBR
1414
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.36/go.mod h1:UdyGa7Q91id/sdyHPwth+043HhmP6yP9MBHgbZM0xo8=
1515
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 h1:bIqFDwgGXXN1Kpp99pDOdKMTTb5d2KyU5X/BZxjOkRo=
1616
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3/go.mod h1:H5O/EsxDWyU+LP/V8i5sm8cxoZgc2fdNR9bxlOFrQTo=
17+
github.com/aws/aws-sdk-go-v2/service/account v1.24.2 h1:1ItkqDExKIDsS8NoIBq7OxQOJnQNOVjC25CYa9RzOos=
18+
github.com/aws/aws-sdk-go-v2/service/account v1.24.2/go.mod h1:NShtay87juyMTb3c6bHN6Bai5dUFmTX7NzURY4/Jyb0=
1719
github.com/aws/aws-sdk-go-v2/service/ec2 v1.225.2 h1:IfMb3Ar8xEaWjgH/zeVHYD8izwJdQgRP5mKCTDt4GNk=
1820
github.com/aws/aws-sdk-go-v2/service/ec2 v1.225.2/go.mod h1:35jGWx7ECvCwTsApqicFYzZ7JFEnBc6oHUuOQ3xIS54=
1921
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.4 h1:CXV68E2dNqhuynZJPB80bhPQwAKqBWVer887figW6Jc=
@@ -86,8 +88,6 @@ github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2
8688
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
8789
github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=
8890
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
89-
github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8=
90-
github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=
9191
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
9292
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
9393
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
@@ -226,7 +226,6 @@ gopkg.in/evanphx/json-patch.v4 v4.12.0 h1:n6jtcsulIzXPJaxegRbvFNNrZDjbij7ny3gmSP
226226
gopkg.in/evanphx/json-patch.v4 v4.12.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M=
227227
gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=
228228
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
229-
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
230229
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
231230
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
232231
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

pkg/ec2provider/ec2provider.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ const (
4646
// EC2API defines the interface for EC2 client operations
4747
type EC2API interface {
4848
DescribeInstances(ctx context.Context, params *ec2.DescribeInstancesInput, optFns ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error)
49+
DescribeRegions(ctx context.Context, params *ec2.DescribeRegionsInput, optFns ...func(*ec2.Options)) (*ec2.DescribeRegionsOutput, error)
4950
}
5051

5152
// Get a node name from instance ID

pkg/ec2provider/ec2provider_mock.go

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package ec2provider
2+
3+
import (
4+
"context"
5+
"sync"
6+
"time"
7+
8+
"github.com/aws/aws-sdk-go-v2/aws"
9+
"github.com/aws/aws-sdk-go-v2/service/ec2"
10+
ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
11+
)
12+
13+
type MockEc2Client struct {
14+
Reservations []*ec2types.Reservation
15+
Regions []ec2types.Region
16+
}
17+
const (
18+
DescribeDelay = 100
19+
)
20+
21+
func newMockedEC2ProviderImpl() *ec2ProviderImpl {
22+
dnsCache := ec2PrivateDNSCache{
23+
cache: make(map[string]string),
24+
lock: sync.RWMutex{},
25+
}
26+
ec2Requests := ec2Requests{
27+
set: make(map[string]bool),
28+
lock: sync.RWMutex{},
29+
}
30+
return &ec2ProviderImpl{
31+
ec2: &MockEc2Client{},
32+
privateDNSCache: dnsCache,
33+
ec2Requests: ec2Requests,
34+
instanceIdsChannel: make(chan string, maxChannelSize),
35+
}
36+
37+
}
38+
39+
func (c *MockEc2Client) DescribeInstances(ctx context.Context, in *ec2.DescribeInstancesInput, opts ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) {
40+
// simulate the time it takes for aws to return
41+
time.Sleep(DescribeDelay * time.Millisecond)
42+
var reservations []ec2types.Reservation
43+
for _, res := range c.Reservations {
44+
var reservation ec2types.Reservation
45+
for _, inst := range res.Instances {
46+
for _, id := range in.InstanceIds {
47+
if id == aws.ToString(inst.InstanceId) {
48+
reservation.Instances = append(reservation.Instances, inst)
49+
}
50+
}
51+
}
52+
if len(reservation.Instances) > 0 {
53+
reservations = append(reservations, reservation)
54+
}
55+
}
56+
return &ec2.DescribeInstancesOutput{
57+
Reservations: reservations,
58+
}, nil
59+
}
60+
61+
func (c *MockEc2Client) DescribeRegions(ctx context.Context, params *ec2.DescribeRegionsInput, optFns ...func(*ec2.Options)) (*ec2.DescribeRegionsOutput, error) {
62+
if c.Regions == nil {
63+
return &ec2.DescribeRegionsOutput{}, nil
64+
}
65+
return &ec2.DescribeRegionsOutput{Regions: c.Regions}, nil
66+
}

pkg/ec2provider/ec2provider_test.go

Lines changed: 2 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -10,66 +10,16 @@ import (
1010

1111
"github.com/aws/aws-sdk-go-v2/aws"
1212
"github.com/aws/aws-sdk-go-v2/credentials"
13-
"github.com/aws/aws-sdk-go-v2/service/ec2"
1413
ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
1514
"github.com/aws/aws-sdk-go-v2/service/sts"
1615
"github.com/prometheus/client_golang/prometheus"
1716
"sigs.k8s.io/aws-iam-authenticator/pkg/metrics"
1817
)
1918

20-
const (
21-
DescribeDelay = 100
22-
)
23-
24-
type mockEc2Client struct {
25-
EC2API
26-
Reservations []*ec2types.Reservation
27-
}
28-
29-
func (c *mockEc2Client) DescribeInstances(ctx context.Context, in *ec2.DescribeInstancesInput, opts ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) {
30-
// simulate the time it takes for aws to return
31-
time.Sleep(DescribeDelay * time.Millisecond)
32-
var reservations []ec2types.Reservation
33-
for _, res := range c.Reservations {
34-
var reservation ec2types.Reservation
35-
for _, inst := range res.Instances {
36-
for _, id := range in.InstanceIds {
37-
if id == aws.ToString(inst.InstanceId) {
38-
reservation.Instances = append(reservation.Instances, inst)
39-
}
40-
}
41-
}
42-
if len(reservation.Instances) > 0 {
43-
reservations = append(reservations, reservation)
44-
}
45-
}
46-
return &ec2.DescribeInstancesOutput{
47-
Reservations: reservations,
48-
}, nil
49-
}
50-
51-
func newMockedEC2ProviderImpl() *ec2ProviderImpl {
52-
dnsCache := ec2PrivateDNSCache{
53-
cache: make(map[string]string),
54-
lock: sync.RWMutex{},
55-
}
56-
ec2Requests := ec2Requests{
57-
set: make(map[string]bool),
58-
lock: sync.RWMutex{},
59-
}
60-
return &ec2ProviderImpl{
61-
ec2: &mockEc2Client{},
62-
privateDNSCache: dnsCache,
63-
ec2Requests: ec2Requests,
64-
instanceIdsChannel: make(chan string, maxChannelSize),
65-
}
66-
67-
}
68-
6919
func TestGetPrivateDNSName(t *testing.T) {
7020
metrics.InitMetrics(prometheus.NewRegistry())
7121
ec2Provider := newMockedEC2ProviderImpl()
72-
ec2Provider.ec2 = &mockEc2Client{Reservations: prepareSingleInstanceOutput()}
22+
ec2Provider.ec2 = &MockEc2Client{Reservations: prepareSingleInstanceOutput()}
7323
go ec2Provider.StartEc2DescribeBatchProcessing(context.TODO())
7424
dns_name, err := ec2Provider.GetPrivateDNSName(context.TODO(), "ec2-1")
7525
if err != nil {
@@ -102,7 +52,7 @@ func TestGetPrivateDNSNameWithBatching(t *testing.T) {
10252
metrics.InitMetrics(prometheus.NewRegistry())
10353
ec2Provider := newMockedEC2ProviderImpl()
10454
reservations := prepare100InstanceOutput()
105-
ec2Provider.ec2 = &mockEc2Client{Reservations: reservations}
55+
ec2Provider.ec2 = &MockEc2Client{Reservations: reservations}
10656
go ec2Provider.StartEc2DescribeBatchProcessing(context.TODO())
10757
var wg sync.WaitGroup
10858
for i := 1; i < 101; i++ {

pkg/server/server.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import (
3030

3131
awsconfig "github.com/aws/aws-sdk-go-v2/config"
3232
"github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
33+
"github.com/aws/aws-sdk-go-v2/service/ec2"
3334
"sigs.k8s.io/aws-iam-authenticator/pkg/config"
3435
"sigs.k8s.io/aws-iam-authenticator/pkg/ec2provider"
3536
"sigs.k8s.io/aws-iam-authenticator/pkg/errutil"
@@ -215,9 +216,10 @@ func (c *Server) getHandler(ctx context.Context, backendMapper BackendMapper, ec
215216
} else {
216217
instanceRegion = instanceRegionOutput.Region
217218
}
219+
ec2Client := ec2.NewFromConfig(cfg)
218220

219221
h := &handler{
220-
verifier: token.NewVerifier(c.ClusterID, c.PartitionID, instanceRegion),
222+
verifier: token.NewVerifier(ctx, c.ClusterID, c.PartitionID, instanceRegion, ec2Client),
221223
ec2Provider: ec2provider.New(ctx, c.ServerEC2DescribeInstancesRoleARN, c.SourceARN, instanceRegion, ec2DescribeQps, ec2DescribeBurst),
222224
clusterID: c.ClusterID,
223225
backendMapper: backendMapper,

0 commit comments

Comments
 (0)