github.com/hyperledger/aries-framework-go@v0.3.2/pkg/didcomm/transport/http/support_test.go (about)

     1  /*
     2  Copyright SecureKey Technologies Inc. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package http
     8  
     9  import (
    10  	"crypto/x509"
    11  	"encoding/pem"
    12  	"fmt"
    13  	"io/ioutil"
    14  	"net"
    15  	"net/http"
    16  	"path/filepath"
    17  	"strings"
    18  	"time"
    19  )
    20  
    21  const (
    22  	certPrefix    = "testdata/crypto/"
    23  	clientTimeout = 5 * time.Second
    24  )
    25  
    26  func addCertsToCertPool(pool *x509.CertPool) error {
    27  	var rawCerts []string
    28  
    29  	// add contents of ec-pubCert(1, 2 and 3).pem to rawCerts
    30  	for i := 1; i <= 3; i++ {
    31  		certPath := fmt.Sprintf("%sec-pubCert%d.pem", certPrefix, i)
    32  		// Create a pool with server certificates
    33  		cert, e := ioutil.ReadFile(filepath.Clean(certPath))
    34  		if e != nil {
    35  			return fmt.Errorf("reading certificate failed: %w", e)
    36  		}
    37  
    38  		rawCerts = append(rawCerts, string(cert))
    39  	}
    40  
    41  	certs := decodeCerts(rawCerts)
    42  	for i := range certs {
    43  		pool.AddCert(certs[i])
    44  	}
    45  
    46  	return nil
    47  }
    48  
    49  func startMockServer(handler http.Handler) net.Listener {
    50  	// ":0" will make the listener auto assign a free port
    51  	listener, err := net.Listen("tcp", "127.0.0.1:0")
    52  	if err != nil {
    53  		logger.Fatalf("HTTP listener failed to start: %s", err)
    54  	}
    55  
    56  	go func() {
    57  		err := http.ServeTLS(listener, handler, certPrefix+"ec-pubCert1.pem", certPrefix+"ec-key1.pem")
    58  		if err != nil && !strings.Contains(err.Error(), "use of closed network connection") {
    59  			logger.Fatalf("HTTP server failed to start: %s", err)
    60  		}
    61  	}()
    62  
    63  	return listener
    64  }
    65  
    66  type mockHTTPHandler struct{}
    67  
    68  func (m mockHTTPHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
    69  	if req.Body != nil {
    70  		body, err := ioutil.ReadAll(req.Body)
    71  		if err != nil || string(body) == "bad" {
    72  			res.WriteHeader(http.StatusBadRequest)
    73  
    74  			_, err = res.Write([]byte(fmt.Sprintf("bad request: %s", body)))
    75  			if err != nil {
    76  				panic(err)
    77  			}
    78  
    79  			return
    80  		}
    81  	}
    82  
    83  	// mocking successful response
    84  	res.WriteHeader(http.StatusAccepted) // usually DID-Comm expects StatusAccepted code (202)
    85  	res.Write([]byte("success"))         // nolint
    86  }
    87  
    88  // decodeCerts will decode a list of pemCertsList (string) into a list of x509 certificates.
    89  func decodeCerts(pemCertsList []string) []*x509.Certificate {
    90  	var certs []*x509.Certificate
    91  
    92  	for _, pemCertsString := range pemCertsList {
    93  		pemCerts := []byte(pemCertsString)
    94  		for len(pemCerts) > 0 {
    95  			var block *pem.Block
    96  
    97  			block, pemCerts = pem.Decode(pemCerts)
    98  			if block == nil {
    99  				break
   100  			}
   101  
   102  			if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
   103  				continue
   104  			}
   105  
   106  			cert, err := x509.ParseCertificate(block.Bytes)
   107  			if err != nil {
   108  				continue
   109  			}
   110  
   111  			certs = append(certs, cert)
   112  		}
   113  	}
   114  
   115  	return certs
   116  }
   117  
   118  func getServerPort(server net.Listener) int {
   119  	// read dynamic port assigned to the server to be used by the client
   120  	return server.Addr().(*net.TCPAddr).Port
   121  }