github.com/ydb-platform/ydb-go-sdk/v3@v3.89.2/tests/integration/static_credentials_test.go (about) 1 //go:build integration 2 // +build integration 3 4 package integration 5 6 import ( 7 "context" 8 "net/url" 9 "os" 10 "testing" 11 "time" 12 13 "github.com/stretchr/testify/require" 14 "google.golang.org/grpc" 15 grpcCredentials "google.golang.org/grpc/credentials" 16 "google.golang.org/grpc/credentials/insecure" 17 18 "github.com/ydb-platform/ydb-go-sdk/v3" 19 "github.com/ydb-platform/ydb-go-sdk/v3/credentials" 20 ) 21 22 func TestStaticCredentials(t *testing.T) { 23 ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) 24 defer cancel() 25 26 var dsn string 27 if v, has := os.LookupEnv("YDB_CONNECTION_STRING"); !has { 28 t.Fatal("env YDB_CONNECTION_STRING required") 29 } else { 30 dsn = v 31 } 32 33 u, err := url.Parse(dsn) 34 if err != nil { 35 t.Fatal(err) 36 } 37 38 u.User = url.UserPassword("root", "1234") 39 40 staticCredentials := credentials.NewStaticCredentials(u.User.Username(), func() string { 41 password, _ := u.User.Password() 42 return password 43 }(), u.Host, credentials.WithGrpcDialOptions(func() grpc.DialOption { 44 if u.Scheme == "grpcs" { 45 transportCredentials, transportCredentialsErr := grpcCredentials.NewClientTLSFromFile( 46 os.Getenv("YDB_SSL_ROOT_CERTIFICATES_FILE"), u.Hostname(), 47 ) 48 if err != nil { 49 t.Fatalf("cannot create transport credentials: %v", transportCredentialsErr) 50 } 51 return grpc.WithTransportCredentials(transportCredentials) 52 } 53 return grpc.WithTransportCredentials(insecure.NewCredentials()) 54 }())) 55 56 token, err := staticCredentials.Token(ctx) 57 require.NoError(t, err) 58 59 t.Logf("token: %s\n", token) 60 61 db, err := ydb.Open(ctx, 62 os.Getenv("YDB_CONNECTION_STRING"), 63 ydb.WithCredentials(staticCredentials), 64 ) 65 if err != nil { 66 t.Fatal(err) 67 } 68 defer func() { 69 // cleanup connection 70 if e := db.Close(ctx); e != nil { 71 t.Fatalf("close failed: %+v", e) 72 } 73 }() 74 _, err = db.Discovery().WhoAmI(ctx) 75 if err != nil { 76 t.Fatal(err) 77 } 78 }