Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add AAD auth using azidentity #698

Merged
merged 4 commits into from Jan 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -10,4 +10,5 @@ coverage.json
coverage.txt
coverage.xml
testresults.xml
.azureconnstr

12 changes: 8 additions & 4 deletions .pipelines/TestSql2017.yml
Expand Up @@ -2,6 +2,8 @@ pool:
vmImage: 'ubuntu-latest'

trigger: none
variables:
TESTPASSWORD: $(SQLPASSWORD)

steps:
- task: GoTool@0
Expand Down Expand Up @@ -39,24 +41,26 @@ steps:
arguments: 'github.com/AlekSi/gocov-xml@latest'
workingDirectory: '$(System.DefaultWorkingDirectory)'

#Your build pipeline references an undefined variables named SQLPASSWORD and HOST.
#Your build pipeline references an undefined variables named SQLPASSWORD and AZURESERVER_DSN.
#Create or edit the build pipeline for this YAML file, define the variable on the Variables tab. See https://go.microsoft.com/fwlink/?linkid=865972

- task: Docker@2
displayName: 'Run SQL 2017 docker image'
inputs:
command: run
arguments: '-m 2GB -e ACCEPT_EULA=1 -d --name sql2017 -p:1433:1433 -e SA_PASSWORD=$(SQLPASSWORD) mcr.microsoft.com/mssql/server:2017-latest'
arguments: '-m 2GB -e ACCEPT_EULA=1 -d --name sql2017 -p:1433:1433 -e SA_PASSWORD=$(TESTPASSWORD) mcr.microsoft.com/mssql/server:2017-latest'

- script: |
~/go/bin/gotestsum --junitfile testresults.xml -- -coverprofile=coverage.txt -covermode count
~/go/bin/gotestsum --junitfile testresults.xml -- -coverprofile=coverage.txt -covermode count ./...
~/go/bin/gocov convert coverage.txt > coverage.json
~/go/bin/gocov-xml < coverage.json > coverage.xml
mkdir coverage
workingDirectory: '$(Build.SourcesDirectory)'
displayName: 'run tests'
env:
SQLPASSWORD: $(SQLPASSWORD)
SQLSERVER_DSN: 'server=.;user id=sa;password=$(TESTPASSWORD)'
AZURESERVER_DSN: $(AZURESERVER_DSN)

continueOnError: true
- task: PublishTestResults@2
displayName: "Publish junit-style results"
Expand Down
47 changes: 31 additions & 16 deletions README.md
Expand Up @@ -112,30 +112,43 @@ 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
### Azure Active Directory authentication

