Skip to content

Commit

Permalink
feat: use alloydb-go-connector (GoogleCloudPlatform#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
enocom authored Apr 14, 2022
1 parent 90ba6c6 commit 896ba1c
Show file tree
Hide file tree
Showing 14 changed files with 198 additions and 247 deletions.
46 changes: 46 additions & 0 deletions .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

name: tests
on:
pull_request:
push:
branches:
- main

jobs:
build:
name: "unit tests"
runs-on: ubuntu-latest
environment: "Private Repos"
steps:
- name: Setup Go
uses: actions/setup-go@v3
with:
go-version: "1.18"
- name: Checkout code
uses: actions/checkout@v3
# TODO remove this step and the following when the repo is public
- name: Checkout AlloyDB connector
uses: actions/checkout@v3
with:
repository: "googlecloudplatform/alloydb-go-connector"
path: "alloydb-go-connector"
token: ${{ secrets.GH_PAT }}
- name: Point to local connector
run: |
go mod edit -replace=cloud.google.com/go/alloydbconn=./alloydb-go-connector
- name: Run tests
run: |
go test -v -race -cover -short ./...
5 changes: 1 addition & 4 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@
.vscode/

# Compiled binary
/cmd/cloud_sql_proxy/cloud_sql_proxy
/cloud_sql_proxy
# v2 binary
/cloudsql-proxy
/alloydb-auth-proxy

/key.json
11 changes: 4 additions & 7 deletions cloudsql/cloudsql.go → alloydb/alloydb.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,20 @@
// See the License for the specific language governing permissions and
// limitations under the License.

package cloudsql
package alloydb

import (
"context"
"io"
"net"

"cloud.google.com/go/cloudsqlconn"
"cloud.google.com/go/alloydbconn"
)

// Dialer dials a Cloud SQL instance and returns its database engine version.
// Dialer dials an AlloyDB instance.
type Dialer interface {
// Dial returns a connection to the specified instance.
Dial(ctx context.Context, inst string, opts ...cloudsqlconn.DialOption) (net.Conn, error)
// EngineVersion retrieves the provided instance's database version (e.g.,
// POSTGRES_14)
EngineVersion(ctx context.Context, inst string) (string, error)
Dial(ctx context.Context, inst string, opts ...alloydbconn.DialOption) (net.Conn, error)

io.Closer
}
36 changes: 18 additions & 18 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ import (
"strings"
"syscall"

"cloud.google.com/go/cloudsqlconn"
"github.com/GoogleCloudPlatform/cloudsql-proxy/v2/cloudsql"
"github.com/GoogleCloudPlatform/cloudsql-proxy/v2/internal/proxy"
"cloud.google.com/go/alloydbconn"
"github.com/GoogleCloudPlatform/alloydb-auth-proxy/alloydb"
"github.com/GoogleCloudPlatform/alloydb-auth-proxy/internal/proxy"
"github.com/spf13/cobra"
)

Expand All @@ -42,7 +42,7 @@ var (

func init() {
versionString = strings.TrimSpace(versionString)
userAgent = "cloud-sql-auth-proxy/" + versionString
userAgent = "alloy-db-auth-proxy/" + versionString
}

// Execute adds all child commands to the root command and sets flags appropriately.
Expand All @@ -57,7 +57,7 @@ func Execute() {
}
}

// Command represents an invocation of the Cloud SQL Auth Proxy.
// Command represents an invocation of the AlloyDB Auth Proxy.
type Command struct {
*cobra.Command
conf *proxy.Config
Expand All @@ -67,8 +67,8 @@ type Command struct {
type Option func(*proxy.Config)

// WithDialer configures the Command to use the provided dialer to connect to
// Cloud SQL instances.
func WithDialer(d cloudsql.Dialer) Option {
// AlloyDB instances.
func WithDialer(d alloydb.Dialer) Option {
return func(c *proxy.Config) {
c.Dialer = d
}
Expand All @@ -84,13 +84,13 @@ func NewCommand(opts ...Option) *Command {
}

cmd := &cobra.Command{
Use: "cloud_sql_proxy instance_connection_name...",
Use: "alloydb-auth-proxy instance_connection_name...",
Version: versionString,
Short: "cloud_sql_proxy provides a secure way to authorize connections to Cloud SQL.",
Long: `The Cloud SQL Auth proxy provides IAM-based authorization and encryption when
connecting to Cloud SQL instances. It listens on a local port and forwards connections
to your instance's IP address, providing a secure connection without having to manage
any client SSL certificates.`,
Short: "alloydb-auth-proxy provides a secure way to authorize connections to AlloyDB.",
Long: `The AlloyDB Auth proxy provides IAM-based authorization and encryption when
connecting to AlloyDB instances. It listens on a local port and forwards
connections to your instance's IP address, providing a secure connection
without having to manage any client SSL certificates.`,
Args: func(cmd *cobra.Command, args []string) error {
err := parseConfig(cmd, c.conf, args)
if err != nil {
Expand All @@ -113,8 +113,8 @@ any client SSL certificates.`,

// Global and per instance flags
cmd.PersistentFlags().StringVarP(&c.conf.Addr, "address", "a", "127.0.0.1",
"Address on which to bind Cloud SQL instance listeners.")
cmd.PersistentFlags().IntVarP(&c.conf.Port, "port", "p", 0,
"Address on which to bind AlloyDB instance listeners.")
cmd.PersistentFlags().IntVarP(&c.conf.Port, "port", "p", 5432,
"Initial port to use for listeners. Subsequent listeners increment from this value.")

c.Command = cmd
Expand Down Expand Up @@ -142,7 +142,7 @@ func parseConfig(cmd *cobra.Command, conf *proxy.Config, args []string) error {
case conf.CredentialsFile != "":
cmd.Printf("Authorizing with the credentials file at %q\n", conf.CredentialsFile)
default:
cmd.Printf("Authorizing with Application Default Credentials")
cmd.Println("Authorizing with Application Default Credentials")
}

var ics []proxy.InstanceConnConfig
Expand Down Expand Up @@ -227,9 +227,9 @@ func runSignalWrapper(cmd *Command) error {
// Otherwise, initialize a new one.
d := cmd.conf.Dialer
if d == nil {
opts := append(cmd.conf.DialerOpts(), cloudsqlconn.WithUserAgent(userAgent))
opts := append(cmd.conf.DialerOpts(), alloydbconn.WithUserAgent(userAgent))
var err error
d, err = cloudsqlconn.NewDialer(ctx, opts...)
d, err = alloydbconn.NewDialer(ctx, opts...)
if err != nil {
shutdownCh <- fmt.Errorf("error initializing dialer: %v", err)
return
Expand Down
68 changes: 52 additions & 16 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@ package cmd
import (
"context"
"errors"
"fmt"
"net"
"sync"
"testing"
"time"

"cloud.google.com/go/cloudsqlconn"
"github.com/GoogleCloudPlatform/cloudsql-proxy/v2/internal/proxy"
"cloud.google.com/go/alloydbconn"
"github.com/GoogleCloudPlatform/alloydb-auth-proxy/internal/proxy"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/spf13/cobra"
Expand All @@ -34,6 +35,9 @@ func TestNewCommandArguments(t *testing.T) {
if c.Addr == "" {
c.Addr = "127.0.0.1"
}
if c.Port == 0 {
c.Port = 5432
}
if c.Instances == nil {
c.Instances = []proxy.InstanceConnConfig{{}}
}
Expand Down Expand Up @@ -240,38 +244,70 @@ func (s *spyDialer) instance() string {
return i
}

func (*spyDialer) Dial(_ context.Context, inst string, _ ...cloudsqlconn.DialOption) (net.Conn, error) {
return nil, errors.New("spy dialer does not dial")
}

func (s *spyDialer) EngineVersion(ctx context.Context, inst string) (string, error) {
func (s *spyDialer) Dial(_ context.Context, inst string, _ ...alloydbconn.DialOption) (net.Conn, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.got = inst
return "", nil
return nil, errors.New("spy dialer does not dial")
}

func (*spyDialer) Close() error {
return nil
}

func TestCommandWithCustomDialer(t *testing.T) {
want := "my-project:my-region:my-instance"
want := "my-project:my-region:my-cluster:my-instance"
s := &spyDialer{}
c := NewCommand(WithDialer(s))
// Keep the test output quiet
c.SilenceUsage = true
c.SilenceErrors = true
c.SetArgs([]string{want})
c.SetArgs([]string{"--port", "10000", want})

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

if err := c.ExecuteContext(ctx); !errors.As(err, &errSigInt) {
t.Fatalf("want errSigInt, got = %v", err)
}
go func() {
if err := c.ExecuteContext(ctx); !errors.As(err, &errSigInt) {
t.Fatalf("want errSigInt, got = %v", err)
}
}()

if got := s.instance(); got != want {
t.Fatalf("want = %v, got = %v", want, got)
// try will run f count times, returning early if f succeeds, or failing
// when count has been exceeded.
try := func(f func() error, count int) {
var (
attempts int
err error
)
for {
if attempts == count {
t.Fatal(err)
}
err = f()
if err != nil {
attempts++
time.Sleep(time.Millisecond)
continue
}
return
}
}
// give the listener some time to start
try(func() error {
conn, err := net.Dial("tcp", "127.0.0.1:10000")
if err != nil {
return err
}
defer conn.Close()
return nil
}, 10)

// give the proxy some time to run
try(func() error {
if got := s.instance(); got != want {
return fmt.Errorf("want = %v, got = %v", want, got)
}
return nil
}, 10)
}
23 changes: 8 additions & 15 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,23 +1,16 @@
module github.com/GoogleCloudPlatform/cloudsql-proxy/v2
module github.com/GoogleCloudPlatform/alloydb-auth-proxy

go 1.16

require (
cloud.google.com/go/cloudsqlconn v0.2.1-0.20220401153611-87e713b37755
cloud.google.com/go/compute v1.5.0
github.com/GoogleCloudPlatform/cloudsql-proxy v1.29.0
github.com/coreos/go-systemd/v22 v22.3.2
github.com/denisenkom/go-mssqldb v0.12.0
github.com/go-sql-driver/mysql v1.6.0
cloud.google.com/go/alloydbconn v0.0.0-0.20220401153611-87e713b37755
github.com/google/go-cmp v0.5.7
github.com/hanwen/go-fuse/v2 v2.1.0
github.com/jackc/pgx/v4 v4.15.0
github.com/lib/pq v1.10.5
github.com/lib/pq v1.10.5 // indirect
github.com/spf13/cobra v1.2.1
go.uber.org/zap v1.21.0
golang.org/x/net v0.0.0-20220325170049-de3da57026de
golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a
golang.org/x/sys v0.0.0-20220406163625-3f8b81556e12
golang.org/x/time v0.0.0-20220224211638-0e9765cccd65
google.golang.org/api v0.74.0
golang.org/x/sys v0.0.0-20220406163625-3f8b81556e12 // indirect
google.golang.org/api v0.74.0 // indirect
google.golang.org/genproto v0.0.0-20220401170504-314d38edb7de // indirect
)

replace cloud.google.com/go/alloydbconn => ../alloydb-go-connector
Loading

0 comments on commit 896ba1c

Please sign in to comment.