Skip to content

Commit

Permalink
Add accesstoken authentication support
Browse files Browse the repository at this point in the history
  • Loading branch information
paulmey committed Jan 23, 2020
1 parent 90474ec commit 741a17d
Show file tree
Hide file tree
Showing 8 changed files with 309 additions and 3 deletions.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,24 @@ 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"

### Using Azure Active Directory access tokens for authentication

Azure Active Directory (AAD) is not supported through the DSN, but through a "token provider" callback.
Since access tokens are relatively short lived and need to be valid when a new connection is made,
a better way to provide them is using a connector:
``` golang
conn, err := mssql.NewAccessTokenConnector(
"Server=test.database.windows.net;Database=testdb",
tokenProvider)
if err != nil {
// handle errors in DSN parsing
}
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)
}
86 changes: 86 additions & 0 deletions accesstokenconnector_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// +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
}{
{"Happy path",
args{dsn, tp},
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
},
false,
},
{"Nil tokenProvider gives error",
args{dsn, nil},
nil,
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 @@ -46,6 +46,7 @@ type connectParams struct {
packetSize uint16
fedAuthLibrary byte
fedAuthADALWorkflow byte
fedAuthAccessToken string
aadTenantID string
aadClientCertPath string
tlsKeyLogFile string
Expand Down
9 changes: 9 additions & 0 deletions examples/azure-managed-identity/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
88 changes: 88 additions & 0 deletions examples/azure-managed-identity/managed_identity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
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()

stmt, err := conn.Prepare("select 1, 'abc'")
if err != nil {
log.Fatal("Prepare failed:", err.Error())
}
defer stmt.Close()

row := stmt.QueryRow()
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
}
9 changes: 8 additions & 1 deletion tds.go
Original file line number Diff line number Diff line change
Expand Up @@ -1033,8 +1033,15 @@ initiate_connection:
FedAuthEcho: fedAuthEcho,
FedAuthADALWorkflow: p.fedAuthADALWorkflow,
}

auth, auth_ok := getAuth(p.user, p.password, p.serverSPN, p.workstation)
if login.FedAuthLibrary == fedAuthLibraryReserved && auth_ok {
if p.fedAuthAccessToken != "" { // accesstoken ignores user/password
if p.logFlags&logDebug != 0 {
log.Println("Using provided access token")
}
login.FedAuthToken = p.fedAuthAccessToken
login.FedAuthLibrary = fedAuthLibrarySecurityToken
} else if login.FedAuthLibrary == fedAuthLibraryReserved && auth_ok {
if p.logFlags&logDebug != 0 {
log.Println("Starting SSPI login")
}
Expand Down
50 changes: 48 additions & 2 deletions tds_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,54 @@ func TestSendLogin(t *testing.T) {
}
}

func TestSendLoginWithFedAuthToken(t *testing.T) {
memBuf := new(MockTransport)
buf := newTdsBuffer(1024, memBuf)
login := login{
TDSVersion: verTDS74,
PacketSize: 0x1000,
ClientProgVer: 0x01060100,
ClientPID: 100,
ClientTimeZone: -4 * 60,
ClientID: [6]byte{0x12, 0x34, 0x56, 0x78, 0x90, 0xab},
OptionFlags1: 0xe0,
OptionFlags3: 8,
HostName: "subdev1",
AppName: "appname",
ServerName: "servername",
CtlIntName: "library",
Language: "en",
Database: "database",
ClientLCID: 0x204,
FedAuthLibrary: fedAuthLibrarySecurityToken,
FedAuthToken: "fedauthtoken",
}
err := sendLogin(buf, login)
if err != nil {
t.Error("sendLogin should succeed")
}
ref := []byte{
16, 1, 0, 223, 0, 0, 1, 0, 215, 0, 0, 0, 4, 0, 0, 116, 0, 16, 0, 0, 0, 1,
6, 1, 100, 0, 0, 0, 0, 0, 0, 0, 224, 0, 0, 24, 16, 255, 255, 255, 4, 2, 0,
0, 94, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 108, 0, 7, 0, 122, 0, 10, 0, 142,
0, 4, 0, 146, 0, 7, 0, 160, 0, 2, 0, 164, 0, 8, 0, 18, 52, 86, 120, 144, 171,
180, 0, 0, 0, 180, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 115, 0, 117, 0, 98,
0, 100, 0, 101, 0, 118, 0, 49, 0, 97, 0, 112, 0, 112, 0, 110, 0, 97, 0,
109, 0, 101, 0, 115, 0, 101, 0, 114, 0, 118, 0, 101, 0, 114, 0, 110, 0, 97,
0, 109, 0, 101, 0, 180, 0, 0, 0, 108, 0, 105, 0, 98, 0, 114, 0, 97, 0, 114, 0,
121, 0, 101, 0, 110, 0, 100, 0, 97, 0, 116, 0, 97, 0, 98, 0, 97, 0, 115, 0, 101,
0, 2, 29, 0, 0, 0, 2, 24, 0, 0, 0, 102, 0, 101, 0, 100, 0, 97, 0, 117, 0, 116,
0, 104, 0, 116, 0, 111, 0, 107, 0, 101, 0, 110, 0, 255}
out := memBuf.Bytes()
if !bytes.Equal(ref, out) {
fmt.Println("Expected:")
fmt.Print(hex.Dump(ref))
fmt.Println("Returned:")
fmt.Print(hex.Dump(out))
t.Error("input output don't match")
}
}

func TestSendSqlBatch(t *testing.T) {
checkConnStr(t)
p, err := parseConnectParams(makeConnStr(t).String())
Expand Down Expand Up @@ -176,8 +224,6 @@ func (l testLogger) Println(v ...interface{}) {
l.t.Log(v...)
}



func TestConnect(t *testing.T) {
checkConnStr(t)
SetLogger(testLogger{t})
Expand Down

0 comments on commit 741a17d

Please sign in to comment.