Skip to content

Commit

Permalink
Create shared auth package for SQL Server (dapr#3304)
Browse files Browse the repository at this point in the history
Signed-off-by: ItalyPaleAle <[email protected]>
  • Loading branch information
ItalyPaleAle authored Jan 8, 2024
1 parent e581f3c commit be9d23e
Show file tree
Hide file tree
Showing 9 changed files with 459 additions and 230 deletions.
126 changes: 126 additions & 0 deletions common/authentication/sqlserver/metadata.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
Copyright 2023 The Dapr Authors
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.
*/

package sqlserver

import (
"context"
"errors"
"fmt"
"unicode"

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

"github.com/dapr/components-contrib/common/authentication/azure"
)

// SQLServerAuthMetadata contains the auth metadata for a SQL Server component.
type SQLServerAuthMetadata struct {
ConnectionString string `mapstructure:"connectionString" mapstructurealiases:"url"`
DatabaseName string `mapstructure:"databaseName" mapstructurealiases:"database"`
SchemaName string `mapstructure:"schemaName" mapstructurealiases:"schema"`
UseAzureAD bool `mapstructure:"useAzureAD"`

azureEnv azure.EnvironmentSettings
}

// Reset the object
func (m *SQLServerAuthMetadata) Reset() {
m.ConnectionString = ""
m.DatabaseName = "dapr"
m.SchemaName = "dbo"
m.UseAzureAD = false
}

// Validate the auth metadata and returns an error if it's not valid.
func (m *SQLServerAuthMetadata) Validate(meta map[string]string) (err error) {
// Validate and sanitize input
if m.ConnectionString == "" {
return errors.New("missing connection string")
}
if !IsValidSQLName(m.DatabaseName) {
return fmt.Errorf("invalid database name, accepted characters are (A-Z, a-z, 0-9, _)")
}
if !IsValidSQLName(m.SchemaName) {
return fmt.Errorf("invalid schema name, accepted characters are (A-Z, a-z, 0-9, _)")
}

// If using Azure AD
if m.UseAzureAD {
m.azureEnv, err = azure.NewEnvironmentSettings(meta)
if err != nil {
return err
}
}

return nil
}

// GetConnector returns the connector from the connection string or Azure AD.
// The returned connector can be used with sql.OpenDB.
func (m *SQLServerAuthMetadata) GetConnector(setDatabase bool) (*mssql.Connector, bool, error) {
// Parse the connection string
config, err := msdsn.Parse(m.ConnectionString)
if err != nil {
return nil, false, fmt.Errorf("failed to parse connection string: %w", err)
}

// If setDatabase is true and the configuration (i.e. the connection string) does not contain a database, add it
// This is for backwards-compatibility reasons
if setDatabase && config.Database == "" {
config.Database = m.DatabaseName
}

// We need to check if the configuration has a database because the migrator needs it
hasDatabase := config.Database != ""

// Configure Azure AD authentication if needed
if m.UseAzureAD {
tokenCred, errToken := m.azureEnv.GetTokenCredential()
if errToken != nil {
return nil, false, errToken
}

conn, err := mssql.NewSecurityTokenConnector(config, func(ctx context.Context) (string, error) {
at, err := tokenCred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string{
m.azureEnv.Cloud.Services[azure.ServiceAzureSQL].Audience,
},
})
if err != nil {
return "", err
}
return at.Token, nil
})
return conn, hasDatabase, err
}

conn := mssql.NewConnectorConfig(config)
return conn, hasDatabase, nil
}

func IsLetterOrNumber(c rune) bool {
return unicode.IsNumber(c) || unicode.IsLetter(c)
}

func IsValidSQLName(s string) bool {
for _, c := range s {
if !(IsLetterOrNumber(c) || (c == '_')) {
return false
}
}

return true
}
130 changes: 21 additions & 109 deletions state/sqlserver/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,103 +14,79 @@ limitations under the License.
package sqlserver

import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"unicode"

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

