Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: add aws-iam (#16612)
Vincent Huangf13681b80384
diff --git a/backend/plugin/db/elasticsearch/elasticsearch.go b/backend/plugin/db/elasticsearch/elasticsearch.goindex 6114d5df92..3f90f69760 100644--- a/backend/plugin/db/elasticsearch/elasticsearch.go+++ b/backend/plugin/db/elasticsearch/elasticsearch.go@@ -3,10 +3,12 @@ package elasticsearchimport ("bytes""context"+ "crypto/sha256""crypto/tls""crypto/x509""database/sql""encoding/base64"+ "encoding/hex""encoding/json""fmt""io"@@ -15,6 +17,9 @@ import ("strings""time"+ "github.com/aws/aws-sdk-go-v2/aws"+ v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4" //nolint:revive+ awsconfig "github.com/aws/aws-sdk-go-v2/config""github.com/elastic/go-elasticsearch/v7""github.com/pkg/errors""google.golang.org/protobuf/types/known/durationpb"@@ -56,7 +61,10 @@ func (client *BasicAuthClient) Do(method string, route []byte, queryString []bytreturn nil, errors.Wrapf(err, "failed to init a HTTP request")}- req.Header.Add("Authorization", client.basicAuthString)+ // Only add basic auth header if it exists (not for AWS IAM auth)+ if client.basicAuthString != "" {+ req.Header.Add("Authorization", client.basicAuthString)+ }req.Header.Set("Content-Type", "application/json")return client.httpClient.Do(req)@@ -74,7 +82,49 @@ func (scheduler *AddressScheduler) GetNewAddress() string {return address}-func (*Driver) Open(_ context.Context, _ storepb.Engine, config db.ConnectionConfig) (db.Driver, error) {+// sigV4RoundTripper implements http.RoundTripper with AWS SigV4 signing+type sigV4RoundTripper struct {+ signer *v4.Signer+ credentials aws.CredentialsProvider+ region string+ service string+ wrapped http.RoundTripper+}++func (rt *sigV4RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {+ // Clone request to avoid mutating the original+ signedReq := req.Clone(req.Context())++ // Read and hash the body+ var bodyBytes []byte+ if req.Body != nil {+ bodyBytes, _ = io.ReadAll(req.Body)+ req.Body = io.NopCloser(bytes.NewReader(bodyBytes))+ signedReq.Body = io.NopCloser(bytes.NewReader(bodyBytes))+ }++ // Calculate payload hash+ h := sha256.New()+ h.Write(bodyBytes)+ payloadHash := hex.EncodeToString(h.Sum(nil))++ // Get credentials+ creds, err := rt.credentials.Retrieve(req.Context())+ if err != nil {+ return nil, errors.Wrap(err, "failed to retrieve AWS credentials")+ }++ // Sign the request+ err = rt.signer.SignHTTP(req.Context(), creds, signedReq,+ payloadHash, rt.service, rt.region, time.Now())+ if err != nil {+ return nil, errors.Wrap(err, "failed to sign request")+ }++ return rt.wrapped.RoundTrip(signedReq)+}++func (*Driver) Open(ctx context.Context, _ storepb.Engine, config db.ConnectionConfig) (db.Driver, error) {address := fmt.Sprintf("%s:%s", config.DataSource.Host, config.DataSource.Port)u, err := url.Parse(address)if err != nil || u.Host == "" {@@ -89,6 +139,16 @@ func (*Driver) Open(_ context.Context, _ storepb.Engine, config db.ConnectionCon}}+ // Check if AWS IAM authentication is requested+ if config.DataSource.GetAuthenticationType() == storepb.DataSource_AWS_RDS_IAM {+ return openWithAWSAuth(ctx, config, address)+ }++ // Existing basic auth implementation+ return openWithBasicAuth(ctx, config, address)+}++func openWithBasicAuth(_ context.Context, config db.ConnectionConfig, address string) (db.Driver, error) {esConfig := elasticsearch.Config{Username: config.DataSource.Username,Password: config.Password,@@ -152,12 +212,90 @@ func (*Driver) Open(_ context.Context, _ storepb.Engine, config db.ConnectionCon}, nil}+func openWithAWSAuth(ctx context.Context, config db.ConnectionConfig, address string) (db.Driver, error) {+ // Validate AWS-specific requirements+ if config.DataSource.GetRegion() == "" {+ return nil, errors.New("region is required for AWS IAM authentication")+ }++ // Load AWS configuration+ awsCfg, err := awsconfig.LoadDefaultConfig(ctx,+ awsconfig.WithRegion(config.DataSource.GetRegion()),+ )+ if err != nil {+ return nil, errors.Wrap(err, "failed to load AWS config")+ }++ // Create base transport with TLS config+ baseTransport := &http.Transport{+ MaxIdleConnsPerHost: 10,+ ResponseHeaderTimeout: time.Second,+ TLSClientConfig: &tls.Config{+ MinVersion: tls.VersionTLS12,+ },+ }++ // Add custom CA if provided+ if config.DataSource.GetSslCert() != "" {+ certPool := x509.NewCertPool()+ if ok := certPool.AppendCertsFromPEM([]byte(config.DataSource.GetSslCert())); !ok {+ return nil, errors.New("cannot add CA cert to pool")+ }+ baseTransport.TLSClientConfig.RootCAs = certPool+ }++ // Create SigV4 transport+ sigV4Transport := &sigV4RoundTripper{+ signer: v4.NewSigner(),+ credentials: awsCfg.Credentials,+ region: config.DataSource.GetRegion(),+ service: "es", // AWS OpenSearch uses "es" service name+ wrapped: baseTransport,+ }++ // Create HTTP client with SigV4 transport+ httpClient := &http.Client{+ Transport: sigV4Transport,+ }++ // Create basic auth client that will use the SigV4 HTTP client+ // Note: basicAuthString will be empty but the structure is reused+ return &Driver{+ typedClient: nil, // Will use basicAuthClient for AWS IAM mode+ basicAuthClient: &BasicAuthClient{+ httpClient: httpClient,+ addrScheduler: &AddressScheduler{+ addresses: []string{address},+ count: 0,+ },+ basicAuthString: "", // No basic auth header needed for AWS IAM+ },+ config: config,+ }, nil+}+// ElasticSearch doesn't keep a live connection as it uses stateless HTTP.func (*Driver) Close(_ context.Context) error {return nil}func (d *Driver) Ping(_ context.Context) error {+ // For AWS IAM mode, use basicAuthClient+ if d.typedClient == nil && d.basicAuthClient != nil {+ resp, err := d.basicAuthClient.Do("GET", []byte("/"), nil)+ if err != nil {+ return errors.Wrapf(err, "failed to ping db")+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ body, _ := io.ReadAll(resp.Body)+ return errors.Errorf("ping failed with status %d: %s", resp.StatusCode, body)+ }+ return nil+ }++ // Existing typed client logicif _, err := d.typedClient.Ping(); err != nil {return errors.Wrapf(err, "failed to ping db")}diff --git a/backend/plugin/db/elasticsearch/elasticsearch_test.go b/backend/plugin/db/elasticsearch/elasticsearch_test.gonew file mode 100644index 0000000000..27c80a46ae--- /dev/null+++ b/backend/plugin/db/elasticsearch/elasticsearch_test.go@@ -0,0 +1,58 @@+package elasticsearch++import (+ "context"+ "testing"++ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/backend/plugin/db"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++func TestOpenWithAWSAuth(t *testing.T) {+ tests := []struct {+ name string+ config db.ConnectionConfig+ wantErr string+ }{+ {+ name: "missing region",+ config: db.ConnectionConfig{+ DataSource: &storepb.DataSource{+ Host: "search-test.us-east-1.es.amazonaws.com",+ Port: "443",+ AuthenticationType: storepb.DataSource_AWS_RDS_IAM,+ },+ },+ wantErr: "region is required for AWS IAM authentication",+ },+ {+ name: "basic auth still works",+ config: db.ConnectionConfig{+ DataSource: &storepb.DataSource{+ Host: "localhost",+ Port: "9200",+ Username: "elastic",+ AuthenticationType: storepb.DataSource_PASSWORD,+ },+ Password: "password123",+ },+ // This will fail to connect but should not error during Open+ wantErr: "",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ driver := &Driver{}+ _, err := driver.Open(context.Background(), storepb.Engine_ELASTICSEARCH, tt.config)+ if tt.wantErr != "" {+ require.Error(t, err)+ require.Contains(t, err.Error(), tt.wantErr)+ } else {+ require.NoError(t, err)+ }+ })+ }+}