renew.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 Renew(w http.ResponseWriter, r *http.Request) {
  16. cert, err := getPeerCertificate(r)
  17. if err != nil {
  18. render.Error(w, err)
  19. return
  20. }
  21. a := mustAuthority(r.Context())
  22. certChain, err := a.Renew(cert)
  23. if err != nil {
  24. render.Error(w, errs.Wrap(http.StatusInternalServerError, err, "cahandler.Renew"))
  25. return
  26. }
  27. certChainPEM := certChainToPEM(certChain)
  28. var caPEM Certificate
  29. if len(certChainPEM) > 1 {
  30. caPEM = certChainPEM[1]
  31. }
  32. LogCertificate(w, certChain[0])
  33. render.JSONStatus(w, &SignResponse{
  34. ServerPEM: certChainPEM[0],
  35. CaPEM: caPEM,
  36. CertChainPEM: certChainPEM,
  37. TLSOptions: a.GetTLSOptions(),
  38. }, http.StatusCreated)
  39. }
  40. func getPeerCertificate(r *http.Request) (*x509.Certificate, error) {
  41. if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
  42. return r.TLS.PeerCertificates[0], nil
  43. }
  44. if s := r.Header.Get(authorizationHeader); s != "" {
  45. if parts := strings.SplitN(s, bearerScheme+" ", 2); len(parts) == 2 {
  46. ctx := r.Context()
  47. return mustAuthority(ctx).AuthorizeRenewToken(ctx, parts[1])
  48. }
  49. }
  50. return nil, errs.BadRequest("missing client certificate")
  51. }