Skip to content

Commit f80e105

Browse files
committed
updated verification to aws sdk go v2
1 parent 604188f commit f80e105

File tree

18 files changed

+312
-225
lines changed

18 files changed

+312
-225
lines changed

cmd/aws-iam-authenticator/root.go

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

26+
"sigs.k8s.io/aws-iam-authenticator/pkg/arn"
2527
"sigs.k8s.io/aws-iam-authenticator/pkg/config"
2628
"sigs.k8s.io/aws-iam-authenticator/pkg/mapper"
2729

28-
"github.com/aws/aws-sdk-go/aws/endpoints"
2930
"github.com/sirupsen/logrus"
3031
"github.com/spf13/cobra"
3132
"github.com/spf13/viper"
@@ -157,14 +158,8 @@ func getConfig() (config.Config, error) {
157158
return cfg, errors.New("cluster ID cannot be empty")
158159
}
159160

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 {
167-
return cfg, errors.New("Invalid partition")
161+
if !slices.Contains(arn.PartitionKeys, cfg.PartitionID) {
162+
return cfg, errors.New("Invalid partition when getting config")
168163
}
169164

170165
// DynamicFile BackendMode and DynamicFilePath are mutually inclusive.

cmd/aws-iam-authenticator/server.go

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,11 @@ import (
2525

2626
"k8s.io/sample-controller/pkg/signals"
2727
"sigs.k8s.io/aws-iam-authenticator/pkg"
28+
"sigs.k8s.io/aws-iam-authenticator/pkg/arn"
2829
"sigs.k8s.io/aws-iam-authenticator/pkg/mapper"
2930
"sigs.k8s.io/aws-iam-authenticator/pkg/metrics"
3031
"sigs.k8s.io/aws-iam-authenticator/pkg/server"
3132

32-
"github.com/aws/aws-sdk-go/aws/endpoints"
3333
"github.com/prometheus/client_golang/prometheus"
3434
"github.com/sirupsen/logrus"
3535
"github.com/spf13/cobra"
@@ -67,14 +67,8 @@ var serverCmd = &cobra.Command{
6767
}
6868

6969
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))
70+
serverCmd.Flags().String("partition", "aws",
71+
fmt.Sprintf("The AWS partition. Must be one of: %v", arn.PartitionKeys))
7872
viper.BindPFlag("server.partition", serverCmd.Flags().Lookup("partition"))
7973

