gencrl_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package gencrl
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "github.com/cloudflare/cfssl/api"
  6. "io/ioutil"
  7. "net/http"
  8. "net/http/httptest"
  9. "testing"
  10. )
  11. const (
  12. cert = "../../crl/testdata/caTwo.pem"
  13. key = "../../crl/testdata/ca-keyTwo.pem"
  14. serialList = "../../crl/testdata/serialList"
  15. expiryTime = "2000"
  16. )
  17. type testJSON struct {
  18. Certificate string
  19. SerialNumber []string
  20. PrivateKey string
  21. ExpiryTime string
  22. ExpectedHTTPStatus int
  23. ExpectedSuccess bool
  24. }
  25. var tester = testJSON{
  26. Certificate: cert,
  27. SerialNumber: []string{"1", "2", "3"},
  28. PrivateKey: key,
  29. ExpiryTime: "2000",
  30. ExpectedHTTPStatus: 200,
  31. ExpectedSuccess: true,
  32. }
  33. func newTestHandler(t *testing.T) http.Handler {
  34. return NewHandler()
  35. }
  36. func TestNewHandler(t *testing.T) {
  37. newTestHandler(t)
  38. }
  39. func newCRLServer(t *testing.T) *httptest.Server {
  40. ts := httptest.NewServer(newTestHandler(t))
  41. return ts
  42. }
  43. func testCRLCreation(t *testing.T, issuingKey, certFile string, expiry string, serialList []string) (resp *http.Response, body []byte) {
  44. ts := newCRLServer(t)
  45. defer ts.Close()
  46. obj := map[string]interface{}{}
  47. if certFile != "" {
  48. c, err := ioutil.ReadFile(certFile)
  49. if err != nil {
  50. t.Fatal(err)
  51. }
  52. obj["certificate"] = string(c)
  53. }
  54. obj["serialNumber"] = serialList
  55. if issuingKey != "" {
  56. c, err := ioutil.ReadFile(issuingKey)
  57. if err != nil {
  58. t.Fatal(err)
  59. }
  60. obj["issuingKey"] = string(c)
  61. }
  62. obj["expireTime"] = expiry
  63. blob, err := json.Marshal(obj)
  64. if err != nil {
  65. t.Fatal(err)
  66. }
  67. resp, err = http.Post(ts.URL, "application/json", bytes.NewReader(blob))
  68. if err != nil {
  69. t.Fatal(err)
  70. }
  71. body, err = ioutil.ReadAll(resp.Body)
  72. if err != nil {
  73. t.Fatal(err)
  74. }
  75. return
  76. }
  77. func TestCRL(t *testing.T) {
  78. resp, body := testCRLCreation(t, tester.PrivateKey, tester.Certificate, tester.ExpiryTime, tester.SerialNumber)
  79. if resp.StatusCode != tester.ExpectedHTTPStatus {
  80. t.Logf("expected: %d, have %d", tester.ExpectedHTTPStatus, resp.StatusCode)
  81. t.Fatal(resp.Status, tester.ExpectedHTTPStatus, string(body))
  82. }
  83. message := new(api.Response)
  84. err := json.Unmarshal(body, message)
  85. if err != nil {
  86. t.Logf("failed to read response body: %v", err)
  87. t.Fatal(resp.Status, tester.ExpectedHTTPStatus, message)
  88. }
  89. }