"github.com/dapr/components-contrib/common/authentication/azure"
sqlserverAuth "github.com/dapr/components-contrib/common/authentication/sqlserver"
"github.com/dapr/kit/metadata"
"github.com/dapr/kit/ptr"
)

const (
connectionStringKey = "connectionString"
tableNameKey = "tableName"
metadataTableNameKey = "metadataTableName"
schemaKey = "schema"
keyTypeKey = "keyType"
keyLengthKey = "keyLength"
indexedPropertiesKey = "indexedProperties"
keyColumnName = "Key"
rowVersionColumnName = "RowVersion"
databaseNameKey = "databaseName"
cleanupIntervalKey = "cleanupIntervalInSeconds"

defaultKeyLength = 200
defaultSchema = "dbo"
defaultDatabase = "dapr"
defaultTable = "state"
defaultMetaTable = "dapr_metadata"
defaultCleanupInterval = time.Hour
)

type sqlServerMetadata struct {
ConnectionString string
DatabaseName string
sqlserverAuth.SQLServerAuthMetadata `mapstructure:",squash"`

TableName string
MetadataTableName string
Schema string
KeyType string
KeyLength int
IndexedProperties string
CleanupInterval *time.Duration `mapstructure:"cleanupIntervalInSeconds"`
UseAzureAD bool `mapstructure:"useAzureAD"`
CleanupInterval *time.Duration `mapstructure:"cleanupInterval" mapstructurealiases:"cleanupIntervalInSeconds"`

// Internal properties
keyTypeParsed KeyType
keyLengthParsed int
indexedPropertiesParsed []IndexedProperty
azureEnv azure.EnvironmentSettings
}

func newMetadata() sqlServerMetadata {
return sqlServerMetadata{
TableName: defaultTable,
Schema: defaultSchema,
DatabaseName: defaultDatabase,
KeyLength: defaultKeyLength,
MetadataTableName: defaultMetaTable,
CleanupInterval: ptr.Of(defaultCleanupInterval),
}
}

