github.com/erda-project/erda-infra@v1.0.10-0.20240327085753-f3a249292aeb/pkg/mysqldriver/tls_test.go (about)

     1  // Copyright (c) 2021 Terminus, 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  // 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 mysqldriver
    16  
    17  import (
    18  	"crypto/tls"
    19  	"os"
    20  	"testing"
    21  
    22  	"bou.ke/monkey"
    23  	"github.com/go-sql-driver/mysql"
    24  	"github.com/stretchr/testify/assert"
    25  )
    26  
    27  const rootPEM = `
    28  -----BEGIN CERTIFICATE-----
    29  MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
    30  MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
    31  YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG
    32  EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy
    33  bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
    34  AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP
    35  VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv
    36  h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE
    37  ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ
    38  EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC
    39  DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7
    40  qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD
    41  VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g
    42  K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI
    43  KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n
    44  ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB
    45  BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY
    46  /iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/
    47  zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza
    48  HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto
    49  WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6
    50  yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
    51  -----END CERTIFICATE-----`
    52  
    53  var rsaCertPEM = `-----BEGIN CERTIFICATE-----
    54  MIIB0zCCAX2gAwIBAgIJAI/M7BYjwB+uMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV
    55  BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
    56  aWRnaXRzIFB0eSBMdGQwHhcNMTIwOTEyMjE1MjAyWhcNMTUwOTEyMjE1MjAyWjBF
    57  MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
    58  ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANLJ
    59  hPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wok/4xIA+ui35/MmNa
    60  rtNuC+BdZ1tMuVCPFZcCAwEAAaNQME4wHQYDVR0OBBYEFJvKs8RfJaXTH08W+SGv
    61  zQyKn0H8MB8GA1UdIwQYMBaAFJvKs8RfJaXTH08W+SGvzQyKn0H8MAwGA1UdEwQF
    62  MAMBAf8wDQYJKoZIhvcNAQEFBQADQQBJlffJHybjDGxRMqaRmDhX0+6v02TUKZsW
    63  r5QuVbpQhH6u+0UgcW0jp9QwpxoPTLTWGXEWBBBurxFwiCBhkQ+V
    64  -----END CERTIFICATE-----
    65  `
    66  
    67  var rsaKeyPEM = `-----BEGIN RSA PRIVATE KEY-----
    68  MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo
    69  k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G
    70  6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N
    71  MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW
    72  SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T
    73  xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi
    74  D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g==
    75  -----END RSA PRIVATE KEY-----
    76  `
    77  
    78  func TestOpenTLS(t *testing.T) {
    79  	type args struct {
    80  		tlsName             string
    81  		mysqlCaCertPath     string
    82  		mysqlClientCertPath string
    83  		mysqlClientKeyPath  string
    84  	}
    85  	type file struct {
    86  		mysqlCaCertValue     string
    87  		mysqlClientCertValue string
    88  		mysqlClientKeyValue  string
    89  	}
    90  	tests := []struct {
    91  		name    string
    92  		args    args
    93  		file    file
    94  		wantErr bool
    95  	}{
    96  		{
    97  			name:    "tlsName was empty",
    98  			args:    args{},
    99  			wantErr: false,
   100  		},
   101  		{
   102  			name: "mysqlCaCertPath was empty",
   103  			args: args{
   104  				tlsName: "tlsName",
   105  			},
   106  			wantErr: false,
   107  		},
   108  		{
   109  			name: "test ca cert",
   110  			args: args{
   111  				tlsName:         "tlsName",
   112  				mysqlCaCertPath: "true",
   113  			},
   114  			file: file{
   115  				mysqlCaCertValue: rootPEM,
   116  			},
   117  			wantErr: false,
   118  		},
   119  		{
   120  			name: "test ca cert and client cert",
   121  			args: args{
   122  				tlsName:             "tlsName",
   123  				mysqlCaCertPath:     "true",
   124  				mysqlClientCertPath: "true",
   125  				mysqlClientKeyPath:  "true",
   126  			},
   127  			file: file{
   128  				mysqlCaCertValue:     rootPEM,
   129  				mysqlClientKeyValue:  rsaKeyPEM,
   130  				mysqlClientCertValue: rsaCertPEM,
   131  			},
   132  			wantErr: false,
   133  		},
   134  	}
   135  	for _, tt := range tests {
   136  		t.Run(tt.name, func(t *testing.T) {
   137  			var errorInfo error
   138  			if tt.args.mysqlCaCertPath != "" {
   139  				f, err := os.CreateTemp("", "ca-cert")
   140  				if err != nil {
   141  					errorInfo = err
   142  				} else {
   143  					_, err = f.Write([]byte(tt.file.mysqlCaCertValue))
   144  					if err != nil {
   145  						errorInfo = err
   146  					}
   147  					tt.args.mysqlCaCertPath = f.Name()
   148  				}
   149  			}
   150  
   151  			if tt.args.mysqlClientCertPath != "" && tt.args.mysqlClientKeyPath != "" {
   152  				certFile, err := os.CreateTemp("", "client-cert")
   153  				if err != nil {
   154  					errorInfo = err
   155  				} else {
   156  					_, err = certFile.Write([]byte(tt.file.mysqlClientCertValue))
   157  					if err != nil {
   158  						errorInfo = err
   159  					}
   160  					tt.args.mysqlClientCertPath = certFile.Name()
   161  				}
   162  				keyFile, err := os.CreateTemp("", "client-key")
   163  				if err != nil {
   164  					errorInfo = err
   165  				} else {
   166  					_, err = keyFile.Write([]byte(tt.file.mysqlClientKeyValue))
   167  					if err != nil {
   168  						errorInfo = err
   169  					}
   170  					tt.args.mysqlClientKeyPath = keyFile.Name()
   171  				}
   172  			}
   173  
   174  			if errorInfo != nil {
   175  				tt.wantErr = true
   176  			}
   177  
   178  			patch := monkey.Patch(mysql.RegisterTLSConfig, func(key string, config *tls.Config) error {
   179  				if tt.args.tlsName != "" && tt.args.mysqlCaCertPath != "" {
   180  					assert.NotNil(t, key)
   181  					assert.Equal(t, tt.args.tlsName, key)
   182  					assert.NotNil(t, config.RootCAs)
   183  				}
   184  				if tt.args.mysqlClientKeyPath != "" && tt.args.mysqlClientCertPath != "" {
   185  					assert.NotNil(t, config.Certificates)
   186  					assert.Equal(t, 1, len(config.Certificates))
   187  				}
   188  				return nil
   189  			})
   190  			defer patch.Unpatch()
   191  
   192  			if err := OpenTLS(tt.args.tlsName, tt.args.mysqlCaCertPath, tt.args.mysqlClientCertPath, tt.args.mysqlClientKeyPath); (err != nil) != tt.wantErr {
   193  				t.Errorf("OpenTLS() error = %v, wantErr %v", err, tt.wantErr)
   194  			}
   195  		})
   196  	}
   197  }