2019-12-20 21:30:05 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
2022-03-10 04:37:41 +00:00
|
|
|
"crypto/x509"
|
2019-12-20 21:30:05 +00:00
|
|
|
"net/http"
|
2022-03-10 04:37:41 +00:00
|
|
|
"strings"
|
2019-12-20 21:30:05 +00:00
|
|
|
|
2022-03-30 08:22:22 +00:00
|
|
|
"github.com/smallstep/certificates/api/render"
|
2019-12-20 21:30:05 +00:00
|
|
|
"github.com/smallstep/certificates/errs"
|
2022-03-10 04:37:41 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
authorizationHeader = "Authorization"
|
|
|
|
bearerScheme = "Bearer"
|
2019-12-20 21:30:05 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Renew uses the information of certificate in the TLS connection to create a
|
|
|
|
// new one.
|
|
|
|
func (h *caHandler) Renew(w http.ResponseWriter, r *http.Request) {
|
2022-03-10 04:37:41 +00:00
|
|
|
cert, err := h.getPeerCertificate(r)
|
|
|
|
if err != nil {
|
2022-03-30 08:22:22 +00:00
|
|
|
render.Error(w, err)
|
2019-12-20 21:30:05 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-03-10 04:37:41 +00:00
|
|
|
certChain, err := h.Authority.Renew(cert)
|
2019-12-20 21:30:05 +00:00
|
|
|
if err != nil {
|
2022-03-30 08:22:22 +00:00
|
|
|
render.Error(w, errs.Wrap(http.StatusInternalServerError, err, "cahandler.Renew"))
|
2019-12-20 21:30:05 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
certChainPEM := certChainToPEM(certChain)
|
|
|
|
var caPEM Certificate
|
2020-01-24 06:04:34 +00:00
|
|
|
if len(certChainPEM) > 1 {
|
2019-12-20 21:30:05 +00:00
|
|
|
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{
|
2019-12-20 21:30:05 +00:00
|
|
|
ServerPEM: certChainPEM[0],
|
|
|
|
CaPEM: caPEM,
|
|
|
|
CertChainPEM: certChainPEM,
|
|
|
|
TLSOptions: h.Authority.GetTLSOptions(),
|
|
|
|
}, http.StatusCreated)
|
|
|
|
}
|
2022-03-10 04:37:41 +00:00
|
|
|
|
|
|
|
func (h *caHandler) getPeerCertificate(r *http.Request) (*x509.Certificate, error) {
|
|
|
|
if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
|
|
|
|
return r.TLS.PeerCertificates[0], nil
|
|
|
|
}
|
|
|
|
if s := r.Header.Get(authorizationHeader); s != "" {
|
|
|
|
if parts := strings.SplitN(s, bearerScheme+" ", 2); len(parts) == 2 {
|
2022-03-11 04:21:01 +00:00
|
|
|
return h.Authority.AuthorizeRenewToken(r.Context(), parts[1])
|
2022-03-10 04:37:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, errs.BadRequest("missing client certificate")
|
|
|
|
}
|