renew.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package api
  2. import (
  3. "crypto/x509"
  4. "net/http"
  5. "strings"
  6. "github.com/smallstep/certificates/api/render"
  7. "github.com/smallstep/certificates/errs"
  8. )
  9. const (
  10. authorizationHeader = "Authorization"
  11. bearerScheme = "Bearer"
  12. )
  13. // Renew uses the information of certificate in the TLS connection to create a
  14. // new one.
  15. func (h *caHandler) Renew(w http.ResponseWriter, r *http.Request) {
  16. cert, err := h.getPeerCertificate(r)
  17. if err != nil {
  18. render.Error(w, err)
  19. return
  20. }
  21. certChain, err := h.Authority.Renew(cert)
  22. if err != nil {
  23. render.Error(w, errs.Wrap(http.StatusInternalServerError, err, "cahandler.Renew"))
  24. return
  25. }
  26. certChainPEM := certChainToPEM(certChain)
  27. var caPEM Certificate
  28. if len(certChainPEM) > 1 {
  29. caPEM = certChainPEM[1]
  30. }
  31. LogCertificate(w, certChain[0])
  32. render.JSONStatus(w, &SignResponse{
  33. ServerPEM: certChainPEM[0],
  34. CaPEM: caPEM,
  35. CertChainPEM: certChainPEM,
  36. TLSOptions: h.Authority.GetTLSOptions(),
  37. }, http.StatusCreated)
  38. }
  39. func (h *caHandler) getPeerCertificate(r *http.Request) (*x509.Certificate, error) {
  40. if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
  41. return r.TLS.PeerCertificates[0], nil
  42. }
  43. if s := r.Header.Get(authorizationHeader); s != "" {
  44. if parts := strings.SplitN(s, bearerScheme+" ", 2); len(parts) == 2 {
  45. return h.Authority.AuthorizeRenewToken(r.Context(), parts[1])
  46. }
  47. }
  48. return nil, errs.BadRequest("missing client certificate")
  49. }