config

package
v2.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 5, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package config provides the Config struct which contains all configuration parameters for the driver and a Validate method to check if the configuration is correct.

Index

Constants

View Source
const (
	// DefaultClientTimeout is the timeout for network round trip + read out http response
	DefaultClientTimeout = 900 * time.Second
	// DefaultJWTClientTimeout is the timeout for network round trip + read out http response but used for JWT auth
	DefaultJWTClientTimeout = 10 * time.Second
	// DefaultLoginTimeout is the timeout for retry for login EXCLUDING clientTimeout
	DefaultLoginTimeout = 300 * time.Second
	// DefaultRequestTimeout is the timeout for retry for request EXCLUDING clientTimeout
	DefaultRequestTimeout = 0 * time.Second
	// DefaultJWTTimeout is the timeout for JWT token expiration
	DefaultJWTTimeout = 60 * time.Second
	// DefaultExternalBrowserTimeout is the timeout for external browser login
	DefaultExternalBrowserTimeout = 120 * time.Second

	// DefaultDomain is the default domain for Snowflake accounts
	DefaultDomain = ".snowflakecomputing.com"
	// CnDomain is the domain for Snowflake accounts in China
	CnDomain = ".snowflakecomputing.cn"
)
View Source
const (

	// SkipTokenFilePermissionsVerificationEnv keeps an env name for skipping token file permission and user verification
	SkipTokenFilePermissionsVerificationEnv = "SKIP_TOKEN_FILE_PERMISSIONS_VERIFICATION"
)

Variables

This section is empty.

Functions

func DSN

func DSN(cfg *Config) (dsn string, err error)

DSN constructs a DSN for Snowflake db.

func DeregisterTLSConfig

func DeregisterTLSConfig(key string) error

DeregisterTLSConfig removes the tls.Config associated with key.

func DescribeIdentityAttributes

func DescribeIdentityAttributes(c *Config) string

DescribeIdentityAttributes returns a string describing the identity attributes of the Config.

func DescribeProxy

func DescribeProxy(c *Config) string

DescribeProxy returns a string describing the proxy configuration.

func DetermineAuthenticatorType

func DetermineAuthenticatorType(cfg *Config, value string) error

DetermineAuthenticatorType parses the authenticator string and sets the Config.Authenticator field.

func ExtractAccountName

func ExtractAccountName(rawAccount string) string

ExtractAccountName extract an account name from a raw account.

func FillMissingConfigParameters

func FillMissingConfigParameters(cfg *Config) error

FillMissingConfigParameters fills in default values for missing config parameters.

func GetFromEnv

func GetFromEnv(name string, failOnMissing bool) (string, error)

GetFromEnv retrieves the value of an environment variable. If failOnMissing is true and the variable is not set, an error is returned.

func GetTLSConfig

func GetTLSConfig(key string) (*tls.Config, bool)

GetTLSConfig returns a TLS config from the registry.

func GetToken

func GetToken(c *Config) (string, error)

GetToken retrieves the token from the Config, reading from file if TokenFilePath is set.

func GetTomlFilePath

func GetTomlFilePath(filePath string) (string, error)

GetTomlFilePath returns the path to the TOML file directory.

func HandleSingleParam

func HandleSingleParam(cfg *Config, key string, value any) error

HandleSingleParam processes a single TOML parameter into a Config.

func MarshalPKCS8PrivateKey

func MarshalPKCS8PrivateKey(key *rsa.PrivateKey) ([]byte, error)

MarshalPKCS8PrivateKey marshals a private key to PKCS8 format.

func OcspMode

func OcspMode(c *Config) string

OcspMode returns the OCSP mode in string INSECURE, FAIL_OPEN, FAIL_CLOSED

func ParseBool

func ParseBool(i any) (bool, error)

ParseBool parses an interface value to bool.

func ParseDuration

func ParseDuration(i any) (time.Duration, error)

ParseDuration parses an interface value to time.Duration.

func ParseInt

func ParseInt(i any) (int, error)

ParseInt parses an interface value to int.

func ParsePKCS8PrivateKey

func ParsePKCS8PrivateKey(block []byte) (*rsa.PrivateKey, error)

ParsePKCS8PrivateKey parses a PKCS8 encoded private key.

func ParseToml

func ParseToml(cfg *Config, connectionMap map[string]any) error

