[#286] client: Add TLS options

Add `WithTLSConfig` option to client.
If it is not nil then client will
try to open secured connection.

Signed-off-by: Pavel Karpy <carpawell@nspcc.ru>
This commit is contained in:
Pavel Karpy 2021-05-20 18:51:28 +03:00 committed by Leonard Lyubich
parent 634e405e9c
commit 89aede1fb3
3 changed files with 35 additions and 2 deletions

View file

@ -2,6 +2,7 @@ package client
import (
"crypto/ecdsa"
"crypto/tls"
"time"
"github.com/nspcc-dev/neofs-api-go/pkg"
@ -110,7 +111,7 @@ func v2MetaHeaderFromOpts(options *callOptions) *v2session.RequestMetaHeader {
func defaultClientOptions() *clientOptions {
return &clientOptions{
rawOpts: make([]client.Option, 0, 3),
rawOpts: make([]client.Option, 0, 4),
}
}
@ -133,6 +134,13 @@ func WithDialTimeout(dur time.Duration) Option {
}
}
// WithTLSConfig returns option to set connection's TLS config to the remote node.
func WithTLSConfig(cfg *tls.Config) Option {
return func(opts *clientOptions) {
opts.rawOpts = append(opts.rawOpts, client.WithTLSCfg(cfg))
}
}
// WithDefaultPrivateKey returns option to set default private key
// used for the work.
func WithDefaultPrivateKey(key *ecdsa.PrivateKey) Option {

View file

@ -6,6 +6,7 @@ import (
"github.com/nspcc-dev/neofs-api-go/rpc/grpc"
grpcstd "google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
func (c *Client) createGRPCClient() (err error) {
@ -33,8 +34,17 @@ func (c *Client) openGRPCConn() error {
var err error
var credOpt grpcstd.DialOption
if c.tlsCfg != nil {
creds := credentials.NewTLS(c.tlsCfg)
credOpt = grpcstd.WithTransportCredentials(creds)
} else {
credOpt = grpcstd.WithInsecure()
}
dialCtx, cancel := context.WithTimeout(context.Background(), c.dialTimeout)
c.conn, err = grpcstd.DialContext(dialCtx, c.addr, grpcstd.WithInsecure())
c.conn, err = grpcstd.DialContext(dialCtx, c.addr, credOpt)
cancel()
return err

View file

@ -1,6 +1,7 @@
package client
import (
"crypto/tls"
"time"
"google.golang.org/grpc"
@ -14,6 +15,8 @@ type cfg struct {
dialTimeout time.Duration
tlsCfg *tls.Config
conn *grpc.ClientConn
}
@ -49,6 +52,18 @@ func WithDialTimeout(v time.Duration) Option {
}
}
// WithTLSCfg returns option to specify
// TLS configuration.
//
// Ignored if WithGRPCConn is provided.
func WithTLSCfg(v *tls.Config) Option {
return func(c *cfg) {
if v != nil {
c.tlsCfg = v
}
}
}
// WithGRPCConn returns option to specify
// gRPC virtual connection.
func WithGRPCConn(v *grpc.ClientConn) Option {