From a5c8f395a01292c00bc3eed53a3a01a0cc50c2f1 Mon Sep 17 00:00:00 2001 From: Sichao Wang Date: Fri, 13 Sep 2024 10:57:13 +0000 Subject: [PATCH] Support Certs via Environement Variable --- kubetest2/internal/awssdk/config.go | 35 +++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/kubetest2/internal/awssdk/config.go b/kubetest2/internal/awssdk/config.go index fe71d0a95..c71d70c6b 100644 --- a/kubetest2/internal/awssdk/config.go +++ b/kubetest2/internal/awssdk/config.go @@ -2,18 +2,49 @@ package awssdk import ( "context" + "crypto/tls" + "crypto/x509" + "net/http" + "os" + + "k8s.io/klog" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" - "k8s.io/klog/v2" ) // NewConfig returns an AWS SDK config // It will panic if the cnfig cannot be created func NewConfig() aws.Config { - c, err := config.LoadDefaultConfig(context.TODO()) + c, err := config.LoadDefaultConfig(context.TODO(), withCertsEnv()) if err != nil { klog.Fatalf("failed to create AWS SDK config: %v", err) } return c } + +func withCertsEnv() func(*config.LoadOptions) error { + return func(lo *config.LoadOptions) error { + certs := os.Getenv("CERTS_CONTENT") + if certs != "" { + klog.Infof("Loading certificates from CERTS_CONTENT") + lo.HTTPClient = newHTTPClientWithCerts([]byte(certs)) + } else { + klog.Warningf("CERTS_CONTENT environment variable is not set or empty") + } + return nil + } +} + +func newHTTPClientWithCerts(certData []byte) *http.Client { + pool := x509.NewCertPool() + if ok := pool.AppendCertsFromPEM(certData); !ok { + klog.Fatalf("Failed to append provided certificates") + } + transport := &http.Transport{ + TLSClientConfig: &tls.Config{ + RootCAs: pool, + }, + } + return &http.Client{Transport: transport} +}