renew.go 1.3 KB

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