github.com/hxx258456/fabric-ca-gm@v0.0.3-0.20221111064038-a268ad7e3a37/lib/tls/tls_test.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8                   http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package tls
    18  
    19  import (
    20  	"crypto/rand"
    21  	"crypto/rsa"
    22  	"encoding/pem"
    23  	"errors"
    24  	"fmt"
    25  	"math/big"
    26  	"os"
    27  	"testing"
    28  	"time"
    29  
    30  	"github.com/hxx258456/ccgo/x509"
    31  
    32  	"github.com/stretchr/testify/assert"
    33  )
    34  
    35  const (
    36  	configDir   = "../../testdata"
    37  	expiredCert = "../../testdata/expiredcert.pem"
    38  )
    39  
    40  func TestGetClientTLSConfig(t *testing.T) {
    41  
    42  	cfg := &ClientTLSConfig{
    43  		CertFiles: []string{"root.pem"},
    44  		Client: KeyCertFiles{
    45  			KeyFile:  "tls_client-key.pem",
    46  			CertFile: "tls_client-cert.pem",
    47  		},
    48  	}
    49  
    50  	err := AbsTLSClient(cfg, configDir)
    51  	if err != nil {
    52  		t.Errorf("Failed to get absolute path for client TLS config: %s", err)
    53  	}
    54  
    55  	_, err = GetClientTLSConfig(cfg, nil)
    56  	if err != nil {
    57  		t.Errorf("Failed to get TLS Config: %s", err)
    58  	}
    59  
    60  }
    61  
    62  func TestGetClientTLSConfigInvalidArgs(t *testing.T) {
    63  	// 1.
    64  	cfg := &ClientTLSConfig{
    65  		CertFiles: []string{"root.pem"},
    66  		Client: KeyCertFiles{
    67  			KeyFile:  "no_tls_client-key.pem",
    68  			CertFile: "no_tls_client-cert.pem",
    69  		},
    70  	}
    71  	_, err := GetClientTLSConfig(cfg, nil)
    72  	assert.Error(t, err)
    73  	assert.Contains(t, err.Error(), "open no_tls_client-cert.pem: no such file or directory")
    74  
    75  	// 2.
    76  	cfg = &ClientTLSConfig{
    77  		CertFiles: nil,
    78  		Client: KeyCertFiles{
    79  			KeyFile:  "tls_client-key.pem",
    80  			CertFile: "tls_client-cert.pem",
    81  		},
    82  	}
    83  	AbsTLSClient(cfg, configDir)
    84  	_, err = GetClientTLSConfig(cfg, nil)
    85  	assert.Error(t, err)
    86  	assert.Contains(t, err.Error(), "No trusted root certificates for TLS were provided")
    87  
    88  	// 3.
    89  	cfg = &ClientTLSConfig{
    90  		CertFiles: nil,
    91  		Client: KeyCertFiles{
    92  			KeyFile:  "no-tls_client-key.pem",
    93  			CertFile: "tls_client-cert.pem",
    94  		},
    95  	}
    96  	AbsTLSClient(cfg, configDir)
    97  	_, err = GetClientTLSConfig(cfg, nil)
    98  	assert.Error(t, err)
    99  	assert.Contains(t, err.Error(), "no-tls_client-key.pem: no such file or directory")
   100  
   101  	// 4.
   102  	cfg = &ClientTLSConfig{
   103  		CertFiles: nil,
   104  		Client: KeyCertFiles{
   105  			KeyFile:  "",
   106  			CertFile: "",
   107  		},
   108  	}
   109  	_, err = GetClientTLSConfig(cfg, nil)
   110  	assert.Error(t, err)
   111  	assert.Contains(t, err.Error(), "No trusted root certificates for TLS were provided")
   112  
   113  	// 5.
   114  	cfg = &ClientTLSConfig{
   115  		CertFiles: []string{"no-root.pem"},
   116  		Client: KeyCertFiles{
   117  			KeyFile:  "tls_client-key.pem",
   118  			CertFile: "tls_client-cert.pem",
   119  		},
   120  	}
   121  	AbsTLSClient(cfg, configDir)
   122  	_, err = GetClientTLSConfig(cfg, nil)
   123  	assert.Error(t, err)
   124  	assert.Contains(t, err.Error(), "no-root.pem: no such file or directory")
   125  }
   126  
   127  func TestAbsServerTLSConfig(t *testing.T) {
   128  	cfg := &ServerTLSConfig{
   129  		KeyFile:  "tls_client-key.pem",
   130  		CertFile: "tls_client-cert.pem",
   131  		ClientAuth: ClientAuth{
   132  			CertFiles: []string{"root.pem"},
   133  		},
   134  	}
   135  
   136  	err := AbsTLSServer(cfg, configDir)
   137  	if err != nil {
   138  		t.Errorf("Failed to get absolute path for server TLS config: %s", err)
   139  	}
   140  }
   141  
   142  func TestCheckCertDates(t *testing.T) {
   143  	err := checkCertDates(expiredCert)
   144  	if err == nil {
   145  		assert.Error(t, errors.New("Expired certificate should have resulted in an error"))
   146  	}
   147  
   148  	err = createTestCertificate()
   149  	if err != nil {
   150  		assert.Error(t, err)
   151  	}
   152  
   153  	err = checkCertDates("notbefore.pem")
   154  	if err == nil {
   155  		assert.Error(t, errors.New("Future valid certificate should have resulted in an error"))
   156  	}
   157  	if err != nil {
   158  		assert.Contains(t, err.Error(), "Certificate provided not valid until later date")
   159  	}
   160  
   161  	os.Remove("notbefore.pem")
   162  }
   163  
   164  func createTestCertificate() error {
   165  	// Dynamically create a certificate with future valid date for testing purposes
   166  	certTemplate := &x509.Certificate{
   167  		IsCA:                  true,
   168  		BasicConstraintsValid: true,
   169  		SubjectKeyId:          []byte{1, 2, 3},
   170  		SerialNumber:          big.NewInt(1234),
   171  		NotBefore:             time.Now().Add(time.Hour * 24),
   172  		NotAfter:              time.Now().Add(time.Hour * 48),
   173  		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
   174  		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
   175  	}
   176  	// generate private key
   177  	privatekey, err := rsa.GenerateKey(rand.Reader, 2048)
   178  	if err != nil {
   179  		return fmt.Errorf("Error occurred during key generation: %s", err)
   180  	}
   181  	publickey := &privatekey.PublicKey
   182  	// create a self-signed certificate. template = parent
   183  	var parent = certTemplate
   184  	cert, err := x509.CreateCertificate(rand.Reader, certTemplate, parent, publickey, privatekey)
   185  	if err != nil {
   186  		return fmt.Errorf("Error occurred during certificate creation: %s", err)
   187  	}
   188  
   189  	pemfile, _ := os.Create("notbefore.pem")
   190  	var pemkey = &pem.Block{
   191  		Type:  "CERTIFICATE",
   192  		Bytes: cert,
   193  	}
   194  	pem.Encode(pemfile, pemkey)
   195  	pemfile.Close()
   196  
   197  	return nil
   198  }