4
0

renew.go 1.7 KB

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