rekey.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package api
  2. import (
  3. "net/http"
  4. "github.com/smallstep/certificates/api/read"
  5. "github.com/smallstep/certificates/errs"
  6. )
  7. // RekeyRequest is the request body for a certificate rekey request.
  8. type RekeyRequest struct {
  9. CsrPEM CertificateRequest `json:"csr"`
  10. }
  11. // Validate checks the fields of the RekeyRequest and returns nil if they are ok
  12. // or an error if something is wrong.
  13. func (s *RekeyRequest) Validate() error {
  14. if s.CsrPEM.CertificateRequest == nil {
  15. return errs.BadRequest("missing csr")
  16. }
  17. if err := s.CsrPEM.CertificateRequest.CheckSignature(); err != nil {
  18. return errs.BadRequestErr(err, "invalid csr")
  19. }
  20. return nil
  21. }
  22. // Rekey is similar to renew except that the certificate will be renewed with new key from csr.
  23. func (h *caHandler) Rekey(w http.ResponseWriter, r *http.Request) {
  24. if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
  25. WriteError(w, errs.BadRequest("missing client certificate"))
  26. return
  27. }
  28. var body RekeyRequest
  29. if err := read.JSON(r.Body, &body); err != nil {
  30. WriteError(w, errs.BadRequestErr(err, "error reading request body"))
  31. return
  32. }
  33. if err := body.Validate(); err != nil {
  34. WriteError(w, err)
  35. return
  36. }
  37. certChain, err := h.Authority.Rekey(r.TLS.PeerCertificates[0], body.CsrPEM.CertificateRequest.PublicKey)
  38. if err != nil {
  39. WriteError(w, errs.Wrap(http.StatusInternalServerError, err, "cahandler.Rekey"))
  40. return
  41. }
  42. certChainPEM := certChainToPEM(certChain)
  43. var caPEM Certificate
  44. if len(certChainPEM) > 1 {
  45. caPEM = certChainPEM[1]
  46. }
  47. LogCertificate(w, certChain[0])
  48. JSONStatus(w, &SignResponse{
  49. ServerPEM: certChainPEM[0],
  50. CaPEM: caPEM,
  51. CertChainPEM: certChainPEM,
  52. TLSOptions: h.Authority.GetTLSOptions(),
  53. }, http.StatusCreated)
  54. }