Azure Active Directory authentication uses temporary authentication tokens to authenticate.
The `mssql` package does not provide an implementation to obtain tokens: instead, import the `azuread` package and use driver name `azuresql`. This driver uses [azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#section-readme) to acquire tokens using a variety of credential types.

The credential type is determined by the new `fedauth` connection string parameter.

* `fedauth=ActiveDirectoryServicePrincipal` or `fedauth=ActiveDirectoryApplication` - authenticates using an Azure Active Directory application client ID and client secret or certificate. Implemented using [ClientSecretCredential or CertificateCredential](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/azidentity#authenticating-service-principals)
* `clientcertpath=<path to certificate file>;password=<certificate password>` or
* `password=<client secret>`
* `user id=<application id>[@tenantid]` Note the `@tenantid` component can be omitted if the server's tenant is the same as the application's tenant.
* `fedauth=ActiveDirectoryPassword` - authenticates using a user name and password.
* `user id=username@domain`
* `password=<password>`
* `applicationclientid=<application id>` - This guid identifies an Azure Active Directory enterprise application that the AAD admin has approved for accessing Azure SQL database resources in the tenant. This driver does not have an associated application id of its own.
* `fedauth=ActiveDirectoryDefault` - authenticates using a chained set of credentials. The chain is built from EnvironmentCredential -> ManagedIdentityCredential->AzureCLICredential. See [DefaultAzureCredential docs](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#configure-defaultazurecredential) for instructions on setting up your host environment to use it. Using this option allows you to have the same connection string in a service deployment as on your interactive development machine.
* `fedauth=ActiveDirectoryManagedIdentity` or `fedauth=ActiveDirectoryMSI` - authenticates using a system-assigned or user-assigned Azure Managed Identity.
* `user id=<identity id>` - optional id of user-assigned managed identity. If empty, system-assigned managed identity is used.
* `fedauth=ActiveDirectoryInteractive` - authenticates using credentials acquired from an external web browser. Only suitable for use with human interaction.
* `applicationclientid=<application id>` - This guid identifies an Azure Active Directory enterprise application that the AAD admin has approved for accessing Azure SQL database resources in the tenant. This driver does not have an associated application id of its own.

The configuration of functionality might change in the future.
```go

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:
import (
"database/sql"
"net/url"

``` go
// Import the Azure AD driver module (also imports the regular driver package)
"github.com/denisenkom/go-mssqldb/azuread"
)

conn, err := mssql.NewAccessTokenConnector(
"Server=test.database.windows.net;Database=testdb",
tokenProvider)
if err != nil {
// handle errors in DSN
func ConnectWithMSI() (*sql.DB, error) {
return sql.Open(azuread.DriverName, "sqlserver://azuresql.database.windows.net?database=yourdb&fedauth=ActiveDirectoryMSI")
}
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 Expand Up @@ -306,6 +319,8 @@ Example:
env SQLSERVER_DSN=sqlserver://user:pass@hostname/instance?database=test1 go test
```

`AZURESERVER_DSN` environment variable provides the connection string for Azure Active Directory-based authentication. If it's not set the AAD test will be skipped.

## Deprecated

These features still exist in the driver, but they are are deprecated.
Expand Down
2 changes: 1 addition & 1 deletion accesstokenconnector.go
Expand Up @@ -22,7 +22,7 @@ func NewAccessTokenConnector(dsn string, tokenProvider func() (string, error)) (
}

conn.fedAuthRequired = true
conn.fedAuthLibrary = fedAuthLibrarySecurityToken
conn.fedAuthLibrary = FedAuthLibrarySecurityToken
conn.securityTokenProvider = func(ctx context.Context) (string, error) {
return tokenProvider()
}
Expand Down
63 changes: 63 additions & 0 deletions azuread/azuread_test.go
@@ -0,0 +1,63 @@
package azuread

import (
"bufio"
"database/sql"
"io"
"os"
"testing"

mssql "github.com/denisenkom/go-mssqldb"
)

func TestAzureSqlAuth(t *testing.T) {
mssqlConfig := testConnParams(t)

conn, err := newConnectorConfig(mssqlConfig)
if err != nil {
t.Fatalf("Unable to get a connector: %v", err)
}
db := sql.OpenDB(conn)
row := db.QueryRow("select 100, suser_sname()")
var val int
var user string
err = row.Scan(&val, &user)
if err != nil {
t.Fatalf("Unable to query the db: %v", err)
}
if val != 100 {
t.Fatalf("Got wrong value from query. Expected:100, Got: %d", val)
}
t.Logf("Got suser_sname value %s", user)

}

// returns parsed connection parameters derived from
// environment variables
func testConnParams(t testing.TB) *azureFedAuthConfig {
dsn := os.Getenv("AZURESERVER_DSN")
const logFlags = 127
if dsn == "" {
// try loading connection string from file
f, err := os.Open(".azureconnstr")
if err == nil {
rdr := bufio.NewReader(f)
dsn, err = rdr.ReadString('\n')
if err != io.EOF && err != nil {
t.Fatal(err)
}
}
}
if dsn == "" {
t.Skip("no azure database connection string. set AZURESERVER_DSN environment variable or create .azureconnstr file")
}
config, err := parse(dsn)
if err != nil {
t.Skip("error parsing connection string ")
}
if config.fedAuthLibrary == mssql.FedAuthLibraryReserved {
t.Skip("Skipping azure test due to missing fedauth parameter ")
}
config.mssqlConfig.LogFlags = logFlags
return config
}
192 changes: 192 additions & 0 deletions azuread/configuration.go
@@ -0,0 +1,192 @@
package azuread

import (
"context"
"errors"
"fmt"
"strings"

"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
mssql "github.com/denisenkom/go-mssqldb"
"github.com/denisenkom/go-mssqldb/msdsn"
)

const (
ActiveDirectoryDefault = "ActiveDirectoryDefault"
ActiveDirectoryIntegrated = "ActiveDirectoryIntegrated"
ActiveDirectoryPassword = "ActiveDirectoryPassword"
ActiveDirectoryInteractive = "ActiveDirectoryInteractive"
// ActiveDirectoryMSI is a synonym for ActiveDirectoryManagedIdentity
ActiveDirectoryMSI = "ActiveDirectoryMSI"
ActiveDirectoryManagedIdentity = "ActiveDirectoryManagedIdentity"
// ActiveDirectoryApplication is a synonym for ActiveDirectoryServicePrincipal
ActiveDirectoryApplication = "ActiveDirectoryApplication"
ActiveDirectoryServicePrincipal = "ActiveDirectoryServicePrincipal"
scopeDefaultSuffix = "/.default"
)

type azureFedAuthConfig struct {
adalWorkflow byte
mssqlConfig msdsn.Config
// The detected federated authentication library
fedAuthLibrary int
fedAuthWorkflow string
// Service principal logins
clientID string
tenantID string
clientSecret string
certificatePath string

// AD password/managed identity/interactive
user string
password string
applicationClientID string
}

// parse returns a config based on an msdsn-style connection string
func parse(dsn string) (*azureFedAuthConfig, error) {
mssqlConfig, params, err := msdsn.Parse(dsn)
if err != nil {
return nil, err
}
config := &azureFedAuthConfig{
fedAuthLibrary: mssql.FedAuthLibraryReserved,
mssqlConfig: mssqlConfig,
}

err = config.validateParameters(params)
if err != nil {
return nil, err
}

return config, nil
}

func (p *azureFedAuthConfig) validateParameters(params map[string]string) error {

fedAuthWorkflow, _ := params["fedauth"]
if fedAuthWorkflow == "" {
return nil
}

p.fedAuthLibrary = mssql.FedAuthLibraryADAL

p.applicationClientID, _ = params["applicationclientid"]

switch {
case strings.EqualFold(fedAuthWorkflow, ActiveDirectoryPassword):
if p.applicationClientID == "" {
return errors.New("applicationclientid parameter is required for " + ActiveDirectoryPassword)
}
p.adalWorkflow = mssql.FedAuthADALWorkflowPassword
p.user, _ = params["user id"]
p.password, _ = params["password"]
case strings.EqualFold(fedAuthWorkflow, ActiveDirectoryIntegrated):
// Active Directory Integrated authentication is not fully supported:
// you can only use this by also implementing an a token provider
// and supplying it via ActiveDirectoryTokenProvider in the Connection.
p.adalWorkflow = mssql.FedAuthADALWorkflowIntegrated
case strings.EqualFold(fedAuthWorkflow, ActiveDirectoryManagedIdentity) || strings.EqualFold(fedAuthWorkflow, ActiveDirectoryMSI):
// When using MSI, to request a specific client ID or user-assigned identity,
// provide the ID in the "user id" parameter
p.adalWorkflow = mssql.FedAuthADALWorkflowMSI
p.clientID, _ = splitTenantAndClientID(params["user id"])
case strings.EqualFold(fedAuthWorkflow, ActiveDirectoryApplication) || strings.EqualFold(fedAuthWorkflow, ActiveDirectoryServicePrincipal):
p.adalWorkflow = mssql.FedAuthADALWorkflowPassword
// Split the clientID@tenantID format
// If no tenant is provided we'll use the one from the server
p.clientID, p.tenantID = splitTenantAndClientID(params["user id"])
if p.clientID == "" {
return errors.New("Must provide 'client id[@tenant id]' as username parameter when using ActiveDirectoryApplication authentication")
}

p.clientSecret, _ = params["password"]

p.certificatePath, _ = params["clientcertpath"]

if p.certificatePath == "" && p.clientSecret == "" {
return errors.New("Must provide 'password' parameter when using ActiveDirectoryApplication authentication without cert/key credentials")
}
case strings.EqualFold(fedAuthWorkflow, ActiveDirectoryDefault):
p.adalWorkflow = mssql.FedAuthADALWorkflowPassword
case strings.EqualFold(fedAuthWorkflow, ActiveDirectoryInteractive):
if p.applicationClientID == "" {
return errors.New("applicationclientid parameter is required for " + ActiveDirectoryInteractive)
}
p.adalWorkflow = mssql.FedAuthADALWorkflowPassword
// user is an optional login hint
p.user, _ = params["user id"]
// we don't really have a password but we need to use some value.
p.adalWorkflow = mssql.FedAuthADALWorkflowPassword

default:
return fmt.Errorf("Invalid federated authentication type '%s': expected one of %+v",
fedAuthWorkflow,
[]string{ActiveDirectoryApplication, ActiveDirectoryServicePrincipal, ActiveDirectoryDefault, ActiveDirectoryIntegrated, ActiveDirectoryInteractive, ActiveDirectoryManagedIdentity, ActiveDirectoryMSI, ActiveDirectoryPassword})
}
p.fedAuthWorkflow = fedAuthWorkflow
return nil
}

func splitTenantAndClientID(user string) (string, string) {
// Split the user name into client id and tenant id at the @ symbol
at := strings.IndexRune(user, '@')
if at < 1 || at >= (len(user)-1) {
return user, ""
}

return user[0:at], user[at+1:]
}

func splitAuthorityAndTenant(authorityUrl string) (string, string) {
separatorIndex := strings.LastIndex(authorityUrl, "/")
tenant := authorityUrl[separatorIndex+1:]
authority := authorityUrl[:separatorIndex]
return authority, tenant
}

func (p *azureFedAuthConfig) provideActiveDirectoryToken(ctx context.Context, serverSPN, stsURL string) (string, error) {
var cred azcore.TokenCredential
var err error
authority, tenant := splitAuthorityAndTenant(stsURL)
// client secret connection strings may override the server tenant
if p.tenantID != "" {
tenant = p.tenantID
}
scope := stsURL
if !strings.HasSuffix(serverSPN, scopeDefaultSuffix) {
scope = strings.TrimRight(serverSPN, "/") + scopeDefaultSuffix
}

switch p.fedAuthWorkflow {
case ActiveDirectoryServicePrincipal, ActiveDirectoryApplication:
switch {
case p.certificatePath != "":
cred, err = azidentity.NewClientCertificateCredential(tenant, p.clientID, p.certificatePath, &azidentity.ClientCertificateCredentialOptions{Password: p.clientSecret})
default:
cred, err = azidentity.NewClientSecretCredential(tenant, p.clientID, p.clientSecret, nil)
}
case ActiveDirectoryPassword:
cred, err = azidentity.NewUsernamePasswordCredential(tenant, p.applicationClientID, p.user, p.password, nil)
case ActiveDirectoryMSI, ActiveDirectoryManagedIdentity:
cred, err = azidentity.NewManagedIdentityCredential(p.clientID, nil)
case ActiveDirectoryInteractive:
cred, err = azidentity.NewInteractiveBrowserCredential(&azidentity.InteractiveBrowserCredentialOptions{AuthorityHost: authority, ClientID: p.applicationClientID})

default:
// Integrated just uses Default until azidentity adds Windows-specific authentication
cred, err = azidentity.NewDefaultAzureCredential(nil)
}

if err != nil {
return "", err
}
opts := policy.TokenRequestOptions{Scopes: []string{scope}}
tk, err := cred.GetToken(ctx, opts)
if err != nil {
return "", err
}
return tk.Token, err
}