ParseToml parses a TOML connection map into a Config.

func ReadToken

func ReadToken(tokenPath string) (string, error)

ReadToken reads a token from the given path (or default path if empty).

func RegisterTLSConfig

func RegisterTLSConfig(key string, config *tls.Config) error

RegisterTLSConfig registers the tls.Config in configs registry. Use the key as a value in the DSN where tlsConfigName=value.

func ResetTLSConfigRegistry

func ResetTLSConfigRegistry()

ResetTLSConfigRegistry clears the TLS config registry. Used in tests.

func SetInputShape added in v2.1.0

func SetInputShape(c *Config, s *ConnectionIdentifierShape)

SetInputShape overwrites the connection-identifier shape on Config. It is the external write path for the unexported shape field and exists so that tests in the gosnowflake driver package can build Configs with a known shape without going through DSN parsing. Production code paths populate the shape via ParseDSN, LoadConnectionConfig, or FillMissingConfigParameters and should not call this.

func ShouldSkipTokenFilePermissionsVerification added in v2.1.0

func ShouldSkipTokenFilePermissionsVerification() bool

ShouldSkipTokenFilePermissionsVerification reports whether the user has requested bypassing owner/permission checks for connections.toml and the credential cache (file, directory, and lock file). Set the SF_SKIP_TOKEN_FILE_PERMISSIONS_VERIFICATION environment variable to "true" to enable the bypass.

func ValidateFilePermission

func ValidateFilePermission(filePath string) error

ValidateFilePermission checks that a file does not have overly permissive permissions.

Types

type AuthType

type AuthType int

AuthType indicates the type of authentication in Snowflake

const (
	// AuthTypeSnowflake is the general username password authentication
	AuthTypeSnowflake AuthType = iota
	// AuthTypeOAuth is the OAuth authentication
	AuthTypeOAuth
	// AuthTypeExternalBrowser is to use a browser to access an Fed and perform SSO authentication
	AuthTypeExternalBrowser
	// AuthTypeOkta is to use a native okta URL to perform SSO authentication on Okta
	AuthTypeOkta
	// AuthTypeJwt is to use Jwt to perform authentication
	AuthTypeJwt
	// AuthTypeTokenAccessor is to use the provided token accessor and bypass authentication
	AuthTypeTokenAccessor
	// AuthTypeUsernamePasswordMFA is to use username and password with mfa
	AuthTypeUsernamePasswordMFA
	// AuthTypePat is to use programmatic access token
	AuthTypePat
	// AuthTypeOAuthAuthorizationCode is to use browser-based OAuth2 flow
	AuthTypeOAuthAuthorizationCode
	// AuthTypeOAuthClientCredentials is to use non-interactive OAuth2 flow
	AuthTypeOAuthClientCredentials
	// AuthTypeWorkloadIdentityFederation is to use CSP identity for authentication
	AuthTypeWorkloadIdentityFederation
)

func (AuthType) String

func (authType AuthType) String() string

type Bool

type Bool uint8

Bool is a type to represent true or false in the Config

const (
	// BoolNotSet represents the default value for the config field which is not set
	BoolNotSet Bool = iota // Reserved for unset to let default value fall into this category
	// BoolTrue represents true for the config field
	BoolTrue
	// BoolFalse represents false for the config field
	BoolFalse
)

func (Bool) String

func (cb Bool) String() string

type CertRevocationCheckMode

type CertRevocationCheckMode int

CertRevocationCheckMode defines the modes for certificate revocation checks.

const (
	// CertRevocationCheckDisabled means that certificate revocation checks are disabled.
	CertRevocationCheckDisabled CertRevocationCheckMode = iota
	// CertRevocationCheckAdvisory means that certificate revocation checks are advisory, and the driver will not fail if the checks end with error (cannot verify revocation status).
	// Driver will fail only if a certicate is revoked.
	CertRevocationCheckAdvisory
	// CertRevocationCheckEnabled means that every certificate revocation check must pass, otherwise the driver will fail.
	CertRevocationCheckEnabled
)

func ParseCertRevocationCheckMode

func ParseCertRevocationCheckMode(s string) (CertRevocationCheckMode, error)

ParseCertRevocationCheckMode parses a string into a CertRevocationCheckMode.

func (CertRevocationCheckMode) String

func (m CertRevocationCheckMode) String() string

