gencrl_test.go 2.2 KB

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