4
0

rekey.go 1.8 KB

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