type Config

type Config struct {
	Account   string // Account name
	User      string // Username
	Password  string // Password (requires User)
	Database  string // Database name
	Schema    string // Schema
	Warehouse string // Warehouse
	Role      string // Role
	Region    string // Region

	OauthClientID                string // Client id for OAuth2 external IdP
	OauthClientSecret            string // Client secret for OAuth2 external IdP
	OauthAuthorizationURL        string // Authorization URL of Auth2 external IdP
	OauthTokenRequestURL         string // Token request URL of Auth2 external IdP
	OauthRedirectURI             string // Redirect URI registered in IdP. The default is http://127.0.0.1:<random port>
	OauthScope                   string // Comma separated list of scopes. If empty it is derived from role.
	EnableSingleUseRefreshTokens bool   // Enables single use refresh tokens for Snowflake IdP

	// ValidateDefaultParameters disable the validation checks for Database, Schema, Warehouse and Role
	// at the time a connection is established
	ValidateDefaultParameters Bool

	Params map[string]*string // other connection parameters

	Protocol string // http or https (optional)
	Host     string // hostname (optional)
	Port     int    // port (optional)

	Authenticator              AuthType // The authenticator type
	SingleAuthenticationPrompt Bool     // If enabled prompting for authentication will only occur for the first authentication challenge

	Passcode           string
	PasscodeInPassword bool

	OktaURL *url.URL

	// Deprecated: timeouts may be reorganized in a future release.
	LoginTimeout time.Duration // Login retry timeout EXCLUDING network roundtrip and read out http response
	// Deprecated: timeouts may be reorganized in a future release.
	RequestTimeout time.Duration // request retry timeout EXCLUDING network roundtrip and read out http response
	// Deprecated: timeouts may be reorganized in a future release.
	JWTExpireTimeout time.Duration // JWT expire after timeout
	// Deprecated: timeouts may be reorganized in a future release.
	ClientTimeout time.Duration // Timeout for network round trip + read out http response
	// Deprecated: timeouts may be reorganized in a future release.
	JWTClientTimeout time.Duration // Timeout for network round trip + read out http response used when JWT token auth is taking place
	// Deprecated: timeouts may be reorganized in a future release.
	ExternalBrowserTimeout time.Duration // Timeout for external browser login
	// Deprecated: timeouts may be reorganized in a future release.
	CloudStorageTimeout time.Duration // Timeout for a single call to a cloud storage provider
	MaxRetryCount       int           // Specifies how many times non-periodic HTTP request can be retried

	Application       string           // application name.
	DisableOCSPChecks bool             // driver doesn't check certificate revocation status
	OCSPFailOpen      OCSPFailOpenMode // OCSP Fail Open

	Token                  string        // Token to use for OAuth other forms of token based auth
	TokenFilePath          string        // TokenFilePath defines a file where to read token from
	TokenAccessor          TokenAccessor // TokenAccessor Optional token accessor to use
	ServerSessionKeepAlive bool          // ServerSessionKeepAlive enables the session to persist even after the driver connection is closed

	PrivateKey *rsa.PrivateKey // Private key used to sign JWT

	Transporter http.RoundTripper // RoundTripper to intercept HTTP requests and responses

	TLSConfigName string // Name of the TLS config to use

	// Deprecated: may be removed in a future release with logging reorganization.
	Tracing            string // sets logging level
	LogQueryText       bool   // indicates whether query text should be logged.
	LogQueryParameters bool   // indicates whether query parameters should be logged.

	TmpDirPath string // sets temporary directory used by a driver for operations like encrypting, compressing etc

	ClientRequestMfaToken          Bool // When true the MFA token is cached in the credential manager. True by default in Windows/OSX. False for Linux.
	ClientStoreTemporaryCredential Bool // When true the ID token is cached in the credential manager. True by default in Windows/OSX. False for Linux.

	DisableQueryContextCache bool // Should HTAP query context cache be disabled

	IncludeRetryReason Bool // Should retried request contain retry reason

	ClientConfigFile string // File path to the client configuration json file

	DisableConsoleLogin Bool // Indicates whether console login should be disabled

	DisableSamlURLCheck Bool // Indicates whether the SAML URL check should be disabled

	WorkloadIdentityProvider          string   // The workload identity provider to use for WIF authentication
	WorkloadIdentityEntraResource     string   // The resource to use for WIF authentication on Azure environment
	WorkloadIdentityImpersonationPath []string // The components to use for WIF impersonation.

	CertRevocationCheckMode           CertRevocationCheckMode // revocation check mode for CRLs
	CrlAllowCertificatesWithoutCrlURL Bool                    // Allow certificates (not short-lived) without CRL DP included to be treated as correct ones
	CrlInMemoryCacheDisabled          bool                    // Should the in-memory cache be disabled
	CrlOnDiskCacheDisabled            bool                    // Should the on-disk cache be disabled
	CrlDownloadMaxSize                int                     // Max size in bytes of CRL to download. 0 means use default (20MB).
	CrlHTTPClientTimeout              time.Duration           // Timeout for HTTP client used to download CRL

	ConnectionDiagnosticsEnabled       bool   // Indicates whether connection diagnostics should be enabled
	ConnectionDiagnosticsAllowlistFile string // File path to the allowlist file for connection diagnostics. If not specified, the allowlist.json file in the current directory will be used.

	ProxyHost     string // Proxy host
	ProxyPort     int    // Proxy port
	ProxyUser     string // Proxy user
	ProxyPassword string // Proxy password
	ProxyProtocol string // Proxy protocol (http or https)
	NoProxy       string // No proxy for this host list
	// contains filtered or unexported fields
}

