Skip to content

Commit

Permalink
AAD Authentication using AccessToken (denisenkom#546)
Browse files Browse the repository at this point in the history
mssql: add Azure Active Directory token based login

Create a new connector that allows refreshing the access token
based on an external identifier.
  • Loading branch information
paulmey authored and rHermes committed Mar 30, 2020
1 parent ce04544 commit b965d5a
Show file tree
Hide file tree
Showing 11 changed files with 519 additions and 39 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,26 @@ Other supported formats are listed below.
* `odbc:server=localhost;user id=sa;password={foo{bar}` // Literal `{`, password is "foo{bar"
* `odbc:server=localhost;user id=sa;password={foo}}bar}` // Escaped `} with `}}`, password is "foo}bar"

### Azure Active Directory authentication - preview

The configuration of functionality might change in the future.

Azure Active Directory (AAD) access tokens are relatively short lived and need to be
valid when a new connection is made. Authentication is supported using a callback func that
provides a fresh and valid token using a connector:
``` golang
conn, err := mssql.NewAccessTokenConnector(
"Server=test.database.windows.net;Database=testdb",
tokenProvider)
if err != nil {
// handle errors in DSN
}
db := sql.OpenDB(conn)
```
Where `tokenProvider` is a function that returns a fresh access token or an error. None of these statements
actually trigger the retrieval of a token, this happens when the first statment is issued and a connection
is created.

## Executing Stored Procedures

To run a stored procedure, set the query text to the procedure name:
Expand Down
51 changes: 51 additions & 0 deletions accesstokenconnector.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// +build go1.10

package mssql

import (
"context"
"database/sql/driver"
"errors"
"fmt"
)

var _ driver.Connector = &accessTokenConnector{}

// accessTokenConnector wraps Connector and injects a
// fresh access token when connecting to the database
type accessTokenConnector struct {
Connector

accessTokenProvider func() (string, error)
}

// NewAccessTokenConnector creates a new connector from a DSN and a token provider.
// The token provider func will be called when a new connection is requested and should return a valid access token.
// The returned connector may be used with sql.OpenDB.
func NewAccessTokenConnector(dsn string, tokenProvider func() (string, error)) (driver.Connector, error) {
if tokenProvider == nil {
return nil, errors.New("mssql: tokenProvider cannot be nil")
}

conn, err := NewConnector(dsn)
if err != nil {
return nil, err
}

c := &accessTokenConnector{
Connector: *conn,
accessTokenProvider: tokenProvider,
}
return c, nil
}

// Connect returns a new database connection
func (c *accessTokenConnector) Connect(ctx context.Context) (driver.Conn, error) {
var err error
c.Connector.params.fedAuthAccessToken, err = c.accessTokenProvider()
if err != nil {
return nil, fmt.Errorf("mssql: error retrieving access token: %+v", err)
}

return c.Connector.Connect(ctx)
}
92 changes: 92 additions & 0 deletions accesstokenconnector_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// +build go1.10

package mssql

import (
"context"
"database/sql/driver"
"errors"
"fmt"
"strings"
"testing"
)

func TestNewAccessTokenConnector(t *testing.T) {
dsn := "Server=server.database.windows.net;Database=db"
tp := func() (string, error) { return "token", nil }
type args struct {
dsn string
tokenProvider func() (string, error)
}
tests := []struct {
name string
args args
want func(driver.Connector) error
wantErr bool
}{
{
name: "Happy path",
args: args{
dsn: dsn,
tokenProvider: tp},
want: func(c driver.Connector) error {
tc, ok := c.(*accessTokenConnector)
if !ok {
return fmt.Errorf("Expected driver to be of type *accessTokenConnector, but got %T", c)
}
p := tc.Connector.params
if p.database != "db" {
return fmt.Errorf("expected params.database=db, but got %v", p.database)
}
if p.host != "server.database.windows.net" {
return fmt.Errorf("expected params.host=server.database.windows.net, but got %v", p.host)
}
if tc.accessTokenProvider == nil {
return fmt.Errorf("Expected tokenProvider to not be nil")
}
t, err := tc.accessTokenProvider()
if t != "token" || err != nil {
return fmt.Errorf("Unexpected results from tokenProvider: %v, %v", t, err)
}
return nil
},
wantErr: false,
},
{
name: "Nil tokenProvider gives error",
args: args{
dsn: dsn,
tokenProvider: nil},
want: nil,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := NewAccessTokenConnector(tt.args.dsn, tt.args.tokenProvider)
if (err != nil) != tt.wantErr {
t.Errorf("NewAccessTokenConnector() error = %v, wantErr %v", err, tt.wantErr)
return
}
if tt.want != nil {
if err := tt.want(got); err != nil {
t.Error(err)
}
}
})
}
}

func TestAccessTokenConnectorFailsToConnectIfNoAccessToken(t *testing.T) {
errorText := "This is a test"
dsn := "Server=server.database.windows.net;Database=db"
tp := func() (string, error) { return "", errors.New(errorText) }
sut, err := NewAccessTokenConnector(dsn, tp)
if err != nil {
t.Fatalf("expected err==nil, but got %+v", err)
}
_, err = sut.Connect(context.TODO())
if err == nil || !strings.Contains(err.Error(), errorText) {
t.Fatalf("expected error to contain %q, but got %q", errorText, err)
}
}
1 change: 1 addition & 0 deletions conn_str.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ type connectParams struct {
failOverPartner string
failOverPort uint64
packetSize uint16
fedAuthAccessToken string
}

