Repository navigation
Expand file tree
/
Copy pathdatabase.go
More file actions
305 lines (277 loc) · 12.4 KB
/
Copy pathdatabase.go
File metadata and controls
305 lines (277 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package pluginsdk
import (
"context"
"errors"
"fmt"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/aws/aws-sdk-go-v2/feature/rds/auth"
)
// Signing in to a cloud's managed database with Marmot's identity: the
// pipeline's token is exchanged for the cloud's credentials, which then
// make a short-lived database password. Amazon RDS and Aurora take an IAM
// authentication token, Cloud SQL an OAuth access token of an IAM user or
// service account, and Azure Database and Azure SQL an Entra ID access
// token. A plugin keeps each cloud's settings in an object of its own
// (aws, gcp, azure), declares the matching sign-in methods and asks
// DatabasePassword for the password each time it connects.
// AWSDatabaseIdentity signs in to an Amazon RDS or Aurora database as an
// IAM role trusted to take Marmot's identity.
type AWSDatabaseIdentity struct {
RoleARN string `json:"role_arn,omitempty" label:"Role ARN" description:"The IAM role Marmot signs in as with the pipeline's identity token, allowed rds-db:connect for the database user"`
Region string `json:"region,omitempty" description:"The AWS region the database is in"`
}
// GCPDatabaseIdentity signs in to a Cloud SQL database as a service
// account, impersonated through workload identity federation.
type GCPDatabaseIdentity struct {
WorkloadIdentityProvider string `json:"workload_identity_provider,omitempty" label:"Workload identity provider" description:"The provider Marmot's identity token is exchanged at, projects/<number>/locations/global/workloadIdentityPools/<pool>/providers/<provider>"`
ServiceAccount string `json:"service_account,omitempty" label:"Service account" description:"The service account the database knows as an IAM user, which the pipeline impersonates"`
}
// AzureDatabaseIdentity signs in to an Azure database as an app
// registration or user-assigned managed identity whose federated
// credential trusts Marmot.
type AzureDatabaseIdentity struct {
TenantID string `json:"tenant_id,omitempty" label:"Tenant ID" description:"The Entra tenant of the identity the pipeline signs in as"`
ClientID string `json:"client_id,omitempty" label:"Client ID" description:"The application (client) ID of the app registration or managed identity the database knows as a user"`
}
// Token scopes of Entra ID's database sign-in.
const (
// AzureOSSRDBMSScope is the scope of Azure Database for PostgreSQL and
// for MySQL.
AzureOSSRDBMSScope = "https://ossrdbms-aad.database.windows.net/.default"
// AzureSQLScope is the scope of Azure SQL Database, Azure SQL Managed
// Instance and SQL Server with Entra authentication.
AzureSQLScope = "https://database.windows.net/.default"
)
// GCPCloudSQLLoginScope is the scope of an access token Cloud SQL takes as
// an IAM database user's password.
const GCPCloudSQLLoginScope = "https://www.googleapis.com/auth/sqlservice.login"
// DatabaseIdentity is one cloud's way of signing in to a database with
// Marmot's identity.
type DatabaseIdentity interface {
// Federated reports whether the config fills this way in.
Federated() bool
// Federate checks its settings and derives the token audience into raw.
Federate(raw RawConfig) error
}
var (
_ DatabaseIdentity = (*AWSDatabaseIdentity)(nil)
_ DatabaseIdentity = (*GCPDatabaseIdentity)(nil)
_ DatabaseIdentity = (*AzureDatabaseIdentity)(nil)
)
// FederateDatabase checks that a config signs in with at most one cloud's
// identity and derives that cloud's audience into raw, the config Validate
// returns to the host. A config that names none keeps signing in with its
// password; an audience without any is refused. Call it from Validate.
func FederateDatabase(raw RawConfig, identities ...DatabaseIdentity) error {
var chosen DatabaseIdentity
for _, identity := range identities {
if !identity.Federated() {
continue
}
if chosen != nil {
return validationError("audience", "sign in with one cloud's identity, not several")
}
chosen = identity
}
if chosen == nil {
if Audience(raw) != "" {
return validationError("audience", "signing in with Marmot's identity needs the settings of one cloud: aws, gcp or azure")
}
return nil
}
return chosen.Federate(raw)
}
// DatabasePassword returns a password for user at endpoint (host:port)
// from the one identity the config fills in, or ok false when it fills in
// none and the plugin uses its own password. Call it each time a
// connection is opened: the passwords last 15 minutes on AWS and about an
// hour on Google Cloud and Azure.
func DatabasePassword(ctx context.Context, endpoint, user, azureScope string, identities ...DatabaseIdentity) (password string, ok bool, err error) {
for _, identity := range identities {
if !identity.Federated() {
continue
}
switch id := identity.(type) {
case *AWSDatabaseIdentity:
password, err = id.RDSAuthToken(ctx, endpoint, user)
case *GCPDatabaseIdentity:
password, err = id.CloudSQLToken(ctx)
case *AzureDatabaseIdentity:
password, err = id.Token(ctx, azureScope)
default:
return "", false, fmt.Errorf("signing in to a database with %T is not supported", identity)
}
return password, true, err
}
return "", false, nil
}
// Federated reports whether the config names a role.
func (a *AWSDatabaseIdentity) Federated() bool {
return a != nil && strings.TrimSpace(a.RoleARN) != ""
}
func (a *AWSDatabaseIdentity) credentials() *AWSConfig {
return &AWSConfig{Credentials: AWSCredentials{RoleARN: strings.TrimSpace(a.RoleARN), Region: strings.TrimSpace(a.Region)}}
}
// Federate checks the role and region and derives the audience.
func (a *AWSDatabaseIdentity) Federate(raw RawConfig) error {
return nestedErrors("aws", a.credentials().Federate(raw))
}
// RDSAuthToken returns an IAM authentication token for user at endpoint
// (host:port), signed with the role's credentials. It is valid for 15
// minutes and is used as the password over TLS.
func (a *AWSDatabaseIdentity) RDSAuthToken(ctx context.Context, endpoint, user string) (string, error) {
cfg, err := a.credentials().NewAWSConfig(ctx)
if err != nil {
return "", err
}
token, err := auth.BuildAuthToken(ctx, endpoint, cfg.Region, user, cfg.Credentials)
if err != nil {
return "", fmt.Errorf("making an RDS authentication token: %w", err)
}
return token, nil
}
// Federated reports whether the config names a provider.
func (g *GCPDatabaseIdentity) Federated() bool {
return g != nil && strings.TrimSpace(g.WorkloadIdentityProvider) != ""
}
func (g *GCPDatabaseIdentity) credentials() *GCPCredentials {
return &GCPCredentials{WorkloadIdentityProvider: strings.TrimSpace(g.WorkloadIdentityProvider), ServiceAccount: strings.TrimSpace(g.ServiceAccount)}
}
// Federate checks the provider and service account and derives the
// audience. Cloud SQL knows service accounts as users, not federated
// principals, so the service account is required.
func (g *GCPDatabaseIdentity) Federate(raw RawConfig) error {
if strings.TrimSpace(g.ServiceAccount) == "" {
return validationError("gcp.service_account", "Cloud SQL signs in a service account, so name the one to impersonate")
}
creds := g.credentials()
if err := creds.Federate(raw); err != nil {
return nestedErrors("gcp", err)
}
g.WorkloadIdentityProvider = creds.WorkloadIdentityProvider
return nil
}
// CloudSQLToken returns an access token for the service account, which
// Cloud SQL takes as its IAM database user's password.
func (g *GCPDatabaseIdentity) CloudSQLToken(ctx context.Context) (string, error) {
source, err := g.credentials().TokenSource(ctx, GCPCloudSQLLoginScope)
if err != nil {
return "", err
}
token, err := source.Token()
if err != nil {
return "", fmt.Errorf("getting a Cloud SQL sign-in token: %w", err)
}
return token.AccessToken, nil
}
// Federated reports whether the config names an app registration.
func (z *AzureDatabaseIdentity) Federated() bool {
return z != nil && (strings.TrimSpace(z.TenantID) != "" || strings.TrimSpace(z.ClientID) != "")
}
func (z *AzureDatabaseIdentity) credentials() *AzureCredentials {
return &AzureCredentials{TenantID: strings.TrimSpace(z.TenantID), ClientID: strings.TrimSpace(z.ClientID)}
}
// Federate checks the tenant and client and derives the audience.
func (z *AzureDatabaseIdentity) Federate(raw RawConfig) error {
return nestedErrors("azure", z.credentials().Federate(raw))
}
// Token returns an Entra ID access token for scope, which the database
// takes as the password of the user named after the identity.
func (z *AzureDatabaseIdentity) Token(ctx context.Context, scope string) (string, error) {
if scope == "" {
return "", errors.New("signing in to an Azure database needs the database's token scope")
}
credential, err := z.credentials().Credential(ctx)
if err != nil {
return "", err
}
token, err := credential.GetToken(ctx, policy.TokenRequestOptions{Scopes: []string{scope}})
if err != nil {
return "", fmt.Errorf("getting an Entra ID token for the database: %w", err)
}
return token.Token, nil
}
// nestedErrors names the fields of a credential helper's validation errors
// by their path under the object holding them.
func nestedErrors(object string, err error) error {
var errs ValidationErrors
if !errors.As(err, &errs) {
return err
}
out := ValidationErrors{Errors: make([]ValidationError, len(errs.Errors))}
for i, e := range errs.Errors {
if e.Field != "audience" {
e.Field = object + "." + e.Field
}
out.Errors[i] = e
}
return out
}
// AWSDatabaseSignIn is the sign-in method of a plugin that keeps an
// AWSDatabaseIdentity in its "aws" setting, for Amazon RDS and Aurora.
// steps follow the generic ones: the engine's own, such as creating the
// database user.
func AWSDatabaseSignIn(steps ...TrustStep) SignInMethod {
m := AWSIdentitySignInAt("aws")
// The whole object is the method's, so choosing another clears it.
m.Fields = []string{"aws"}
m.ID, m.Label = "aws", "Amazon RDS with Marmot's identity"
m.Description = "Nothing to paste. Let an IAM role connect to the database."
m.Federation.Trust = append(m.Federation.Trust, TrustStep{
Title: "Let the role connect as the database user", Filename: "rds-connect-policy.json", Language: "json",
Text: "Attach this policy to the role. The resource id is the database's DbiResourceId, or the cluster's for Aurora.",
Code: `{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "rds-db:connect",
"Resource": "arn:aws:rds-db:{{config.aws.region}}:<account-id>:dbuser:<resource-id>/{{config.user}}"
}]
}`,
})
m.Federation.Trust = append(m.Federation.Trust, steps...)
return m
}
// GCPDatabaseSignIn is the sign-in method of a plugin that keeps a
// GCPDatabaseIdentity in its "gcp" setting, for Cloud SQL. steps follow
// the generic ones.
func GCPDatabaseSignIn(steps ...TrustStep) SignInMethod {
m := GCPIdentitySignInAt("gcp")
// The whole object is the method's, so choosing another clears it.
m.Fields = []string{"gcp"}
m.ID, m.Label = "gcp", "Cloud SQL with Marmot's identity"
m.Description = "Nothing to paste. Let a service account connect to the instance."
m.Required = append(m.Required, "gcp.service_account")
m.Federation.Trust = []TrustStep{
m.Federation.Trust[0],
{
Title: "Let this pipeline act as the service account",
Code: "gcloud iam service-accounts add-iam-policy-binding {{config.gcp.service_account}} \\\n" +
" --role=roles/iam.workloadIdentityUser \\\n" +
" --member=principal://iam.googleapis.com/projects/<project-number>/locations/global/workloadIdentityPools/<pool>/subject/{{subject}}",
Language: "sh",
},
{
Title: "Let the service account sign in to the instance",
Code: "gcloud projects add-iam-policy-binding <project> \\\n" +
" --role=roles/cloudsql.instanceUser \\\n" +
" --member=serviceAccount:{{config.gcp.service_account}}",
Language: "sh",
},
}
m.Federation.Trust = append(m.Federation.Trust, steps...)
return m
}
// AzureDatabaseSignIn is the sign-in method of a plugin that keeps an
// AzureDatabaseIdentity in its "azure" setting, for Azure Database for
// PostgreSQL or MySQL and Azure SQL. steps follow the generic one.
func AzureDatabaseSignIn(steps ...TrustStep) SignInMethod {
m := AzureIdentitySignInAt("azure")
// The whole object is the method's, so choosing another clears it.
m.Fields = []string{"azure"}
m.ID, m.Label = "azure", "Azure with Marmot's identity"
m.Description = "Nothing to paste. Add an app registration or managed identity as a database user."
m.Federation.Trust = append(m.Federation.Trust, steps...)
return m
}