linker.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package acme
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "github.com/go-chi/chi/v5"
  10. "github.com/smallstep/certificates/api/render"
  11. "github.com/smallstep/certificates/authority"
  12. "github.com/smallstep/certificates/authority/provisioner"
  13. )
  14. // LinkType captures the link type.
  15. type LinkType int
  16. const (
  17. // NewNonceLinkType new-nonce
  18. NewNonceLinkType LinkType = iota
  19. // NewAccountLinkType new-account
  20. NewAccountLinkType
  21. // AccountLinkType account
  22. AccountLinkType
  23. // OrderLinkType order
  24. OrderLinkType
  25. // NewOrderLinkType new-order
  26. NewOrderLinkType
  27. // OrdersByAccountLinkType list of orders owned by account
  28. OrdersByAccountLinkType
  29. // FinalizeLinkType finalize order
  30. FinalizeLinkType
  31. // NewAuthzLinkType authz
  32. NewAuthzLinkType
  33. // AuthzLinkType new-authz
  34. AuthzLinkType
  35. // ChallengeLinkType challenge
  36. ChallengeLinkType
  37. // CertificateLinkType certificate
  38. CertificateLinkType
  39. // DirectoryLinkType directory
  40. DirectoryLinkType
  41. // RevokeCertLinkType revoke certificate
  42. RevokeCertLinkType
  43. // KeyChangeLinkType key rollover
  44. KeyChangeLinkType
  45. )
  46. func (l LinkType) String() string {
  47. switch l {
  48. case NewNonceLinkType:
  49. return "new-nonce"
  50. case NewAccountLinkType:
  51. return "new-account"
  52. case AccountLinkType:
  53. return "account"
  54. case NewOrderLinkType:
  55. return "new-order"
  56. case OrderLinkType:
  57. return "order"
  58. case NewAuthzLinkType:
  59. return "new-authz"
  60. case AuthzLinkType:
  61. return "authz"
  62. case ChallengeLinkType:
  63. return "challenge"
  64. case CertificateLinkType:
  65. return "certificate"
  66. case DirectoryLinkType:
  67. return "directory"
  68. case RevokeCertLinkType:
  69. return "revoke-cert"
  70. case KeyChangeLinkType:
  71. return "key-change"
  72. default:
  73. return fmt.Sprintf("unexpected LinkType '%d'", int(l))
  74. }
  75. }
  76. func GetUnescapedPathSuffix(typ LinkType, provisionerName string, inputs ...string) string {
  77. switch typ {
  78. case NewNonceLinkType, NewAccountLinkType, NewOrderLinkType, NewAuthzLinkType, DirectoryLinkType, KeyChangeLinkType, RevokeCertLinkType:
  79. return fmt.Sprintf("/%s/%s", provisionerName, typ)
  80. case AccountLinkType, OrderLinkType, AuthzLinkType, CertificateLinkType:
  81. return fmt.Sprintf("/%s/%s/%s", provisionerName, typ, inputs[0])
  82. case ChallengeLinkType:
  83. return fmt.Sprintf("/%s/%s/%s/%s", provisionerName, typ, inputs[0], inputs[1])
  84. case OrdersByAccountLinkType:
  85. return fmt.Sprintf("/%s/%s/%s/orders", provisionerName, AccountLinkType, inputs[0])
  86. case FinalizeLinkType:
  87. return fmt.Sprintf("/%s/%s/%s/finalize", provisionerName, OrderLinkType, inputs[0])
  88. default:
  89. return ""
  90. }
  91. }
  92. // NewLinker returns a new Directory type.
  93. func NewLinker(dns, prefix string) Linker {
  94. _, _, err := net.SplitHostPort(dns)
  95. if err != nil && strings.Contains(err.Error(), "too many colons in address") {
  96. // this is most probably an IPv6 without brackets, e.g. ::1, 2001:0db8:85a3:0000:0000:8a2e:0370:7334
  97. // in case a port was appended to this wrong format, we try to extract the port, then check if it's
  98. // still a valid IPv6: 2001:0db8:85a3:0000:0000:8a2e:0370:7334:8443 (8443 is the port). If none of
  99. // these cases, then the input dns is not changed.
  100. lastIndex := strings.LastIndex(dns, ":")
  101. hostPart, portPart := dns[:lastIndex], dns[lastIndex+1:]
  102. if ip := net.ParseIP(hostPart); ip != nil {
  103. dns = "[" + hostPart + "]:" + portPart
  104. } else if ip := net.ParseIP(dns); ip != nil {
  105. dns = "[" + dns + "]"
  106. }
  107. }
  108. return &linker{prefix: prefix, dns: dns}
  109. }
  110. // Linker interface for generating links for ACME resources.
  111. type Linker interface {
  112. GetLink(ctx context.Context, typ LinkType, inputs ...string) string
  113. Middleware(http.Handler) http.Handler
  114. LinkOrder(ctx context.Context, o *Order)
  115. LinkAccount(ctx context.Context, o *Account)
  116. LinkChallenge(ctx context.Context, o *Challenge, azID string)
  117. LinkAuthorization(ctx context.Context, o *Authorization)
  118. LinkOrdersByAccountID(ctx context.Context, orders []string)
  119. }
  120. type linkerKey struct{}
  121. // NewLinkerContext adds the given linker to the context.
  122. func NewLinkerContext(ctx context.Context, v Linker) context.Context {
  123. return context.WithValue(ctx, linkerKey{}, v)
  124. }
  125. // LinkerFromContext returns the current linker from the given context.
  126. func LinkerFromContext(ctx context.Context) (v Linker, ok bool) {
  127. v, ok = ctx.Value(linkerKey{}).(Linker)
  128. return
  129. }
  130. // MustLinkerFromContext returns the current linker from the given context. It
  131. // will panic if it's not in the context.
  132. func MustLinkerFromContext(ctx context.Context) Linker {
  133. if v, ok := LinkerFromContext(ctx); !ok {
  134. panic("acme linker is not the context")
  135. } else {
  136. return v
  137. }
  138. }
  139. type baseURLKey struct{}
  140. func newBaseURLContext(ctx context.Context, r *http.Request) context.Context {
  141. var u *url.URL
  142. if r.Host != "" {
  143. u = &url.URL{Scheme: "https", Host: r.Host}
  144. }
  145. return context.WithValue(ctx, baseURLKey{}, u)
  146. }
  147. func baseURLFromContext(ctx context.Context) *url.URL {
  148. if u, ok := ctx.Value(baseURLKey{}).(*url.URL); ok {
  149. return u
  150. }
  151. return nil
  152. }
  153. // linker generates ACME links.
  154. type linker struct {
  155. prefix string
  156. dns string
  157. }
  158. // Middleware gets the provisioner and current url from the request and sets
  159. // them in the context so we can use the linker to create ACME links.
  160. func (l *linker) Middleware(next http.Handler) http.Handler {
  161. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  162. // Add base url to the context.
  163. ctx := newBaseURLContext(r.Context(), r)
  164. // Add provisioner to the context.
  165. nameEscaped := chi.URLParam(r, "provisionerID")
  166. name, err := url.PathUnescape(nameEscaped)
  167. if err != nil {
  168. render.Error(w, WrapErrorISE(err, "error url unescaping provisioner name '%s'", nameEscaped))
  169. return
  170. }
  171. p, err := authority.MustFromContext(ctx).LoadProvisionerByName(name)
  172. if err != nil {
  173. render.Error(w, err)
  174. return
  175. }
  176. acmeProv, ok := p.(*provisioner.ACME)
  177. if !ok {
  178. render.Error(w, NewError(ErrorAccountDoesNotExistType, "provisioner must be of type ACME"))
  179. return
  180. }
  181. ctx = NewProvisionerContext(ctx, Provisioner(acmeProv))
  182. next.ServeHTTP(w, r.WithContext(ctx))
  183. })
  184. }
  185. // GetLink is a helper for GetLinkExplicit.
  186. func (l *linker) GetLink(ctx context.Context, typ LinkType, inputs ...string) string {
  187. var name string
  188. if p, ok := ProvisionerFromContext(ctx); ok {
  189. name = p.GetName()
  190. }
  191. var u url.URL
  192. if baseURL := baseURLFromContext(ctx); baseURL != nil {
  193. u = *baseURL
  194. }
  195. if u.Scheme == "" {
  196. u.Scheme = "https"
  197. }
  198. if u.Host == "" {
  199. u.Host = l.dns
  200. }
  201. u.Path = l.prefix + GetUnescapedPathSuffix(typ, name, inputs...)
  202. return u.String()
  203. }
  204. // LinkOrder sets the ACME links required by an ACME order.
  205. func (l *linker) LinkOrder(ctx context.Context, o *Order) {
  206. o.AuthorizationURLs = make([]string, len(o.AuthorizationIDs))
  207. for i, azID := range o.AuthorizationIDs {
  208. o.AuthorizationURLs[i] = l.GetLink(ctx, AuthzLinkType, azID)
  209. }
  210. o.FinalizeURL = l.GetLink(ctx, FinalizeLinkType, o.ID)
  211. if o.CertificateID != "" {
  212. o.CertificateURL = l.GetLink(ctx, CertificateLinkType, o.CertificateID)
  213. }
  214. }
  215. // LinkAccount sets the ACME links required by an ACME account.
  216. func (l *linker) LinkAccount(ctx context.Context, acc *Account) {
  217. acc.OrdersURL = l.GetLink(ctx, OrdersByAccountLinkType, acc.ID)
  218. }
  219. // LinkChallenge sets the ACME links required by an ACME challenge.
  220. func (l *linker) LinkChallenge(ctx context.Context, ch *Challenge, azID string) {
  221. ch.URL = l.GetLink(ctx, ChallengeLinkType, azID, ch.ID)
  222. }
  223. // LinkAuthorization sets the ACME links required by an ACME authorization.
  224. func (l *linker) LinkAuthorization(ctx context.Context, az *Authorization) {
  225. for _, ch := range az.Challenges {
  226. l.LinkChallenge(ctx, ch, az.ID)
  227. }
  228. }
  229. // LinkOrdersByAccountID converts each order ID to an ACME link.
  230. func (l *linker) LinkOrdersByAccountID(ctx context.Context, orders []string) {
  231. for i, id := range orders {
  232. orders[i] = l.GetLink(ctx, OrderLinkType, id)
  233. }
  234. }