Config is a set of configuration parameters

func GetConfigFromEnv

func GetConfigFromEnv(properties []*Param) (*Config, error)

GetConfigFromEnv is used to parse the environment variable values to specific fields of the Config

func LoadConnectionConfig

func LoadConnectionConfig() (*Config, error)

LoadConnectionConfig returns connection configs loaded from the toml file. By default, SNOWFLAKE_HOME(toml file path) is os.snowflakeHome/.snowflake and SNOWFLAKE_DEFAULT_CONNECTION_NAME(DSN) is 'default'

func ParseDSN

func ParseDSN(dsn string) (cfg *Config, err error)

ParseDSN parses the DSN string to a Config.

func (*Config) Validate

func (c *Config) Validate() error

Validate enables testing if config is correct. A driver client may call it manually, but it is also called during opening first connection.

type ConnectionIdentifierShape added in v2.1.0

type ConnectionIdentifierShape struct {
	AccountProvided    bool
	AccountWithRegion  bool // raw account string contains '.'
	AccountOrgProvided bool // raw account string contains '-'
	RegionProvided     bool
	HostProvided       bool
}

ConnectionIdentifierShape captures the *shape* of the connection identifier the user supplied: which of {account, region, host} they actually set, and whether the raw account string they typed contained the substrings that signal an "account.region" form (dot) or an "org-account" form (dash).

Fields reflect user intent at the moment of input, not the final post-normalization state of Config. For example, if a user supplies only "myorg-myacct" as the account, the driver will later synthesize a Host — AccountProvided will be true and HostProvided will remain false.

func InputShapeOf added in v2.1.0

func InputShapeOf(c *Config) *ConnectionIdentifierShape

InputShapeOf returns the connection-identifier shape captured during DSN parsing, TOML loading, or programmatic Config setup. Returns nil when shape capture has not run; callers must nil-check.

This is the only external read path for Config's unexported shape field; the gosnowflake driver package uses it at post-login telemetry-emit time.

type OCSPFailOpenMode

type OCSPFailOpenMode uint32

OCSPFailOpenMode is OCSP fail open mode. OCSPFailOpenTrue by default and may set to ocspModeFailClosed for fail closed mode

const (
	// OCSPFailOpenNotSet represents OCSP fail open mode is not set, which is the default value.
	OCSPFailOpenNotSet OCSPFailOpenMode = iota
	// OCSPFailOpenTrue represents OCSP fail open mode.
	OCSPFailOpenTrue
	// OCSPFailOpenFalse represents OCSP fail closed mode.
	OCSPFailOpenFalse
)

type Param

type Param struct {
	Name          string
	EnvName       string
	FailOnMissing bool
}

Param binds Config field names to environment variable names.

type TokenAccessor

type TokenAccessor interface {
	GetTokens() (token string, masterToken string, sessionID int64)
	SetTokens(token string, masterToken string, sessionID int64)
	Lock() error
	Unlock()
}

TokenAccessor manages the session token and master token

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL