Debian Codegraph @

mysql/awsmysql/awsmysql.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
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 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package awsmysql provides connections to AWS RDS MySQL instances.
16 //
17 // # URLs
18 //
19 // For mysql.Open, awsmysql registers for the scheme "awsmysql".
20 // The default URL opener will create a connection using the default
21 // credentials from the environment, as described in
22 // https://docs.aws.amazon.com/sdk-for-go/api/aws/session/.
23 // To customize the URL opener, or for more details on the URL format,
24 // see URLOpener.
25 //
26 // See https://gocloud.dev/concepts/urls/ for background information.
27 package awsmysql // import "gocloud.dev/mysql/awsmysql"
28
29 import (
30 "context"
31 "crypto/tls"
32 "database/sql"
33 "database/sql/driver"
34 "fmt"
35 "net/http"
36 "net/url"
37
38 "github.com/XSAM/otelsql"
39 "github.com/aws/aws-sdk-go-v2/aws"
40 "github.com/aws/aws-sdk-go-v2/config"
41 "github.com/aws/aws-sdk-go-v2/credentials/stscreds"
42 "github.com/aws/aws-sdk-go-v2/feature/rds/auth"
43 "github.com/aws/aws-sdk-go-v2/service/sts"
44 "github.com/go-sql-driver/mysql"
45 "github.com/google/wire"
46 "gocloud.dev/aws/rds"
47 gcmysql "gocloud.dev/mysql"
48 )
49
50 // Set is a Wire provider set that provides a *sql.DB given
51 // *Params and an HTTP client.
52 var Set = wire.NewSet(
53 wire.Struct(new(URLOpener), "CertSource", "HTTPClient"),
54 rds.CertFetcherSet,
55 )
56
57 // URLOpener opens RDS MySQL URLs
58 // like "awsmysql://user:[email protected]:3306/mydb".
59 //
60 // To use IAM authentication, omit the password:
61 //
62 // awsmysql://[email protected]:3306/mydb
63 //
64 // To specify an AWS profile or assume a role, add the following query parameters:
65 //
66 // - aws_profile: the AWS shared config profile to use
67 // - aws_role_arn: the ARN of the role to assume
68 type URLOpener struct {
69 // HTTPClient is the HTTP client used to fetch RDS certificates,
70 // and IAM authentication tokens.
71 HTTPClient *http.Client
72 // CertSource specifies how the opener will obtain the RDS Certificate
73 // Authority. If nil, it will use the default *rds.CertFetcher.
74 CertSource rds.CertPoolProvider
75 // TraceOpts contains options for OpenTelemetry.
76 TraceOpts []otelsql.Option
77 }
78
79 // Scheme is the URL scheme awsmysql registers its URLOpener under on
80 // mysql.DefaultMux.
81 const Scheme = "awsmysql"
82
83 func init() {
84 gcmysql.DefaultURLMux().RegisterMySQL(Scheme, &URLOpener{})
85 }
86
87 // OpenMySQLURL opens a new RDS database connection wrapped with OpenTelemetry instrumentation.
88 func (uo *URLOpener) OpenMySQLURL(ctx context.Context, u *url.URL) (*sql.DB, error) {
89 source := uo.CertSource
90 if source == nil {
91 source = &rds.CertFetcher{Client: uo.HTTPClient}
92 }
93 if u.Host == "" {
94 return nil, fmt.Errorf("open OpenMySQLURL: empty endpoint")
95 }
96 // If no password provided, assume it's AWS IAM authentication.
97 // awsmysql://iam-user@host:port/dbname
98 var iam func(context.Context) (string, error)
99 if _, ok := u.User.Password(); !ok {
100 var (
101 q = u.Query()
102 profile = q.Get("aws_profile")
103 )
104 q.Del("aws_profile")
105 cfg, err := config.LoadDefaultConfig(ctx,
106 config.WithHTTPClient(uo.HTTPClient), // Ignored if nil.
107 config.WithSharedConfigProfile(profile)) // Ignored if empty.
108 if err != nil {
109 return nil, fmt.Errorf("open OpenMySQLURL: load AWS config: %v", err)
110 }
111 creds := cfg.Credentials
112 if roleARN := q.Get("aws_role_arn"); roleARN != "" {
113 // If a RoleARN is specified, replace the credentials with AssumeRole provider.
114 creds = stscreds.NewAssumeRoleProvider(sts.NewFromConfig(cfg), roleARN)
115 q.Del("aws_role_arn")
116 }
117 u.RawQuery = q.Encode()
118 creds = aws.NewCredentialsCache(creds)
119 iam = func(ctx context.Context) (string, error) {
120 // BuildAuthToken is local-operation
121 // and does not make network calls.
122 // The credentials provider may make network calls,
123 // but we are wrapped it with caching.
124 return auth.BuildAuthToken(ctx, u.Host, cfg.Region, u.User.Username(), creds)
125 }
126 }
127 cfg, err := gcmysql.ConfigFromURL(u)
128 if err != nil {
129 return nil, err
130 }
131 c := &connector{
132 cfg: cfg,
133 iam: iam,
134 provider: source,
135
136 sem: make(chan struct{}, 1),
137 ready: make(chan struct{}),
138 }
139 c.sem <- struct{}{}
140 return otelsql.OpenDB(c, uo.TraceOpts...), nil
141 }
142
143 type connector struct {
144 sem chan struct{} // receive to acquire, send to release
145 provider CertPoolProvider
146
147 ready chan struct{} // closed after resolving dsn
148 cfg *mysql.Config
149 iam func(context.Context) (string, error)
150 }
151
152 func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
153 select {
154 case <-c.sem:
155 certPool, err := c.provider.RDSCertPool(ctx)
156 if err != nil {
157 c.sem <- struct{}{} // release
158 return nil, fmt.Errorf("connect RDS: %v", err)
159 }
160 c.cfg.TLS = &tls.Config{RootCAs: certPool}
161 close(c.ready)
162 // Don't release sem: make it block forever, so this case won't be run again.
163 case <-c.ready:
164 // Already succeeded.
165 case <-ctx.Done():
166 return nil, fmt.Errorf("connect RDS: waiting for certificates: %v", ctx.Err())
167 }
168 cfg := c.cfg.Clone()
169 if c.iam != nil {
170 var err error
171 if cfg.Passwd, err = c.iam(ctx); err != nil {
172 return nil, fmt.Errorf("connect RDS: refresh auth token: %v", err)
173 }
174 }
175 inner, err := mysql.NewConnector(cfg)
176 if err != nil {
177 return nil, fmt.Errorf("connect RDS: create connector: %v", err)
178 }
179 return inner.Connect(ctx)
180 }
181
182 func (c *connector) Driver() driver.Driver {
183 return mysql.MySQLDriver{}
184 }
185
186 // A CertPoolProvider obtains a certificate pool that contains the RDS CA certificate.
187 type CertPoolProvider = rds.CertPoolProvider
188
189 // CertFetcher pulls the RDS CA certificates from Amazon's servers. The zero
190 // value will fetch certificates using the default HTTP client.
191 type CertFetcher = rds.CertFetcher