8074
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.Fprintf(os.Stderr, "[Warn] Unable to create config for metadata client, err: %v", err)
92+
panic(err)
93+
}
94+
95+
imdsClient := imds.NewFromConfig(cfg)
96+
getRegionOutput, err := imdsClient.GetRegion(ctx, &imds.GetRegionInput{})
97+
if err != nil {
98+
fmt.Fprintf(os.Stderr, "[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=

hack/dev/describe-regions-policy.json

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"Version": "2012-10-17",
3+
"Statement": [
4+
{
5+
"Effect": "Allow",
6+
"Action": "ec2:DescribeRegions",
7+
"Resource": "*"
8+
}
9+
]
10+
}

hack/e2e/aws.sh

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@ function create_role() {
2828
--assume-role-policy-document "$POLICY" \
2929
--output text \
3030
--query 'Role.Arn')
31+
32+
## attach describe-regions policy to the role
33+
aws iam put-role-policy \
34+
--region "${REGION}" \
35+
--role-name "$ROLE_NAME" \
36+
--policy-name "DescribeRegionsPolicy" \
37+
--policy-document "file://${BASE_DIR}/../dev/describe-regions-policy.json"
3138
else
3239
set -e
3340
loudecho "${ROLE_NAME} role already exists" >&2

hack/e2e/run.sh

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,18 @@ if [[ "${CLEAN}" == true ]]; then
258258
"${CLUSTER_NAME}" \
259259
"${KOPS_STATE_FILE}"
260260

261+
aws iam list-role-policies --role-name ${ADMIN_ROLE_NAME} --query "PolicyNames[]" --output text |
262+
while read policy_name; do
263+
echo "Deleting inline policy: $policy_name"
264+
aws iam delete-role-policy --role-name ${ADMIN_ROLE_NAME} --policy-name "$policy_name"
265+
done
261266
aws iam delete-role --role-name "${ADMIN_ROLE_NAME}" --region ${REGION}
267+
268+
aws iam list-role-policies --role-name ${USER_ROLE_NAME} --query "PolicyNames[]" --output text |
269+
while read policy_name; do
270+
echo "Deleting inline policy: $policy_name"
271+
aws iam delete-role-policy --role-name ${USER_ROLE_NAME} --policy-name "$policy_name"
272+
done
262273
aws iam delete-role --role-name "${USER_ROLE_NAME}" --region ${REGION}
263274
else
264275
loudecho "Not cleaning"

hack/lib/dev-env.sh

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,11 @@ authenticator_backend_mode_dest_file="${authenticator_dynamicfile_dest_path}/bac
7171
authenticator_config_dest_dir="/etc/authenticator"
7272
authenticator_export_dest_dir="/var/authenticator/export"
7373
authenticator_state_dest_dir="/var/authenticator/state"
74+
policies_template="${REPO_ROOT}/hack/dev/policies.template"
75+
policies_json="${OUTPUT}/dev/authenticator/policies.json"
7476
apiserver_config_dest_dir="/etc/kubernetes/authenticator"
77+
describe_regions_policy_json="${REPO_ROOT}/hack/dev/describe-regions-policy.json"
78+
7579
# Kubeconfig used when authenticator loads its mapping configuration from the API server
7680
authenticator_kubeconfig="${authenticator_config_dest_dir}/authenticator-kubeconfig.yaml"
7781
# Kubeconfig passed to the apiserver so it can kind its authentication webhook
@@ -86,6 +90,10 @@ kubectl_kubeconfig="${client_dir}/kubeconfig.yaml"
8690
# Admin kubeconfig generated by kind
8791
kind_kubeconfig="${client_dir}/kind-kubeconfig.yaml"
8892

93+
AWS_ACCOUNT=$(aws sts get-caller-identity --query "Account" --output text)
94+
DESCRIBEREGIONS_ROLE_NAME="authenticator-describeregions-role"
95+
DESCRIBEREGIONS_POLICY_NAME="DescribeRegionsPolicy"
96+
8997
function install_kind() {
9098
if ! [[ -f "${KIND_BIN}" ]]; then
9199
if [[ "$OSTYPE" == "darwin"* ]]; then
@@ -190,6 +198,33 @@ function start_authenticator_with_dynamicfile() {
190198
chmod -R 777 "${authenticator_dynamicfile_host_path}"
191199
chmod 777 "${authenticator_access_entry_host_file}"
192200

201+
# Create a role that can call ec2:DescribeRegions to run the tests
202+
if ! RoleOutput=$(aws iam get-role --role-name "${DESCRIBEREGIONS_ROLE_NAME}" 2>&1); then
203+
sed -e "s|{{AWS_ACCOUNT}}|${AWS_ACCOUNT}|g" \
204+
"${policies_template}" > "${policies_json}"
205+
sleep 2
206+
aws iam create-role --role-name ${DESCRIBEREGIONS_ROLE_NAME} --assume-role-policy-document file://${policies_json} 1>/dev/null
207+
echo "Waiting for IAM propagation of ${DESCRIBEREGIONS_ROLE_NAME}..."
208+
sleep 10
209+
210+
aws iam put-role-policy \
211+
--role-name $DESCRIBEREGIONS_ROLE_NAME \
212+
--policy-name $DESCRIBEREGIONS_POLICY_NAME \
213+
--policy-document file://$describe_regions_policy_json
214+
sleep 2
215+
fi
216+
217+
# Assume the role and get its credentials
218+
DESCRIBEREGIONS_ROLE_ARN="arn:aws:iam::$(aws sts get-caller-identity --query Account --output text):role/${DESCRIBEREGIONS_ROLE_NAME}"
219+
ASSUME_OUTPUT=$(aws sts assume-role \
220+
--role-arn "$DESCRIBEREGIONS_ROLE_ARN" \
221+
--role-session-name "DescribeRegionsSession")
222+
export AWS_ACCESS_KEY_ID=$(echo $ASSUME_OUTPUT | jq -r .Credentials.AccessKeyId)
223+
export AWS_SECRET_ACCESS_KEY=$(echo $ASSUME_OUTPUT | jq -r .Credentials.SecretAccessKey)
224+
export AWS_SESSION_TOKEN=$(echo $ASSUME_OUTPUT | jq -r .Credentials.SessionToken)
225+
226+
echo "Successfully assumed role: $DESCRIBEREGIONS_ROLE_NAME"
227+
193228
docker run \
194229
--detach \
195230
--ip "${AUTHENTICATOR_IP}" \
@@ -202,6 +237,9 @@ function start_authenticator_with_dynamicfile() {
202237
--publish ${authenticator_healthz_port}:${authenticator_healthz_port} \
203238
--publish ${AUTHENTICATOR_PORT}:${AUTHENTICATOR_PORT} \
204239
--env AWS_REGION="us-west-2" \
240+
--env AWS_ACCESS_KEY_ID \
241+
--env AWS_SECRET_ACCESS_KEY \
242+
--env AWS_SESSION_TOKEN \
205243
"${AUTHENTICATOR_IMAGE}" \
206244
server \
207245
--config "${authenticator_config_dest_dir}/authenticator_dynamicfile_mode.yaml"

hack/stop-dev-env.sh

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ set -o nounset
3434
# between them is over localhost and fixed port.
3535

3636
REPO_ROOT="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )/.." &> /dev/null && pwd )"
37+
DESCRIBEREGIONS_ROLE_NAME="authenticator-describeregions-role"
3738

3839
source "${REPO_ROOT}/hack/lib/dev-env.sh"
3940

@@ -47,3 +48,13 @@ sleep 5
4748

4849
# Tear down network
4950
delete_network
51+
52+
# Delete role used to run tests
53+
# List inline policies
54+
aws iam list-role-policies --role-name ${DESCRIBEREGIONS_ROLE_NAME} --query "PolicyNames[]" --output text |
55+
while read policy_name; do
56+
echo "Deleting inline policy: $policy_name"
57+
aws iam delete-role-policy --role-name ${DESCRIBEREGIONS_ROLE_NAME} --policy-name "$policy_name"
58+
done
59+
60+
aws iam delete-role --role-name ${DESCRIBEREGIONS_ROLE_NAME}

0 commit comments

Comments
 (0)