-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
261 lines (218 loc) · 7.15 KB
/
client.go
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
package rpcclient
import (
"context"
"crypto"
"math"
"strings"
tcredentials "github.com/effective-security/porto/gserver/credentials"
"github.com/effective-security/porto/xhttp/httperror"
"github.com/effective-security/x/values"
"github.com/effective-security/xlog"
"github.com/effective-security/xpki/jwt/dpop"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
)
var logger = xlog.NewPackageLogger("github.com/effective-security/porto/pkg", "rpcclient")
var (
// client-side handling retrying of request failures where data was not written to the wire or
// where server indicates it did not process the data. gRPC default is default is "FailFast(true)"
defaultWaitForReady = grpc.WaitForReady(true)
// client-side request send limit, gRPC default is math.MaxInt32
// Make sure that "client-side send limit < server-side default send/recv limit"
// Same value as "embed.DefaultMaxRequestBytes" plus gRPC overhead bytes
defaultMaxCallSendMsgSize = grpc.MaxCallSendMsgSize(2 * 1024 * 1024)
// client-side response receive limit, gRPC default is 4MB
// Make sure that "client-side receive limit >= server-side default send/recv limit"
// because range response can easily exceed request send limits
// Default to math.MaxInt32; writes exceeding server-side send limit fails anyway
defaultMaxCallRecvMsgSize = grpc.MaxCallRecvMsgSize(math.MaxInt32)
)
// defaultCallOpts defines a list of default "gRPC.CallOption".
// Some options are exposed to "client.Config".
// Defaults will be overridden by the settings in "client.Config".
var defaultCallOpts = []grpc.CallOption{
defaultWaitForReady,
defaultMaxCallSendMsgSize,
defaultMaxCallRecvMsgSize,
}
// Client provides and manages v1 client session.
type Client struct {
cfg Config
conn *grpc.ClientConn
callOpts []grpc.CallOption
ctx context.Context
cancel context.CancelFunc
//lock sync.RWMutex
}
// NewFromURL creates a new client from a URL.
func NewFromURL(url string, ignoreAccessTokenError bool) (*Client, error) {
return New(&Config{
Endpoint: url,
}, ignoreAccessTokenError)
}
// New creates a new client from a given configuration.
func New(cfg *Config, ignoreAccessTokenError bool) (*Client, error) {
return newClient(cfg, ignoreAccessTokenError)
}
// Close shuts down the client's connections.
func (c *Client) Close() error {
c.cancel()
if c.conn != nil {
return toErr(c.ctx, c.conn.Close())
}
return c.ctx.Err()
}
// Conn returns the current in-use connection
func (c *Client) Conn() *grpc.ClientConn {
return c.conn
}
// Opts returns the current Call options
func (c *Client) Opts() []grpc.CallOption {
return c.callOpts
}
func newClient(cfg *Config, ignoreAccessTokenError bool) (*Client, error) {
if cfg == nil || len(cfg.Endpoint) == 0 {
return nil, errors.Errorf("endpoint is required in client config")
}
// use a temporary skeleton client to bootstrap first connection
baseCtx := context.Background()
if cfg.Context != nil {
baseCtx = cfg.Context
}
ctx, cancel := context.WithCancel(baseCtx)
client := &Client{
conn: nil,
cfg: *cfg,
ctx: ctx,
cancel: cancel,
callOpts: defaultCallOpts,
}
dialEndpoint := cfg.Endpoint
var dopts []grpc.DialOption
var creds credentials.TransportCredentials
if cfg.UserAgent != "" {
dopts = append(dopts, grpc.WithUserAgent(cfg.UserAgent))
}
if cfg.TLS != nil &&
(strings.HasPrefix(dialEndpoint, "https://") || strings.HasPrefix(dialEndpoint, "unixs://")) {
bundle := tcredentials.NewBundle(tcredentials.Config{TLSConfig: cfg.TLS})
creds = bundle.TransportCredentials()
if cfg.CallerIdentity != nil {
bundle.WithCallerIdentity(cfg.CallerIdentity)
} else {
at, location, err := cfg.LoadAuthToken()
logger.KV(xlog.DEBUG, "token_location", location)
if err != nil && !ignoreAccessTokenError {
return nil, errors.WithMessage(err, "failed to load access token")
}
if err == nil {
if at.Expired() {
if !ignoreAccessTokenError {
return nil, errors.Errorf("authorization: token expired")
}
} else {
// grpc: the credentials require transport level security
token := at.AccessToken
typ := values.StringsCoalesce(at.TokenType, "Bearer")
if at.DpopJkt != "" {
k, _, err := cfg.Storage().LoadKey(at.DpopJkt)
if err != nil {
return nil, errors.WithMessage(err, "unable to load key for DPoP")
}
typ = "DPoP"
signer, err := dpop.NewSigner(k.Key.(crypto.Signer))
if err != nil {
return nil, errors.WithMessage(err, "unable to create DPoP signer")
}
bundle.WithDPoP(signer)
}
tok := tcredentials.Token{
TokenType: typ,
AccessToken: token,
Expires: at.Expires,
}
bundle.UpdateAuthToken(tok)
}
}
}
dopts = append(dopts, grpc.WithPerRPCCredentials(bundle.PerRPCCredentials()))
}
logger.KV(xlog.TRACE, "dial", dialEndpoint)
conn, err := client.dial(dialEndpoint, creds, dopts...)
if err != nil {
client.cancel()
return nil, errors.WithStack(err)
}
client.conn = conn
return client, nil
}
var removePrefix = strings.NewReplacer("https://", "", "http://", "", "unixs://", "", "unix://", "")
// dial configures and dials any grpc balancer target.
func (c *Client) dial(target string, creds credentials.TransportCredentials, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
opts, err := c.dialSetupOpts(creds, dopts...)
if err != nil {
return nil, errors.Errorf("failed to configure dialer: %v", err)
}
opts = append(opts, c.cfg.DialOptions...)
dctx := c.ctx
if c.cfg.DialTimeout > 0 {
opts = append(opts, grpc.WithBlock())
var cancel context.CancelFunc
dctx, cancel = context.WithTimeout(c.ctx, c.cfg.DialTimeout)
defer cancel()
}
target = removePrefix.Replace(target)
if !strings.Contains(target, ":") {
target += ":443"
}
logger.KV(xlog.DEBUG, "target", target, "timeout", c.cfg.DialTimeout)
conn, err := grpc.DialContext(dctx, target, opts...)
if err != nil {
return nil, err
}
logger.KV(xlog.DEBUG, "target", target, "status", "connecton_created")
return conn, nil
}
// dialSetupOpts gives the dial opts prior to any authentication.
func (c *Client) dialSetupOpts(creds credentials.TransportCredentials, dopts ...grpc.DialOption) (opts []grpc.DialOption, err error) {
if c.cfg.DialKeepAliveTime > 0 {
params := keepalive.ClientParameters{
Time: c.cfg.DialKeepAliveTime,
Timeout: c.cfg.DialKeepAliveTimeout,
}
opts = append(opts, grpc.WithKeepaliveParams(params))
}
opts = append(opts, dopts...)
if creds == nil {
creds = insecure.NewCredentials()
}
opts = append(opts, grpc.WithTransportCredentials(creds))
return opts, nil
}
func toErr(ctx context.Context, err error) error {
if err == nil {
return nil
}
code := httperror.GRPCCode(err)
switch code {
case codes.DeadlineExceeded:
fallthrough
case codes.Canceled:
if ctx.Err() != nil {
err = ctx.Err()
}
}
return err
}
/*
func canceledByCaller(stopCtx context.Context, err error) bool {
if stopCtx.Err() == nil || err == nil {
return false
}
return err == context.Canceled || err == context.DeadlineExceeded
}
*/