func parseConnectParams(dsn string) (connectParams, error) {
Expand Down
9 changes: 9 additions & 0 deletions examples/azuread-accesstoken/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
## Azure Managed Identity example

This example shows how Azure Managed Identity can be used to access SQL Azure. Take note of the
trust boundary before using MSI to prevent exposure of the tokens outside of the trust boundary.

This example can only be run from a Azure Virtual Machine with Managed Identity configured.
You can follow the steps from this tutorial to turn on managed identity for your VM and grant the
VM access to a SQL Azure database:
https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/tutorial-windows-vm-access-sql
8 changes: 8 additions & 0 deletions examples/azuread-accesstoken/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module github.com/denisenkom/go-mssqldb/examples/azure-ad-accesstoken

go 1.13

require (
github.com/Azure/go-autorest/autorest/adal v0.8.1
github.com/denisenkom/go-mssqldb v0.0.0-20191128021309-1d7a30a10f73
)
30 changes: 30 additions & 0 deletions examples/azuread-accesstoken/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
github.com/Azure/go-autorest v13.3.2+incompatible h1:VxzPyuhtnlBOzc4IWCZHqpyH2d+QMLQEuy3wREyY4oc=
github.com/Azure/go-autorest/autorest v0.9.0 h1:MRvx8gncNaXJqOoLmhNjUAKh33JJF8LyxPhomEtOsjs=
github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI=
github.com/Azure/go-autorest/autorest v0.9.4 h1:1cM+NmKw91+8h5vfjgzK4ZGLuN72k87XVZBWyGwNjUM=
github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0=
github.com/Azure/go-autorest/autorest/adal v0.8.1 h1:pZdL8o72rK+avFWl+p9nE8RWi1JInZrWJYlnpfXJwHk=
github.com/Azure/go-autorest/autorest/adal v0.8.1/go.mod h1:ZjhuQClTqx435SRJ2iMlOxPYt3d2C/T/7TiQCVZSn3Q=
github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA=
github.com/Azure/go-autorest/autorest/date v0.2.0 h1:yW+Zlqf26583pE43KhfnhFcdmSWlm5Ew6bxipnr/tbM=
github.com/Azure/go-autorest/autorest/date v0.2.0/go.mod h1:vcORJHLJEh643/Ioh9+vPmf1Ij9AEBM5FuBIXLmIy0g=
github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0=
github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0=
github.com/Azure/go-autorest/autorest/mocks v0.3.0/go.mod h1:a8FDP3DYzQ4RYfVAxAN3SVSiiO77gL2j2ronKKP0syM=
github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc=
github.com/Azure/go-autorest/tracing v0.5.0 h1:TRn4WjSnkcSy5AEG3pnbtFSwNtwzjr4VYyQflFE619k=
github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk=
github.com/denisenkom/go-mssqldb v0.0.0-20191128021309-1d7a30a10f73 h1:OGNva6WhsKst5OZf7eZOklDztV3hwtTHovdrLHV+MsA=
github.com/denisenkom/go-mssqldb v0.0.0-20191128021309-1d7a30a10f73/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY=
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413 h1:ULYEB3JvPRE/IfO+9uO7vKV/xzVTO7XPAwm8xbf4w2g=
golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
82 changes: 82 additions & 0 deletions examples/azuread-accesstoken/managed_identity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package main

import (
"database/sql"
"flag"
"fmt"
"log"

"github.com/Azure/go-autorest/autorest/adal"
mssql "github.com/denisenkom/go-mssqldb"
)

var (
debug = flag.Bool("debug", false, "enable debugging")
server = flag.String("server", "", "the database server")
database = flag.String("database", "", "the database")
)

func main() {
flag.Parse()

if *debug {
fmt.Printf(" server:%s\n", *server)
fmt.Printf(" database:%s\n", *database)
}

if *server == "" {
log.Fatal("Server name cannot be left empty")
}

if *database == "" {
log.Fatal("Database name cannot be left empty")
}

connString := fmt.Sprintf("Server=%s;Database=%s", *server, *database)
if *debug {
fmt.Printf(" connString:%s\n", connString)
}

tokenProvider, err := getMSITokenProvider()
if err != nil {
log.Fatal("Error creating token provider for system assigned Azure Managed Identity:", err.Error())
}

connector, err := mssql.NewAccessTokenConnector(
connString, tokenProvider)
if err != nil {
log.Fatal("Connector creation failed:", err.Error())
}
conn := sql.OpenDB(connector)
defer conn.Close()

row := conn.QueryRow("select 1, 'abc'")
var somenumber int64
var somechars string
err = row.Scan(&somenumber, &somechars)
if err != nil {
log.Fatal("Scan failed:", err.Error())
}
fmt.Printf("somenumber:%d\n", somenumber)
fmt.Printf("somechars:%s\n", somechars)

fmt.Printf("bye\n")
}

func getMSITokenProvider() (func() (string, error), error) {
msiEndpoint, err := adal.GetMSIEndpoint()
if err != nil {
return nil, err
}
msi, err := adal.NewServicePrincipalTokenFromMSI(
msiEndpoint, "https://database.windows.net/")
if err != nil {
return nil, err
}

return func() (string, error) {
msi.EnsureFresh()
token := msi.OAuthToken()
return token, nil
}, nil
}

0 comments on commit b965d5a

Please sign in to comment.