|
| 1 | +/* |
| 2 | +Copyright 2025 The Crossplane Authors. |
| 3 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +you may not use this file except in compliance with the License. |
| 5 | +You may obtain a copy of the License at |
| 6 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +Unless required by applicable law or agreed to in writing, software |
| 8 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | +See the License for the specific language governing permissions and |
| 11 | +limitations under the License. |
| 12 | +*/ |
| 13 | + |
| 14 | +// Package aws contains utilities for authenticating to EKS clusters. |
| 15 | +package aws |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "encoding/base64" |
| 20 | + "fmt" |
| 21 | + "net/http" |
| 22 | + "strings" |
| 23 | + |
| 24 | + "github.com/aws/aws-sdk-go-v2/aws/arn" |
| 25 | + "github.com/aws/aws-sdk-go-v2/config" |
| 26 | + "github.com/aws/aws-sdk-go-v2/service/sts" |
| 27 | + smithyhttp "github.com/aws/smithy-go/transport/http" |
| 28 | + "github.com/pkg/errors" |
| 29 | + "k8s.io/client-go/rest" |
| 30 | +) |
| 31 | + |
| 32 | +const ( |
| 33 | + // clusterIDHeader is the header name for the cluster ID |
| 34 | + clusterIDHeader = "x-k8s-aws-id" |
| 35 | + // expireHeader is the header name for the expiration time |
| 36 | + expireHeader = "X-Amz-Expires" |
| 37 | + // tokenPrefix is the prefix for the EKS token |
| 38 | + tokenPrefix = "k8s-aws-v1." |
| 39 | + // tokenExpiration is the default expiration time for EKS tokens (15 minutes) |
| 40 | + tokenExpiration = 900 |
| 41 | +) |
| 42 | + |
| 43 | +// WrapRESTConfig configures the supplied REST config to use bearer tokens |
| 44 | +// fetched using AWS credentials chain for EKS authentication. |
| 45 | +// This uses AWS Web Identity / IRSA to assume a role that has access to the EKS cluster. |
| 46 | +// clusterNameFromKubeconfig is the cluster name from the kubeconfig (can be an ARN or plain name). |
| 47 | +func WrapRESTConfig(ctx context.Context, rc *rest.Config, clusterNameFromKubeconfig string) error { |
| 48 | + // Extract cluster name from ARN if needed |
| 49 | + clusterName, err := extractClusterNameFromARN(clusterNameFromKubeconfig) |
| 50 | + if err != nil { |
| 51 | + return errors.Wrap(err, "failed to extract cluster name from kubeconfig") |
| 52 | + } |
| 53 | + |
| 54 | + cfg, err := config.LoadDefaultConfig(ctx) |
| 55 | + if err != nil { |
| 56 | + return errors.Wrap(err, "failed to load AWS config using default credentials chain") |
| 57 | + } |
| 58 | + |
| 59 | + // Create STS client with the credentials (which may already be assumed role credentials) |
| 60 | + stsClient := sts.NewFromConfig(cfg) |
| 61 | + |
| 62 | + // Create a token source that generates EKS tokens on demand |
| 63 | + tokenSource := &eksTokenSource{ |
| 64 | + ctx: ctx, |
| 65 | + stsClient: stsClient, |
| 66 | + clusterID: clusterName, |
| 67 | + } |
| 68 | + |
| 69 | + // Wrap the transport to inject the bearer token |
| 70 | + rc.Wrap(func(rt http.RoundTripper) http.RoundTripper { |
| 71 | + return &bearerAuthRoundTripper{ |
| 72 | + source: tokenSource, |
| 73 | + rt: rt, |
| 74 | + } |
| 75 | + }) |
| 76 | + |
| 77 | + // Clear any exec provider since we're handling auth ourselves |
| 78 | + rc.ExecProvider = nil |
| 79 | + |
| 80 | + return nil |
| 81 | +} |
| 82 | + |
| 83 | +// extractClusterNameFromARN extracts the cluster name from an EKS cluster ARN |
| 84 | +// ARN format: arn:aws:eks:region:account:cluster/cluster-name |
| 85 | +func extractClusterNameFromARN(arnString string) (string, error) { |
| 86 | + // Check if it's an ARN using AWS SDK |
| 87 | + if !arn.IsARN(arnString) { |
| 88 | + // Not an ARN, might be just the cluster name |
| 89 | + return arnString, nil |
| 90 | + } |
| 91 | + |
| 92 | + // Parse ARN using AWS SDK |
| 93 | + parsedARN, err := arn.Parse(arnString) |
| 94 | + if err != nil { |
| 95 | + return "", errors.Wrap(err, "failed to parse ARN") |
| 96 | + } |
| 97 | + |
| 98 | + // EKS cluster ARNs have Resource in format "cluster/cluster-name" |
| 99 | + // Split by '/' to get the cluster name |
| 100 | + parts := strings.Split(parsedARN.Resource, "/") |
| 101 | + if len(parts) < 2 { |
| 102 | + return "", fmt.Errorf("invalid EKS cluster ARN resource format: %s", parsedARN.Resource) |
| 103 | + } |
| 104 | + |
| 105 | + return parts[len(parts)-1], nil |
| 106 | +} |
| 107 | + |
| 108 | +// eksTokenSource generates EKS authentication tokens using AWS STS |
| 109 | +type eksTokenSource struct { |
| 110 | + ctx context.Context |
| 111 | + stsClient *sts.Client |
| 112 | + clusterID string |
| 113 | +} |
| 114 | + |
| 115 | +// Token generates an EKS authentication token |
| 116 | +// This replicates the behavior of `aws eks get-token` command |
| 117 | +// The STS client uses credentials from the AWS default credentials chain, |
| 118 | +// which includes assumed role credentials from Web Identity/IRSA |
| 119 | +func (s *eksTokenSource) Token() (string, error) { |
| 120 | + // Create a presigned request for GetCallerIdentity |
| 121 | + // This is what EKS uses for authentication |
| 122 | + // Default expiration is 15 minutes (900 seconds) which is what EKS expects |
| 123 | + presigner := sts.NewPresignClient(s.stsClient) |
| 124 | + |
| 125 | + // Create presigned request with cluster ID and expiration headers |
| 126 | + // This matches the provider-aws implementation exactly |
| 127 | + presignedReq, err := presigner.PresignGetCallerIdentity(s.ctx, |
| 128 | + &sts.GetCallerIdentityInput{}, |
| 129 | + func(po *sts.PresignOptions) { |
| 130 | + po.ClientOptions = []func(*sts.Options){ |
| 131 | + sts.WithAPIOptions( |
| 132 | + smithyhttp.AddHeaderValue(clusterIDHeader, s.clusterID), |
| 133 | + smithyhttp.AddHeaderValue(expireHeader, fmt.Sprintf("%d", tokenExpiration)), |
| 134 | + ), |
| 135 | + } |
| 136 | + }) |
| 137 | + if err != nil { |
| 138 | + return "", errors.Wrap(err, "failed to presign GetCallerIdentity request") |
| 139 | + } |
| 140 | + |
| 141 | + // Encode the presigned URL as a base64 token with the EKS prefix |
| 142 | + token := tokenPrefix + base64.RawURLEncoding.EncodeToString([]byte(presignedReq.URL)) |
| 143 | + |
| 144 | + return token, nil |
| 145 | +} |
| 146 | + |
| 147 | +// bearerAuthRoundTripper injects a bearer token into HTTP requests |
| 148 | +type bearerAuthRoundTripper struct { |
| 149 | + source *eksTokenSource |
| 150 | + rt http.RoundTripper |
| 151 | +} |
| 152 | + |
| 153 | +// RoundTrip implements http.RoundTripper |
| 154 | +func (b *bearerAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { |
| 155 | + token, err := b.source.Token() |
| 156 | + if err != nil { |
| 157 | + return nil, errors.Wrap(err, "failed to get EKS token") |
| 158 | + } |
| 159 | + |
| 160 | + // Clone the request and add the bearer token |
| 161 | + reqCopy := req.Clone(req.Context()) |
| 162 | + reqCopy.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) |
| 163 | + |
| 164 | + return b.rt.RoundTrip(reqCopy) |
| 165 | +} |
0 commit comments