2020-07-01 13:40:13 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2022-03-18 13:25:34 +00:00
|
|
|
"github.com/smallstep/certificates/api/read"
|
2022-03-30 08:22:22 +00:00
|
|
|
"github.com/smallstep/certificates/api/render"
|
2020-07-01 13:40:13 +00:00
|
|
|
"github.com/smallstep/certificates/errs"
|
|
|
|
)
|
|
|
|
|
|
|
|
// RekeyRequest is the request body for a certificate rekey request.
|
|
|
|
type RekeyRequest struct {
|
2020-07-05 17:10:36 +00:00
|
|
|
CsrPEM CertificateRequest `json:"csr"`
|
2020-07-01 13:40:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Validate checks the fields of the RekeyRequest and returns nil if they are ok
|
|
|
|
// or an error if something is wrong.
|
|
|
|
func (s *RekeyRequest) Validate() error {
|
|
|
|
if s.CsrPEM.CertificateRequest == nil {
|
|
|
|
return errs.BadRequest("missing csr")
|
|
|
|
}
|
|
|
|
if err := s.CsrPEM.CertificateRequest.CheckSignature(); err != nil {
|
2021-11-19 02:44:58 +00:00
|
|
|
return errs.BadRequestErr(err, "invalid csr")
|
2020-07-01 13:40:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Rekey is similar to renew except that the certificate will be renewed with new key from csr.
|
|
|
|
func (h *caHandler) Rekey(w http.ResponseWriter, r *http.Request) {
|
2020-07-03 10:30:22 +00:00
|
|
|
if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
|
2022-03-30 08:22:22 +00:00
|
|
|
render.Error(w, errs.BadRequest("missing client certificate"))
|
2020-07-03 10:30:22 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-07-01 13:40:13 +00:00
|
|
|
var body RekeyRequest
|
2022-03-18 13:25:34 +00:00
|
|
|
if err := read.JSON(r.Body, &body); err != nil {
|
2022-03-30 08:22:22 +00:00
|
|
|
render.Error(w, errs.BadRequestErr(err, "error reading request body"))
|
2020-07-01 13:40:13 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-07-03 10:28:15 +00:00
|
|
|
if err := body.Validate(); err != nil {
|
2022-03-30 08:22:22 +00:00
|
|
|
render.Error(w, err)
|
2020-07-01 13:40:13 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-07-08 06:17:59 +00:00
|
|
|
certChain, err := h.Authority.Rekey(r.TLS.PeerCertificates[0], body.CsrPEM.CertificateRequest.PublicKey)
|
2020-07-01 13:40:13 +00:00
|
|
|
if err != nil {
|
2022-03-30 08:22:22 +00:00
|
|
|
render.Error(w, errs.Wrap(http.StatusInternalServerError, err, "cahandler.Rekey"))
|
2020-07-01 13:40:13 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
certChainPEM := certChainToPEM(certChain)
|
|
|
|
var caPEM Certificate
|
|
|
|
if len(certChainPEM) > 1 {
|
|
|
|
caPEM = certChainPEM[1]
|
|
|
|
}
|
|
|
|
|
2020-08-12 22:50:45 +00:00
|
|
|
LogCertificate(w, certChain[0])
|
2022-03-30 08:22:22 +00:00
|
|
|
render.JSONStatus(w, &SignResponse{
|
2020-07-01 13:40:13 +00:00
|
|
|
ServerPEM: certChainPEM[0],
|
|
|
|
CaPEM: caPEM,
|
|
|
|
CertChainPEM: certChainPEM,
|
|
|
|
TLSOptions: h.Authority.GetTLSOptions(),
|
|
|
|
}, http.StatusCreated)
|
|
|
|
}
|