initca_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package initca
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "net/http"
  6. "net/http/httptest"
  7. "testing"
  8. "github.com/cloudflare/cfssl/csr"
  9. )
  10. func csrData(t *testing.T) *bytes.Reader {
  11. req := &csr.CertificateRequest{
  12. Names: []csr.Name{
  13. {
  14. C: "US",
  15. ST: "California",
  16. L: "San Francisco",
  17. O: "CloudFlare",
  18. OU: "Systems Engineering",
  19. },
  20. },
  21. CN: "cloudflare.com",
  22. Hosts: []string{"cloudflare.com"},
  23. KeyRequest: csr.NewBasicKeyRequest(),
  24. }
  25. csrBytes, err := json.Marshal(req)
  26. if err != nil {
  27. t.Fatal(err)
  28. }
  29. return bytes.NewReader(csrBytes)
  30. }
  31. func TestInitCARESTfulVerbs(t *testing.T) {
  32. ts := httptest.NewServer(NewHandler())
  33. data := csrData(t)
  34. // POST should work.
  35. req, _ := http.NewRequest("POST", ts.URL, data)
  36. resp, _ := http.DefaultClient.Do(req)
  37. if resp.StatusCode != http.StatusOK {
  38. t.Fatal(resp.Status)
  39. }
  40. // Test GET, PUT, DELETE and whatever, expect 400 errors.
  41. req, _ = http.NewRequest("GET", ts.URL, data)
  42. resp, _ = http.DefaultClient.Do(req)
  43. if resp.StatusCode != http.StatusMethodNotAllowed {
  44. t.Fatal(resp.Status)
  45. }
  46. req, _ = http.NewRequest("PUT", ts.URL, data)
  47. resp, _ = http.DefaultClient.Do(req)
  48. if resp.StatusCode != http.StatusMethodNotAllowed {
  49. t.Fatal(resp.Status)
  50. }
  51. req, _ = http.NewRequest("DELETE", ts.URL, data)
  52. resp, _ = http.DefaultClient.Do(req)
  53. if resp.StatusCode != http.StatusMethodNotAllowed {
  54. t.Fatal(resp.Status)
  55. }
  56. req, _ = http.NewRequest("WHATEVER", ts.URL, data)
  57. resp, _ = http.DefaultClient.Do(req)
  58. if resp.StatusCode != http.StatusMethodNotAllowed {
  59. t.Fatal(resp.Status)
  60. }
  61. }
  62. func TestBadRequestBody(t *testing.T) {
  63. ts := httptest.NewServer(NewHandler())
  64. req, _ := http.NewRequest("POST", ts.URL, nil)
  65. resp, _ := http.DefaultClient.Do(req)
  66. if resp.StatusCode == http.StatusOK {
  67. t.Fatal(resp.Status)
  68. }
  69. }
  70. func TestBadRequestBody_2(t *testing.T) {
  71. ts := httptest.NewServer(NewHandler())
  72. r := &csr.CertificateRequest{}
  73. csrBytes, err := json.Marshal(r)
  74. if err != nil {
  75. t.Fatal(err)
  76. }
  77. data := bytes.NewReader(csrBytes)
  78. req, _ := http.NewRequest("POST", ts.URL, data)
  79. resp, _ := http.DefaultClient.Do(req)
  80. if resp.StatusCode == http.StatusOK {
  81. t.Fatal(resp.Status)
  82. }
  83. }