blob: a2d8b45e86ab6130eee41dc5de945d35ee3456c7 [file] [log] [blame]
Abhay Kumara2ae5992025-11-10 14:02:24 +00001// Copyright 2019 The etcd Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Package credentials implements gRPC credential interface with etcd specific logic.
16// e.g., client handshake with custom authority parameter
17package credentials
18
19import (
20 "context"
21 "crypto/tls"
22 "sync"
23
24 grpccredentials "google.golang.org/grpc/credentials"
25
26 "go.etcd.io/etcd/api/v3/v3rpc/rpctypes"
27)
28
29func NewTransportCredential(cfg *tls.Config) grpccredentials.TransportCredentials {
30 return grpccredentials.NewTLS(cfg)
31}
32
33// PerRPCCredentialsBundle defines gRPC credential interface.
34type PerRPCCredentialsBundle interface {
35 UpdateAuthToken(token string)
36 PerRPCCredentials() grpccredentials.PerRPCCredentials
37}
38
39func NewPerRPCCredentialBundle() PerRPCCredentialsBundle {
40 return &perRPCCredentialBundle{
41 rc: &perRPCCredential{},
42 }
43}
44
45// perRPCCredentialBundle implements `PerRPCCredentialsBundle` interface.
46type perRPCCredentialBundle struct {
47 rc *perRPCCredential
48}
49
50func (b *perRPCCredentialBundle) UpdateAuthToken(token string) {
51 if b.rc == nil {
52 return
53 }
54 b.rc.UpdateAuthToken(token)
55}
56
57func (b *perRPCCredentialBundle) PerRPCCredentials() grpccredentials.PerRPCCredentials {
58 return b.rc
59}
60
61// perRPCCredential implements `grpccredentials.PerRPCCredentials` interface.
62type perRPCCredential struct {
63 authToken string
64 authTokenMu sync.RWMutex
65}
66
67func (rc *perRPCCredential) RequireTransportSecurity() bool { return false }
68
69func (rc *perRPCCredential) GetRequestMetadata(ctx context.Context, s ...string) (map[string]string, error) {
70 rc.authTokenMu.RLock()
71 authToken := rc.authToken
72 rc.authTokenMu.RUnlock()
73 if authToken == "" {
74 return nil, nil
75 }
76 return map[string]string{rpctypes.TokenFieldNameGRPC: authToken}, nil
77}
78
79func (rc *perRPCCredential) UpdateAuthToken(token string) {
80 rc.authTokenMu.Lock()
81 rc.authToken = token
82 rc.authTokenMu.Unlock()
83}