Skip to content

Commit 5b14b6a

Browse files
authored
fix: Correctly set the credentials token source and the WithIAMAuthN opt (#2544)
This fixes a bug in how the auth proxy handled the configuration when the `--impersonate-service-account` flag and the `auto-iam-auth` instance configuration parameter are set at the same time. This is especially important to make the Cloud SQL Proxy Operator work correctly, see GoogleCloudPlatform/cloud-sql-proxy-operator#719 Fixes #2542
1 parent 235b7b0 commit 5b14b6a

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

internal/proxy/proxy.go

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,20 @@ func parseImpersonationChain(chain string) (string, []string) {
323323

324324
const iamLoginScope = "https://www.googleapis.com/auth/sqlservice.login"
325325

326+
// iamAuthNEnabled returns true if IAM authentication is enabled globally
327+
// or for any instance in the configuration.
328+
func (c *Config) iamAuthNEnabled() bool {
329+
if c.IAMAuthN {
330+
return true
331+
}
332+
for _, inst := range c.Instances {
333+
if inst.IAMAuthN != nil && *inst.IAMAuthN {
334+
return true
335+
}
336+
}
337+
return false
338+
}
339+
326340
func credentialsOpt(c Config, l cloudsql.Logger) (cloudsqlconn.Option, error) {
327341
// If service account impersonation is configured, set up an impersonated
328342
// credentials token source.
@@ -363,7 +377,8 @@ func credentialsOpt(c Config, l cloudsql.Logger) (cloudsqlconn.Option, error) {
363377
if err != nil {
364378
return nil, err
365379
}
366-
if c.IAMAuthN {
380+
381+
if c.iamAuthNEnabled() {
367382
iamLoginTS, err := impersonate.CredentialsTokenSource(
368383
context.Background(),
369384
impersonate.CredentialsConfig{
@@ -439,7 +454,7 @@ func (c *Config) DialerOptions(l cloudsql.Logger) ([]cloudsqlconn.Option, error)
439454
opts = append(opts, cloudsqlconn.WithUniverseDomain(c.UniverseDomain))
440455
}
441456

442-
if c.IAMAuthN {
457+
if c.iamAuthNEnabled() {
443458
opts = append(opts, cloudsqlconn.WithIAMAuthN())
444459
}
445460

tests/postgres_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,14 @@ func TestPostgresIAMDBAuthn(t *testing.T) {
280280
dsn: fmt.Sprintf("host=localhost user=%s database=%s sslmode=disable",
281281
impersonatedIAMUser, *postgresDB),
282282
},
283+
{
284+
desc: "using impersonation with query param",
285+
args: []string{
286+
"--impersonate-service-account", *impersonatedUser,
287+
fmt.Sprintf("%s?auto-iam-authn=true", *postgresConnName)},
288+
dsn: fmt.Sprintf("host=localhost user=%s password=password database=%s sslmode=disable",
289+
impersonatedIAMUser, *postgresDB),
290+
},
283291
}
284292
for _, tc := range tcs {
285293
t.Run(tc.desc, func(t *testing.T) {

0 commit comments

Comments
 (0)