func (m *sqlServerMetadata) Parse(meta map[string]string) error {
// Reset first
m.SQLServerAuthMetadata.Reset()

// Decode the metadata
err := metadata.DecodeMetadata(meta, &m)
if err != nil {
return err
}
if m.ConnectionString == "" {
return errors.New("missing connection string")

// Validate and parse the auth metadata
err = m.SQLServerAuthMetadata.Validate(meta)
if err != nil {
return err
}

if !isValidSQLName(m.TableName) {
// Validate and sanitize more values
if !sqlserverAuth.IsValidSQLName(m.TableName) {
return fmt.Errorf("invalid table name, accepted characters are (A-Z, a-z, 0-9, _)")
}

if !isValidSQLName(m.MetadataTableName) {
if !sqlserverAuth.IsValidSQLName(m.MetadataTableName) {
return fmt.Errorf("invalid metadata table name, accepted characters are (A-Z, a-z, 0-9, _)")
}

if !isValidSQLName(m.DatabaseName) {
return fmt.Errorf("invalid database name, accepted characters are (A-Z, a-z, 0-9, _)")
}

err = m.setKeyType()
if err != nil {
return err
}

if !isValidSQLName(m.Schema) {
return fmt.Errorf("invalid schema name, accepted characters are (A-Z, a-z, 0-9, _)")
}

err = m.setIndexedProperties()
if err != nil {
return err
Expand All @@ -120,7 +96,8 @@ func (m *sqlServerMetadata) Parse(meta map[string]string) error {
if m.CleanupInterval != nil {
// Non-positive value from meta means disable auto cleanup.
if *m.CleanupInterval <= 0 {
if meta[cleanupIntervalKey] == "" {
val, _ := metadata.GetMetadataProperty(meta, "cleanupInterval", "cleanupIntervalInSeconds")
if val == "" {
// Unfortunately the mapstructure decoder decodes an empty string to 0, a missing key would be nil however
m.CleanupInterval = ptr.Of(defaultCleanupInterval)
} else {
Expand All @@ -129,60 +106,9 @@ func (m *sqlServerMetadata) Parse(meta map[string]string) error {
}
}

// If using Azure AD
if m.UseAzureAD {
m.azureEnv, err = azure.NewEnvironmentSettings(meta)
if err != nil {
return err
}
}

return nil
}

// GetConnector returns the connector from the connection string or Azure AD.
// The returned connector can be used with sql.OpenDB.
func (m *sqlServerMetadata) GetConnector(setDatabase bool) (*mssql.Connector, bool, error) {
// Parse the connection string
config, err := msdsn.Parse(m.ConnectionString)
if err != nil {
return nil, false, fmt.Errorf("failed to parse connection string: %w", err)
}

// If setDatabase is true and the configuration (i.e. the connection string) does not contain a database, add it
// This is for backwards-compatibility reasons
if setDatabase && config.Database == "" {
config.Database = m.DatabaseName
}

// We need to check if the configuration has a database because the migrator needs it
hasDatabase := config.Database != ""

// Configure Azure AD authentication if needed
if m.UseAzureAD {
tokenCred, errToken := m.azureEnv.GetTokenCredential()
if errToken != nil {
return nil, false, errToken
}

conn, err := mssql.NewSecurityTokenConnector(config, func(ctx context.Context) (string, error) {
at, err := tokenCred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string{
m.azureEnv.Cloud.Services[azure.ServiceAzureSQL].Audience,
},
})
if err != nil {
return "", err
}
return at.Token, nil
})
return conn, hasDatabase, err
}

conn := mssql.NewConnectorConfig(config)
return conn, hasDatabase, nil
}

// Validates and returns the key type.
func (m *sqlServerMetadata) setKeyType() error {
if m.KeyType != "" {
Expand Down Expand Up @@ -247,7 +173,7 @@ func (m *sqlServerMetadata) validateIndexedProperties(indexedProperties []Indexe
return errors.New("indexed property type cannot be empty")
}

if !isValidSQLName(p.ColumnName) {
if !sqlserverAuth.IsValidSQLName(p.ColumnName) {
return fmt.Errorf("invalid indexed property column name, accepted characters are (A-Z, a-z, 0-9, _)")
}

Expand All @@ -263,23 +189,9 @@ func (m *sqlServerMetadata) validateIndexedProperties(indexedProperties []Indexe
return nil
}

func isLetterOrNumber(c rune) bool {
return unicode.IsNumber(c) || unicode.IsLetter(c)
}

func isValidSQLName(s string) bool {
for _, c := range s {
if !(isLetterOrNumber(c) || (c == '_')) {
return false
}
}

return true
}

func isValidIndexedPropertyName(s string) bool {
for _, c := range s {
if !(isLetterOrNumber(c) || (c == '_') || (c == '.') || (c == '[') || (c == ']')) {
if !(sqlserverAuth.IsLetterOrNumber(c) || (c == '_') || (c == '.') || (c == '[') || (c == ']')) {
return false
}
}
Expand All @@ -289,7 +201,7 @@ func isValidIndexedPropertyName(s string) bool {

func isValidIndexedPropertyType(s string) bool {
for _, c := range s {
if !(isLetterOrNumber(c) || (c == '(') || (c == ')')) {
if !(sqlserverAuth.IsLetterOrNumber(c) || (c == '(') || (c == ')')) {
return false
}
}
Expand Down
4 changes: 2 additions & 2 deletions state/sqlserver/metadata.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ metadata:
"dapr_metadata"
default: |
"dapr_metadata"
- name: schema
- name: schemaName
description: |
The schema to use.
example: |
Expand Down Expand Up @@ -93,7 +93,7 @@ metadata:
List of indexed properties, as a string containing a JSON document.
example: |
'[{"column": "transactionid", "property": "id", "type": "int"}, {"column": "customerid", "property": "customer", "type": "nvarchar(100)"}]'
- name: cleanupIntervalInSeconds
- name: cleanupInterval
type: number
description: |
Interval, in seconds, to clean up rows with an expired TTL. Default: 3600 (i.e. 1 hour).
Expand Down
Loading

0 comments on commit be9d23e

Please sign in to comment.