renew.go 1.5 KB

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