renew.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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/authority"
  8. "github.com/smallstep/certificates/errs"
  9. )
  10. const (
  11. authorizationHeader = "Authorization"
  12. bearerScheme = "Bearer"
  13. )
  14. // Renew uses the information of certificate in the TLS connection to create a
  15. // new one.
  16. func Renew(w http.ResponseWriter, r *http.Request) {
  17. ctx := r.Context()
  18. // Get the leaf certificate from the peer or the token.
  19. cert, token, err := getPeerCertificate(r)
  20. if err != nil {
  21. render.Error(w, r, err)
  22. return
  23. }
  24. // The token can be used by RAs to renew a certificate.
  25. if token != "" {
  26. ctx = authority.NewTokenContext(ctx, token)
  27. logOtt(w, token)
  28. }
  29. a := mustAuthority(ctx)
  30. certChain, err := a.RenewContext(ctx, cert, nil)
  31. if err != nil {
  32. render.Error(w, r, errs.Wrap(http.StatusInternalServerError, err, "cahandler.Renew"))
  33. return
  34. }
  35. certChainPEM := certChainToPEM(certChain)
  36. var caPEM Certificate
  37. if len(certChainPEM) > 1 {
  38. caPEM = certChainPEM[1]
  39. }
  40. LogCertificate(w, certChain[0])
  41. render.JSONStatus(w, r, &SignResponse{
  42. ServerPEM: certChainPEM[0],
  43. CaPEM: caPEM,
  44. CertChainPEM: certChainPEM,
  45. TLSOptions: a.GetTLSOptions(),
  46. }, http.StatusCreated)
  47. }
  48. func getPeerCertificate(r *http.Request) (*x509.Certificate, string, error) {
  49. if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
  50. return r.TLS.PeerCertificates[0], "", nil
  51. }
  52. if s := r.Header.Get(authorizationHeader); s != "" {
  53. if parts := strings.SplitN(s, bearerScheme+" ", 2); len(parts) == 2 {
  54. ctx := r.Context()
  55. peer, err := mustAuthority(ctx).AuthorizeRenewToken(ctx, parts[1])
  56. return peer, parts[1], err
  57. }
  58. }
  59. return nil, "", errs.BadRequest("missing client certificate")
  60. }