Created
July 14, 2023 05:57
-
-
Save jenskueper/e03fee5a98472980ff1fdc55a69093d5 to your computer and use it in GitHub Desktop.
Golang Opensearch / Elasticsearch sigv4 signer AWS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package signer | |
import ( | |
"crypto/sha256" | |
"fmt" | |
"io" | |
"net/http" | |
"time" | |
"github.com/aws/aws-sdk-go-v2/aws" | |
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4" | |
) | |
// V4Signer is a http.RoundTripper implementation to sign requests according to | |
// https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html | |
type V4Signer struct { | |
RoundTripper http.RoundTripper | |
AwsCfg aws.Config | |
Region string | |
} | |
func (s *V4Signer) RoundTrip(req *http.Request) (*http.Response, error) { | |
signer := v4.NewSigner() | |
cred, err := s.AwsCfg.Credentials.Retrieve(req.Context()) | |
if err != nil { | |
return nil, fmt.Errorf("retrieving credentials: %w", err) | |
} | |
h := sha256.New() | |
if _, err = io.Copy(h, req.Body); err != nil { | |
return nil, fmt.Errorf("calculating hash: %w", err) | |
} | |
err = signer.SignHTTP( | |
req.Context(), | |
cred, | |
req, | |
fmt.Sprintf("%x", h.Sum(nil)), | |
"es", | |
s.Region, | |
time.Now()) | |
if err != nil { | |
return nil, fmt.Errorf("signing request: %w", err) | |
} | |
return s.RoundTripper.RoundTrip(req) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment