github.com/pingcap/ticdc@v0.0.0-20220526033649-485a10ef2652/pkg/security/credential.go (about)

     1  // Copyright 2020 PingCAP, Inc.
     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  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package security
    15  
    16  import (
    17  	"crypto/tls"
    18  
    19  	cerror "github.com/pingcap/ticdc/pkg/errors"
    20  	"github.com/pingcap/tidb-tools/pkg/utils"
    21  	pd "github.com/tikv/pd/client"
    22  	"google.golang.org/grpc"
    23  	"google.golang.org/grpc/credentials"
    24  )
    25  
    26  // Credential holds necessary path parameter to build a tls.Config
    27  type Credential struct {
    28  	CAPath        string   `toml:"ca-path" json:"ca-path"`
    29  	CertPath      string   `toml:"cert-path" json:"cert-path"`
    30  	KeyPath       string   `toml:"key-path" json:"key-path"`
    31  	CertAllowedCN []string `toml:"cert-allowed-cn" json:"cert-allowed-cn"`
    32  }
    33  
    34  // IsTLSEnabled checks whether TLS is enabled or not.
    35  func (s *Credential) IsTLSEnabled() bool {
    36  	return len(s.CAPath) != 0
    37  }
    38  
    39  // PDSecurityOption creates a new pd SecurityOption from Security
    40  func (s *Credential) PDSecurityOption() pd.SecurityOption {
    41  	return pd.SecurityOption{
    42  		CAPath:   s.CAPath,
    43  		CertPath: s.CertPath,
    44  		KeyPath:  s.KeyPath,
    45  	}
    46  }
    47  
    48  // ToGRPCDialOption constructs a gRPC dial option.
    49  func (s *Credential) ToGRPCDialOption() (grpc.DialOption, error) {
    50  	tlsCfg, err := s.ToTLSConfig()
    51  	if err != nil || tlsCfg == nil {
    52  		return grpc.WithInsecure(), err
    53  	}
    54  	return grpc.WithTransportCredentials(credentials.NewTLS(tlsCfg)), nil
    55  }
    56  
    57  // ToTLSConfig generates tls's config from *Security
    58  func (s *Credential) ToTLSConfig() (*tls.Config, error) {
    59  	cfg, err := utils.ToTLSConfig(s.CAPath, s.CertPath, s.KeyPath)
    60  	return cfg, cerror.WrapError(cerror.ErrToTLSConfigFailed, err)
    61  }
    62  
    63  // ToTLSConfigWithVerify generates tls's config from *Security and requires
    64  // verifing remote cert common name.
    65  func (s *Credential) ToTLSConfigWithVerify() (*tls.Config, error) {
    66  	cfg, err := utils.ToTLSConfigWithVerify(s.CAPath, s.CertPath, s.KeyPath, s.CertAllowedCN)
    67  	return cfg, cerror.WrapError(cerror.ErrToTLSConfigFailed, err)
    68  }