github.com/ydb-platform/ydb-go-sdk/v3@v3.57.0/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  	"github.com/ydb-platform/ydb-go-sdk/v3/internal/version"
    21  )
    22  
    23  func TestStaticCredentials(t *testing.T) {
    24  	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
    25  	defer cancel()
    26  
    27  	var dsn string
    28  	if v, has := os.LookupEnv("YDB_CONNECTION_STRING"); !has {
    29  		t.Fatal("env YDB_CONNECTION_STRING required")
    30  	} else {
    31  		dsn = v
    32  	}
    33  
    34  	u, err := url.Parse(dsn)
    35  	if err != nil {
    36  		t.Fatal(err)
    37  	}
    38  
    39  	if version.Gte(os.Getenv("YDB_VERSION"), "23.3") {
    40  		u.User = url.UserPassword("root", "1234")
    41  	} else {
    42  		u.User = url.User("root")
    43  	}
    44  
    45  	staticCredentials := credentials.NewStaticCredentials(u.User.Username(), func() string {
    46  		password, _ := u.User.Password()
    47  		return password
    48  	}(), u.Host, credentials.WithGrpcDialOptions(func() grpc.DialOption {
    49  		if u.Scheme == "grpcs" {
    50  			transportCredentials, transportCredentialsErr := grpcCredentials.NewClientTLSFromFile(
    51  				os.Getenv("YDB_SSL_ROOT_CERTIFICATES_FILE"), u.Hostname(),
    52  			)
    53  			if err != nil {
    54  				t.Fatalf("cannot create transport credentials: %v", transportCredentialsErr)
    55  			}
    56  			return grpc.WithTransportCredentials(transportCredentials)
    57  		}
    58  		return grpc.WithTransportCredentials(insecure.NewCredentials())
    59  	}()))
    60  
    61  	token, err := staticCredentials.Token(ctx)
    62  	require.NoError(t, err)
    63  
    64  	t.Logf("token: %s\n", token)
    65  
    66  	db, err := ydb.Open(ctx,
    67  		"", // corner case for check replacement of endpoint+database+secure
    68  		ydb.WithConnectionString(os.Getenv("YDB_CONNECTION_STRING")),
    69  		ydb.WithCredentials(staticCredentials),
    70  	)
    71  	if err != nil {
    72  		t.Fatal(err)
    73  	}
    74  	defer func() {
    75  		// cleanup connection
    76  		if e := db.Close(ctx); e != nil {
    77  			t.Fatalf("close failed: %+v", e)
    78  		}
    79  	}()
    80  	_, err = db.Discovery().WhoAmI(ctx)
    81  	if err != nil {
    82  		t.Fatal(err)
    83  	}
    84  }