Skip to content

Instantly share code, notes, and snippets.

@nickzelei
Created February 14, 2023 03:34
Show Gist options
  • Save nickzelei/338a32de48913cf49ae44ace245eef33 to your computer and use it in GitHub Desktop.
Save nickzelei/338a32de48913cf49ae44ace245eef33 to your computer and use it in GitHub Desktop.
STS V2 Presign K8s Token
package main
import (
"context"
"encoding/base64"
"fmt"
"net/http"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/sts"
)
const (
k8sHeader = "x-k8s-aws-id"
tokenPrefix = "k8s-aws-v1."
)
func main() {
ctx := context.Background()
clusterName := "<YOUR_CLUSTER_HERE>"
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
panic(err)
}
stsclient := sts.NewFromConfig(cfg)
presignclient := sts.NewPresignClient(stsclient)
out, err := presignclient.PresignGetCallerIdentity(ctx, &sts.GetCallerIdentityInput{}, func(opt *sts.PresignOptions) {
opt.Presigner = newCustomHTTPPresignerV4(opt.Presigner, map[string]string{
k8sHeader: clusterName,
"X-Amz-Expires": "60",
})
})
if err != nil {
panic(err)
}
token := fmt.Sprintf("%s%s", tokenPrefix, base64.RawStdEncoding.EncodeToString([]byte(out.URL)))
fmt.Println(token)
}
type customHTTPPresignerV4 struct {
client sts.HTTPPresignerV4
headers map[string]string
}
func newCustomHTTPPresignerV4(client sts.HTTPPresignerV4, headers map[string]string) sts.HTTPPresignerV4 {
return &customHTTPPresignerV4{
client: client,
headers: headers,
}
}
func (p *customHTTPPresignerV4) PresignHTTP(
ctx context.Context, credentials aws.Credentials, r *http.Request,
payloadHash string, service string, region string, signingTime time.Time,
optFns ...func(*v4.SignerOptions),
) (url string, signedHeader http.Header, err error) {
for key, val := range p.headers {
r.Header.Add(key, val)
}
return p.client.PresignHTTP(ctx, credentials, r, payloadHash, service, region, signingTime, optFns...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment