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.
|
2022-04-26 19:58:40 +00:00
|
|
|
func Renew(w http.ResponseWriter, r *http.Request) {
|
2022-09-20 22:46:59 +00:00
|
|
|
//nolint:contextcheck // the reqest has the context
|
2022-04-26 19:58:40 +00:00
|
|
|
cert, err := getPeerCertificate(r)
|
2022-03-10 04:37:41 +00:00
|
|
|
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-04-26 19:58:40 +00:00
|
|
|
a := mustAuthority(r.Context())
|
|
|
|
certChain, err := a.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,
|
2022-04-26 19:58:40 +00:00
|
|
|
TLSOptions: a.GetTLSOptions(),
|
2019-12-20 21:30:05 +00:00
|
|
|
}, http.StatusCreated)
|
|
|
|
}
|
2022-03-10 04:37:41 +00:00
|
|
|
|
2022-04-26 19:58:40 +00:00
|
|
|
func getPeerCertificate(r *http.Request) (*x509.Certificate, error) {
|
2022-03-10 04:37:41 +00:00
|
|
|
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-04-26 19:58:40 +00:00
|
|
|
ctx := r.Context()
|
|
|
|
return mustAuthority(ctx).AuthorizeRenewToken(ctx, parts[1])
|
2022-03-10 04:37:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, errs.BadRequest("missing client certificate")
|
|
|
|
}
|