Skip to content

fix api token initialization #722

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ func NewClientWithAddressContext(ctx context.Context, address string) (client Cl
return nil, fmt.Errorf("error parsing address '%s': %w", address, err)
}

at := &authToken{}
at := newAuthToken()

opts := []grpc.DialOption{
grpc.WithUserAgent(userAgent()),
Expand Down Expand Up @@ -404,7 +404,7 @@ func NewClientWithSocket(socket string) (client Client, err error) {
if socket == "" {
return nil, errors.New("nil socket")
}
at := &authToken{}
at := newAuthToken()
logger.Printf("dapr client initializing for: %s", socket)
addr := "unix://" + socket
conn, err := grpc.Dial( //nolint:staticcheck
Expand All @@ -421,11 +421,6 @@ func NewClientWithSocket(socket string) (client Client, err error) {
}

func newClientWithConnection(conn *grpc.ClientConn, authToken *authToken) Client {
apiToken := os.Getenv(apiTokenEnvVarName)
if apiToken != "" {
logger.Println("client uses API token")
authToken.set(apiToken)
}
return &GRPCClient{
connection: conn,
protoClient: pb.NewDaprClient(conn),
Expand All @@ -435,14 +430,26 @@ func newClientWithConnection(conn *grpc.ClientConn, authToken *authToken) Client

// NewClientWithConnection instantiates Dapr client using specific connection.
func NewClientWithConnection(conn *grpc.ClientConn) Client {
return newClientWithConnection(conn, &authToken{})
return newClientWithConnection(conn, newAuthToken())
}

// NOTE: authToken must be created using newAuthToken()
// it is crucial to correctly initialize the dapr client with the API token from the environment variable
type authToken struct {
mu sync.RWMutex
authToken string
}

func newAuthToken() *authToken {
apiToken := os.Getenv(apiTokenEnvVarName)
if apiToken != "" {
logger.Println("client uses API token")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
logger.Println("client uses API token")
logger.Println("API Token loaded from the environment variable")

}
return &authToken{
authToken: apiToken,
}
}

func (a *authToken) get() string {
a.mu.RLock()
defer a.mu.RUnlock()
Expand Down
Loading