-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnowflake.go
More file actions
434 lines (360 loc) · 12 KB
/
snowflake.go
File metadata and controls
434 lines (360 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
// Copyright 2026 Snowflake Inc.
// SPDX-License-Identifier: MPL-2.0
package snowflake
import (
"context"
"database/sql"
"fmt"
"math"
"strings"
"time"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/go-secure-stdlib/strutil"
"github.com/hashicorp/vault/sdk/database/dbplugin/v5"
"github.com/hashicorp/vault/sdk/database/helper/dbutil"
"github.com/hashicorp/vault/sdk/helper/dbtxn"
"github.com/hashicorp/vault/sdk/helper/template"
_ "github.com/snowflakedb/gosnowflake"
)
const (
snowflakeSQLTypeName = "snowflake"
defaultSnowflakeRenewSQL = `
alter user {{name}} set DAYS_TO_EXPIRY = {{expiration}};
`
defaultSnowflakeRotatePasswordSQL = `
alter user {{name}} set PASSWORD = '{{password}}';
`
defaultSnowflakeRotateRSAPublicKeySQL = `
alter user {{name}} set RSA_PUBLIC_KEY = '{{public_key}}';
`
defaultSnowflakeDeleteSQL = `
drop user if exists {{name}};
`
defaultUserNameTemplate = `{{ printf "v_%s_%s_%s_%s" (.DisplayName | truncate 32) (.RoleName | truncate 32) (random 20) (unix_time) | truncate 255 | replace "-" "_" }}`
// defaultCortexUserCreationSQL creates a minimal Snowflake user suitable for
// Cortex access using RSA key-pair authentication. This is the recommended
// credential type for Cortex CLI and API integrations.
//
// Use with credential_type=rsa_private_key on the Vault role.
defaultCortexUserCreationSQL = `
CREATE USER "{{name}}"
LOGIN_NAME = '{{name}}'
RSA_PUBLIC_KEY = '{{public_key}}'
DEFAULT_ROLE = 'PUBLIC'
DAYS_TO_EXPIRY = {{expiration}}
COMMENT = 'Vault-managed Cortex user';
`
// defaultCortexGrantSQL grants the SNOWFLAKE.CORTEX_USER database role to a
// user, enabling access to Snowflake Cortex LLM functions (COMPLETE, SUMMARIZE,
// SENTIMENT, TRANSLATE, EMBED_TEXT_*) and the Cortex CLI.
//
// This statement is automatically appended when cortex_access=true is set on
// the database connection config.
//
// Docs: https://docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-finetuning/set-up-cortex-finetuning#grant-the-cortex-user-database-role-to-a-snowflake-user
defaultCortexGrantSQL = `
GRANT DATABASE ROLE SNOWFLAKE.CORTEX_USER TO USER "{{name}}";
`
)
var _ dbplugin.Database = (*SnowflakeSQL)(nil)
func New() (interface{}, error) {
db := new()
// Wrap the plugin with middleware to sanitize errors
dbType := dbplugin.NewDatabaseErrorSanitizerMiddleware(db, db.secretValues)
return dbType, nil
}
func new() *SnowflakeSQL {
connProducer := &snowflakeConnectionProducer{}
connProducer.Type = snowflakeSQLTypeName
db := &SnowflakeSQL{
snowflakeConnectionProducer: connProducer,
}
return db
}
type SnowflakeSQL struct {
*snowflakeConnectionProducer
usernameProducer template.StringTemplate
}
func (s *SnowflakeSQL) Type() (string, error) {
return snowflakeSQLTypeName, nil
}
func (s *SnowflakeSQL) getConnection(ctx context.Context) (*sql.DB, error) {
db, err := s.Connection(ctx)
if err != nil {
return nil, err
}
return db.(*sql.DB), nil
}
func (s *SnowflakeSQL) Initialize(ctx context.Context, req dbplugin.InitializeRequest) (dbplugin.InitializeResponse, error) {
err := s.snowflakeConnectionProducer.Initialize(ctx, req.Config, req.VerifyConnection)
if err != nil {
return dbplugin.InitializeResponse{}, err
}
usernameTemplate, err := strutil.GetString(req.Config, "username_template")
if err != nil {
return dbplugin.InitializeResponse{}, fmt.Errorf("failed to retrieve username_template: %w", err)
}
if usernameTemplate == "" {
usernameTemplate = defaultUserNameTemplate
}
up, err := template.NewTemplate(template.Template(usernameTemplate))
if err != nil {
return dbplugin.InitializeResponse{}, fmt.Errorf("unable to initialize username template: %w", err)
}
s.usernameProducer = up
_, err = s.usernameProducer.Generate(dbplugin.UsernameMetadata{})
if err != nil {
return dbplugin.InitializeResponse{}, fmt.Errorf("invalid username template: %w", err)
}
resp := dbplugin.InitializeResponse{
Config: req.Config,
}
resp.SetSupportedCredentialTypes([]dbplugin.CredentialType{
dbplugin.CredentialTypePassword,
dbplugin.CredentialTypeRSAPrivateKey,
})
return resp, nil
}
func (s *SnowflakeSQL) NewUser(ctx context.Context, req dbplugin.NewUserRequest) (dbplugin.NewUserResponse, error) {
s.mu.RLock()
defer s.mu.RUnlock()
statements := req.Statements.Commands
if len(statements) == 0 {
return dbplugin.NewUserResponse{}, dbutil.ErrEmptyCreationStatement
}
username, err := s.generateUsername(req)
if err != nil {
return dbplugin.NewUserResponse{}, err
}
expirationStr, err := calculateExpirationString(req.Expiration)
if err != nil {
return dbplugin.NewUserResponse{}, err
}
// Get the connection
db, err := s.getConnection(ctx)
if err != nil {
return dbplugin.NewUserResponse{}, err
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return dbplugin.NewUserResponse{}, err
}
defer tx.Rollback()
m := map[string]string{
"name": username,
"username": username,
"expiration": expirationStr,
}
switch req.CredentialType {
case dbplugin.CredentialTypePassword:
m["password"] = req.Password
case dbplugin.CredentialTypeRSAPrivateKey:
m["public_key"] = preparePublicKey(string(req.PublicKey))
default:
return dbplugin.NewUserResponse{}, fmt.Errorf("unsupported credential type %q",
req.CredentialType.String())
}
// Execute each query
for _, stmt := range statements {
// it's fine to split the statements on the semicolon.
for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") {
query = strings.TrimSpace(query)
if len(query) == 0 {
continue
}
if err := dbtxn.ExecuteTxQueryDirect(ctx, tx, m, query); err != nil {
return dbplugin.NewUserResponse{}, err
}
}
}
// When cortex_access is enabled on the connection config, automatically
// grant SNOWFLAKE.CORTEX_USER to the new user so it can call Cortex LLM
// functions and use the Cortex CLI without extra manual setup.
if s.snowflakeConnectionProducer.CortexAccess {
for _, query := range strutil.ParseArbitraryStringSlice(defaultCortexGrantSQL, ";") {
query = strings.TrimSpace(query)
if len(query) == 0 {
continue
}
if err := dbtxn.ExecuteTxQueryDirect(ctx, tx, m, query); err != nil {
return dbplugin.NewUserResponse{}, fmt.Errorf("failed to grant Cortex access to user %q: %w", username, err)
}
}
}
err = tx.Commit()
resp := dbplugin.NewUserResponse{
Username: username,
}
return resp, err
}
func (s *SnowflakeSQL) generateUsername(req dbplugin.NewUserRequest) (string, error) {
username, err := s.usernameProducer.Generate(req.UsernameConfig)
if err != nil {
return "", errwrap.Wrapf("error generating username: {{err}}", err)
}
return username, nil
}
func (s *SnowflakeSQL) UpdateUser(ctx context.Context, req dbplugin.UpdateUserRequest) (dbplugin.UpdateUserResponse, error) {
s.mu.RLock()
defer s.mu.RUnlock()
if req.Username == "" {
err := fmt.Errorf("a username must be provided to update a user")
return dbplugin.UpdateUserResponse{}, err
}
db, err := s.getConnection(ctx)
if err != nil {
return dbplugin.UpdateUserResponse{}, err
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return dbplugin.UpdateUserResponse{}, err
}
defer tx.Rollback()
if req.Password != nil || req.PublicKey != nil {
err = s.updateUserCredential(ctx, tx, req)
if err != nil {
return dbplugin.UpdateUserResponse{}, err
}
}
if req.Expiration != nil {
err = s.updateUserExpiration(ctx, tx, req.Username, req.Expiration)
if err != nil {
return dbplugin.UpdateUserResponse{}, err
}
}
if err := tx.Commit(); err != nil {
return dbplugin.UpdateUserResponse{}, err
}
return dbplugin.UpdateUserResponse{}, nil
}
func (s *SnowflakeSQL) updateUserCredential(ctx context.Context, tx *sql.Tx, req dbplugin.UpdateUserRequest) error {
m := map[string]string{
"name": req.Username,
"username": req.Username,
}
var stmts []string
switch req.CredentialType {
case dbplugin.CredentialTypePassword:
if req.Password == nil || req.Password.NewPassword == "" {
return fmt.Errorf("new password credential must not be empty")
}
stmts = req.Password.Statements.Commands
if len(stmts) == 0 {
stmts = []string{defaultSnowflakeRotatePasswordSQL}
}
m["password"] = req.Password.NewPassword
case dbplugin.CredentialTypeRSAPrivateKey:
if req.PublicKey == nil || len(req.PublicKey.NewPublicKey) == 0 {
return fmt.Errorf("new public key credential must not be empty")
}
stmts = req.PublicKey.Statements.Commands
if len(stmts) == 0 {
stmts = []string{defaultSnowflakeRotateRSAPublicKeySQL}
}
m["public_key"] = preparePublicKey(string(req.PublicKey.NewPublicKey))
default:
return fmt.Errorf("unsupported credential type %q", req.CredentialType.String())
}
for _, stmt := range stmts {
for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") {
query = strings.TrimSpace(query)
if len(query) == 0 {
continue
}
if err := dbtxn.ExecuteTxQueryDirect(ctx, tx, m, query); err != nil {
return fmt.Errorf("failed to execute query: %w", err)
}
}
}
return nil
}
func (s *SnowflakeSQL) updateUserExpiration(ctx context.Context, tx *sql.Tx, username string, req *dbplugin.ChangeExpiration) error {
expiration := req.NewExpiration
if username == "" || expiration.IsZero() {
return fmt.Errorf("must provide both username and valid expiration to modify expiration")
}
expirationStr, err := calculateExpirationString(expiration)
if err != nil {
return err
}
stmts := req.Statements.Commands
if len(stmts) == 0 {
stmts = []string{defaultSnowflakeRenewSQL}
}
for _, stmt := range stmts {
for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") {
query = strings.TrimSpace(query)
if len(query) == 0 {
continue
}
m := map[string]string{
"name": username,
"username": username,
"expiration": expirationStr,
}
if err := dbtxn.ExecuteTxQueryDirect(ctx, tx, m, query); err != nil {
return fmt.Errorf("failed to execute query: %w", err)
}
}
}
return nil
}
func (s *SnowflakeSQL) DeleteUser(ctx context.Context, req dbplugin.DeleteUserRequest) (dbplugin.DeleteUserResponse, error) {
s.mu.RLock()
defer s.mu.RUnlock()
username := req.Username
statements := req.Statements.Commands
if len(statements) == 0 {
statements = []string{defaultSnowflakeDeleteSQL}
}
db, err := s.getConnection(ctx)
if err != nil {
return dbplugin.DeleteUserResponse{}, err
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return dbplugin.DeleteUserResponse{}, err
}
defer tx.Rollback()
for _, stmt := range statements {
for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") {
query = strings.TrimSpace(query)
if len(query) == 0 {
continue
}
m := map[string]string{
"name": username,
"username": username,
}
if err := dbtxn.ExecuteTxQueryDirect(ctx, tx, m, query); err != nil {
return dbplugin.DeleteUserResponse{}, err
}
}
}
err = tx.Commit()
return dbplugin.DeleteUserResponse{}, err
}
// calculateExpirationString has a minimum expiration of 1 Day. This
// limitation is due to Snowflake requiring any expiration to be in
// terms of days, with 1 being the minimum.
func calculateExpirationString(expiration time.Time) (string, error) {
currentTime := time.Now()
if currentTime.Before(expiration) {
timeDiff := expiration.Sub(currentTime)
inSeconds := timeDiff.Seconds()
inDays := math.Max(math.Floor(inSeconds/float64(60*60*24)), 1)
expirationStr := fmt.Sprintf("%d", int(inDays))
return expirationStr, nil
} else {
err := fmt.Errorf("expiration time earlier than current time")
return "", err
}
}
// preparePublicKey strips the BEGIN and END lines from the given PEM string.
// This is required by Snowflake when setting the RSA_PUBLIC_KEY credential per
// the statement "Exclude the public key delimiters in the SQL statement" in
// https://docs.snowflake.com/en/user-guide/key-pair-auth.html#step-4-assign-the-public-key-to-a-snowflake-user
func preparePublicKey(pub string) string {
pub = strings.Replace(pub, "-----BEGIN PUBLIC KEY-----\n", "", 1)
return strings.Replace(pub, "-----END PUBLIC KEY-----\n", "", 1)
}