github.com/jcarley/cli@v0.0.0-20180201210820-966d90434c30/commands/certs/create_test.go (about)

     1  package certs
     2  
     3  import (
     4  	"encoding/json"
     5  	"flag"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net/http"
     9  	"os"
    10  	"testing"
    11  
    12  	"github.com/daticahealth/cli/commands/services"
    13  	"github.com/daticahealth/cli/commands/ssl"
    14  	"github.com/daticahealth/cli/test"
    15  )
    16  
    17  const (
    18  	certName = "example.com"
    19  	pubKey   = `-----BEGIN CERTIFICATE-----
    20  MIIDFDCCAfygAwIBAgIJAJ04dO4O6PrLMA0GCSqGSIb3DQEBBQUAMBAxDjAMBgNV
    21  BAMTBWxvY2FsMB4XDTE3MDEyNjA2MjQwMloXDTI3MDEyNDA2MjQwMlowEDEOMAwG
    22  A1UEAxMFbG9jYWwwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC7dwM2
    23  rMj9N0mEZP+V9sWx0MKcuc4Uymv4BbJO/dP7ryXJEMqSZc7DrmUs1XTKEguWu9dL
    24  0BylzCvaWalqKixojWL1Wojj6i8DfgHgFum+Fjd3EUZhbNnerfCC94Of1XCRSezG
    25  sWP7V0gGSlxoptRvhH4NTHkyemnaZEDs323VtuhG0AgoQ8EWS/XeVAWLlSsHRPWp
    26  BXjQn0ve33SsnbhbpkRkyB1jlH7vxbEaAX9aKrZYYSmXLz3NKp8ti8AljqybWC86
    27  ymVl5qStd6yz/CrFiGWki0F46/BdPB8ZCY4iOsuMXbWWDiRuq7llu8iWEat651DO
    28  VeAPKdQsRZgK/y1hAgMBAAGjcTBvMB0GA1UdDgQWBBRrj840X4a+uGDsKCRMHzX1
    29  mtXAWTBABgNVHSMEOTA3gBRrj840X4a+uGDsKCRMHzX1mtXAWaEUpBIwEDEOMAwG
    30  A1UEAxMFbG9jYWyCCQCdOHTuDuj6yzAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEB
    31  BQUAA4IBAQAVpa/IkKyDPE7X4RsHZLsinEfJpAahrLsSBGDIo6cgpB3txntgmoLU
    32  pC71ZQEE5glE4ENvflyLvvg6fAwlOVL0sax0GKfYgLJhg11CmsoRYiHCPh/bwqtU
    33  iqAzjo7yCsyzo1Q0IMbc0RHFBmikHJEL6Dsuri1Skj+KnXLBibl8FeFuppgusV+W
    34  8q3T/6ZNM8nFhRAPAQf7n4c4y+VjYuw/WSEdByH2NuLnLivb97E5BC0nr3/AK0Kz
    35  MSsO3RiSxj07Gepc+Ce0VNXZkVAjUiwHvZeC7ebLC/SQs8ihogi/TVELgQkksgC/
    36  lyUFiVHqjeeIKxYNy3d7RqGxzKKDRssi
    37  -----END CERTIFICATE-----`
    38  	privKey = `-----BEGIN RSA PRIVATE KEY-----
    39  MIIEpQIBAAKCAQEAu3cDNqzI/TdJhGT/lfbFsdDCnLnOFMpr+AWyTv3T+68lyRDK
    40  kmXOw65lLNV0yhILlrvXS9Acpcwr2lmpaiosaI1i9VqI4+ovA34B4BbpvhY3dxFG
    41  YWzZ3q3wgveDn9VwkUnsxrFj+1dIBkpcaKbUb4R+DUx5Mnpp2mRA7N9t1bboRtAI
    42  KEPBFkv13lQFi5UrB0T1qQV40J9L3t90rJ24W6ZEZMgdY5R+78WxGgF/Wiq2WGEp
    43  ly89zSqfLYvAJY6sm1gvOsplZeakrXess/wqxYhlpItBeOvwXTwfGQmOIjrLjF21
    44  lg4kbqu5ZbvIlhGreudQzlXgDynULEWYCv8tYQIDAQABAoIBAQCN1FHzGLCLmzuc
    45  1gjkvan+iPHkP1MiOa+MG0s3JiUugum0gGayciIHvDbBv9E3XIW2CfGuYwp5icoX
    46  zcQ2FSg6BdY7yL5OqQveuYPTtaIsdYSLKd+0r/T522FexMKpt4MN+P8RqH37V6Kf
    47  V70oVCffIz928kezoBfb6gOQ8s2XZRn8VHF+RDuxlT2x+eintCj9J87ynUYgcKwp
    48  Pop2LkmRARqOCApAFCoIcywW7eV91JIXLvkmxn9J2Y/y0hdBXZyRGmPMnJEZjliI
    49  nTanzs4RZENuOI37/zSXLn4R6M4MwRk/Lmi+Wsdd9gyOoLM+2hLtHVsdKPbHFlJ0
    50  e5BzA35RAoGBAORU5DrKLUKQQDLcnhq70naph1taJFb7hTuX6stUaekRjZyVw1cd
    51  2neOv3Z12h/vHOEnKcJhUVRTTCp5nn2FJVk2aSyeIUQ6LKajxlTmTe39gLubEDFr
    52  jRmtX4WGJ+noKHz4gotZbL1Yn88PlIzBWYc6+BJOlqlckerCAza0EMKtAoGBANIu
    53  Y35BZe2Y9BJ7BMzkxR9ZKs5ddXFAiSoT0TAI44UxX0M7R5/VMMNc4z3LmtUCHqOS
    54  RCDdcjMunj5yiqaM1CEQ9Ol+YJ79IKtt2i0den5vDvHuHde0dNiAmpLJlFsazaIR
    55  Zc8cLDvPiaNsb4mxM3Jq4SHfUebUemGl9FnsJOAFAoGALXLsXvthWO+Hp9gcLGwY
    56  b4A9LiTaOOol0f/iP4jU8AyLaJCy6kNJ+iRS3gyFV3fsArEd8dAXNTbDYW0F7Cw1
    57  i/V1p+jt7Du8KYtN7hZNisK7/hvWdE/ZLTRCYDyc80U/0ehRa9Vn/KSIYtnSEtZl
    58  sLI/ML2t5ZZEgTsPErNy5p0CgYEAzVG9pbeTL9CsFWWRYerVWfNMKr4HnTOzCqTD
    59  RE5anGGHsvC03kFv2ljiMBq2zQC+F4IqBYTuK2uN8GkKYvrNuuOKrJHlJ0sVYAH3
    60  EP1sDRjGm7XF91L0lg7DcUN0Jq9/U6P1NaZK2764sSmbqAGvxUT9Wo6CvqCwULXC
    61  hxl1SFUCgYEAyl+2eRiFXW6Opi3yLWSJ1FyqgZnqV9AUSXFTu3HFkw4yLzIwuq9M
    62  nfOBIcrGX2exIylqMoeLxl9WfKbvZTQbL4zCzHoOtsuSTZErZywIIH0Jl5YZJnaT
    63  EZ/6B0fi6DsLHY1tkIEvqgGI0kQX6IE84iZSi/Ubh8gQGwtutoZ1Stk=
    64  -----END RSA PRIVATE KEY-----`
    65  	pubKeyPath  = "example.pem"
    66  	privKeyPath = "example-key.pem"
    67  	invalidPath = "invalid-file.pem"
    68  )
    69  
    70  func TestMain(m *testing.M) {
    71  	flag.Parse()
    72  	if err := createCertFiles(); err != nil {
    73  		fmt.Println(err)
    74  		os.Exit(1)
    75  	}
    76  	statusCode := m.Run()
    77  	cleanupCertFiles()
    78  	os.Exit(statusCode)
    79  }
    80  
    81  var certCreateTests = []struct {
    82  	name        string
    83  	pubKeyPath  string
    84  	privKeyPath string
    85  	downStream  string
    86  	selfSigned  bool
    87  	resolve     bool
    88  	expectErr   bool
    89  }{
    90  	{certName, pubKeyPath, privKeyPath, test.DownStream, true, true, false},
    91  	{certName, pubKeyPath, privKeyPath, test.DownStream, true, false, false},
    92  	{certName, pubKeyPath, privKeyPath, test.DownStream, false, true, false},
    93  	{certName, pubKeyPath, invalidPath, test.DownStream, true, true, true},
    94  	{certName, invalidPath, privKeyPath, test.DownStream, true, true, true},
    95  	{"/?%", pubKeyPath, privKeyPath, test.DownStream, true, true, true},
    96  }
    97  
    98  func TestCertsCreate(t *testing.T) {
    99  	mux, server, baseURL := test.Setup()
   100  	defer test.Teardown(server)
   101  	settings := test.GetSettings(baseURL.String())
   102  	mux.HandleFunc("/environments/"+test.EnvID+"/services/"+test.SvcID+"/certs",
   103  		func(w http.ResponseWriter, r *http.Request) {
   104  			test.AssertEquals(t, r.Method, "POST")
   105  			fmt.Fprint(w, `{}`)
   106  		},
   107  	)
   108  	mux.HandleFunc("/environments/"+test.EnvID+"/services",
   109  		func(w http.ResponseWriter, r *http.Request) {
   110  			test.AssertEquals(t, r.Method, "GET")
   111  			fmt.Fprint(w, fmt.Sprintf(`[{"id":"%s","label":"%s"}]`, test.SvcID, test.DownStream))
   112  		},
   113  	)
   114  
   115  	for _, data := range certCreateTests {
   116  		t.Logf("Data: %+v", data)
   117  
   118  		// test
   119  		err := CmdCreate(data.name, data.pubKeyPath, data.privKeyPath, data.downStream, data.selfSigned, data.resolve, false, New(settings), services.New(settings), ssl.New(settings))
   120  
   121  		// assert
   122  		if err != nil != data.expectErr {
   123  			t.Errorf("Unexpected error: %s", err)
   124  			continue
   125  		}
   126  	}
   127  }
   128  
   129  func TestCertsCreateLetsEncrypt(t *testing.T) {
   130  	mux, server, baseURL := test.Setup()
   131  	defer test.Teardown(server)
   132  	settings := test.GetSettings(baseURL.String())
   133  	mux.HandleFunc("/environments/"+test.EnvID+"/services/"+test.SvcID+"/certs",
   134  		func(w http.ResponseWriter, r *http.Request) {
   135  			test.AssertEquals(t, r.Method, "POST")
   136  			defer r.Body.Close()
   137  			body, _ := ioutil.ReadAll(r.Body)
   138  			var certReq struct {
   139  				Name        string `json:"name"`
   140  				LetsEncrypt bool   `json:"letsEncrypt"`
   141  			}
   142  			err := json.Unmarshal(body, &certReq)
   143  			if err != nil || !certReq.LetsEncrypt || certReq.Name != certName {
   144  				w.WriteHeader(400)
   145  			}
   146  			fmt.Fprint(w, `{}`)
   147  		},
   148  	)
   149  	mux.HandleFunc("/environments/"+test.EnvID+"/services",
   150  		func(w http.ResponseWriter, r *http.Request) {
   151  			test.AssertEquals(t, r.Method, "GET")
   152  			fmt.Fprint(w, fmt.Sprintf(`[{"id":"%s","label":"%s"}]`, test.SvcID, test.DownStream))
   153  		},
   154  	)
   155  	// test
   156  	err := New(settings).CreateLetsEncrypt(certName, test.SvcID)
   157  
   158  	// assert
   159  	if err != nil {
   160  		t.Fatalf("Unexpected error: %s", err)
   161  	}
   162  }
   163  
   164  func TestCertsCreateFailSSL(t *testing.T) {
   165  	mux, server, baseURL := test.Setup()
   166  	defer test.Teardown(server)
   167  	settings := test.GetSettings(baseURL.String())
   168  	mux.HandleFunc("/environments/"+test.EnvID+"/services",
   169  		func(w http.ResponseWriter, r *http.Request) {
   170  			test.AssertEquals(t, r.Method, "GET")
   171  			fmt.Fprint(w, fmt.Sprintf(`[{"id":"%s","label":"%s"}]`, test.SvcID, test.DownStream))
   172  		},
   173  	)
   174  
   175  	// test
   176  	err := CmdCreate(certName, pubKeyPath, privKeyPath, test.DownStream, false, false, false, New(settings), services.New(settings), ssl.New(settings))
   177  
   178  	// assert
   179  	if err == nil {
   180  		t.Fatalf("Expected error but found nil")
   181  	}
   182  }
   183  
   184  func createCertFiles() error {
   185  	cert, err := os.OpenFile(pubKeyPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
   186  	if err != nil {
   187  		return err
   188  	}
   189  	defer cert.Close()
   190  	cert.WriteString(pubKey)
   191  	key, err := os.OpenFile(privKeyPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
   192  	if err != nil {
   193  		return err
   194  	}
   195  	defer key.Close()
   196  	key.WriteString(privKey)
   197  	return nil
   198  }
   199  
   200  func cleanupCertFiles() error {
   201  	err := os.Remove(pubKeyPath)
   202  	if err == nil {
   203  		err = os.Remove(privKeyPath)
   204  	}
   205  	return err
   206  }