linker.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. //nolint:gosec // operating on internally defined inputs
  82. return fmt.Sprintf("/%s/%s/%s", provisionerName, typ, inputs[0])
  83. case ChallengeLinkType:
  84. //nolint:gosec // operating on internally defined inputs
  85. return fmt.Sprintf("/%s/%s/%s/%s", provisionerName, typ, inputs[0], inputs[1])
  86. case OrdersByAccountLinkType:
  87. //nolint:gosec // operating on internally defined inputs
  88. return fmt.Sprintf("/%s/%s/%s/orders", provisionerName, AccountLinkType, inputs[0])
  89. case FinalizeLinkType:
  90. //nolint:gosec // operating on internally defined inputs
  91. return fmt.Sprintf("/%s/%s/%s/finalize", provisionerName, OrderLinkType, inputs[0])
  92. default:
  93. return ""
  94. }
  95. }
  96. // NewLinker returns a new Directory type.
  97. func NewLinker(dns, prefix string) Linker {
  98. _, _, err := net.SplitHostPort(dns)
  99. if err != nil && strings.Contains(err.Error(), "too many colons in address") {
  100. // this is most probably an IPv6 without brackets, e.g. ::1, 2001:0db8:85a3:0000:0000:8a2e:0370:7334
  101. // in case a port was appended to this wrong format, we try to extract the port, then check if it's
  102. // still a valid IPv6: 2001:0db8:85a3:0000:0000:8a2e:0370:7334:8443 (8443 is the port). If none of
  103. // these cases, then the input dns is not changed.
  104. lastIndex := strings.LastIndex(dns, ":")
  105. hostPart, portPart := dns[:lastIndex], dns[lastIndex+1:]
  106. if ip := net.ParseIP(hostPart); ip != nil {
  107. dns = "[" + hostPart + "]:" + portPart
  108. } else if ip := net.ParseIP(dns); ip != nil {
  109. dns = "[" + dns + "]"
  110. }
  111. }
  112. return &linker{prefix: prefix, dns: dns}
  113. }
  114. // Linker interface for generating links for ACME resources.
  115. type Linker interface {
  116. GetLink(ctx context.Context, typ LinkType, inputs ...string) string
  117. Middleware(http.Handler) http.Handler
  118. LinkOrder(ctx context.Context, o *Order)
  119. LinkAccount(ctx context.Context, o *Account)
  120. LinkChallenge(ctx context.Context, o *Challenge, azID string)
  121. LinkAuthorization(ctx context.Context, o *Authorization)
  122. LinkOrdersByAccountID(ctx context.Context, orders []string)
  123. }
  124. type linkerKey struct{}
  125. // NewLinkerContext adds the given linker to the context.
  126. func NewLinkerContext(ctx context.Context, v Linker) context.Context {
  127. return context.WithValue(ctx, linkerKey{}, v)
  128. }
  129. // LinkerFromContext returns the current linker from the given context.
  130. func LinkerFromContext(ctx context.Context) (v Linker, ok bool) {
  131. v, ok = ctx.Value(linkerKey{}).(Linker)
  132. return
  133. }
  134. // MustLinkerFromContext returns the current linker from the given context. It
  135. // will panic if it's not in the context.
  136. func MustLinkerFromContext(ctx context.Context) Linker {
  137. var (
  138. v Linker
  139. ok bool
  140. )
  141. if v, ok = LinkerFromContext(ctx); !ok {
  142. panic("acme linker is not the context")
  143. }
  144. return v
  145. }
  146. type baseURLKey struct{}
  147. func newBaseURLContext(ctx context.Context, r *http.Request) context.Context {
  148. var u *url.URL
  149. if r.Host != "" {
  150. u = &url.URL{Scheme: "https", Host: r.Host}
  151. }
  152. return context.WithValue(ctx, baseURLKey{}, u)
  153. }
  154. func baseURLFromContext(ctx context.Context) *url.URL {
  155. if u, ok := ctx.Value(baseURLKey{}).(*url.URL); ok {
  156. return u
  157. }
  158. return nil
  159. }
  160. // linker generates ACME links.
  161. type linker struct {
  162. prefix string
  163. dns string
  164. }
  165. // Middleware gets the provisioner and current url from the request and sets
  166. // them in the context so we can use the linker to create ACME links.
  167. func (l *linker) Middleware(next http.Handler) http.Handler {
  168. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  169. // Add base url to the context.
  170. ctx := newBaseURLContext(r.Context(), r)
  171. // Add provisioner to the context.
  172. nameEscaped := chi.URLParam(r, "provisionerID")
  173. name, err := url.PathUnescape(nameEscaped)
  174. if err != nil {
  175. render.Error(w, r, WrapErrorISE(err, "error url unescaping provisioner name '%s'", nameEscaped))
  176. return
  177. }
  178. p, err := authority.MustFromContext(ctx).LoadProvisionerByName(name)
  179. if err != nil {
  180. render.Error(w, r, err)
  181. return
  182. }
  183. acmeProv, ok := p.(*provisioner.ACME)
  184. if !ok {
  185. render.Error(w, r, NewError(ErrorAccountDoesNotExistType, "provisioner must be of type ACME"))
  186. return
  187. }
  188. ctx = NewProvisionerContext(ctx, Provisioner(acmeProv))
  189. next.ServeHTTP(w, r.WithContext(ctx))
  190. })
  191. }
  192. // GetLink is a helper for GetLinkExplicit.
  193. func (l *linker) GetLink(ctx context.Context, typ LinkType, inputs ...string) string {
  194. var name string
  195. if p, ok := ProvisionerFromContext(ctx); ok {
  196. name = p.GetName()
  197. }
  198. var u url.URL
  199. if baseURL := baseURLFromContext(ctx); baseURL != nil {
  200. u = *baseURL
  201. }
  202. if u.Scheme == "" {
  203. u.Scheme = "https"
  204. }
  205. if u.Host == "" {
  206. u.Host = l.dns
  207. }
  208. u.Path = l.prefix + GetUnescapedPathSuffix(typ, name, inputs...)
  209. return u.String()
  210. }
  211. // LinkOrder sets the ACME links required by an ACME order.
  212. func (l *linker) LinkOrder(ctx context.Context, o *Order) {
  213. o.AuthorizationURLs = make([]string, len(o.AuthorizationIDs))
  214. for i, azID := range o.AuthorizationIDs {
  215. o.AuthorizationURLs[i] = l.GetLink(ctx, AuthzLinkType, azID)
  216. }
  217. o.FinalizeURL = l.GetLink(ctx, FinalizeLinkType, o.ID)
  218. if o.CertificateID != "" {
  219. o.CertificateURL = l.GetLink(ctx, CertificateLinkType, o.CertificateID)
  220. }
  221. }
  222. // LinkAccount sets the ACME links required by an ACME account.
  223. func (l *linker) LinkAccount(ctx context.Context, acc *Account) {
  224. acc.OrdersURL = l.GetLink(ctx, OrdersByAccountLinkType, acc.ID)
  225. }
  226. // LinkChallenge sets the ACME links required by an ACME challenge.
  227. func (l *linker) LinkChallenge(ctx context.Context, ch *Challenge, azID string) {
  228. ch.URL = l.GetLink(ctx, ChallengeLinkType, azID, ch.ID)
  229. }
  230. // LinkAuthorization sets the ACME links required by an ACME authorization.
  231. func (l *linker) LinkAuthorization(ctx context.Context, az *Authorization) {
  232. for _, ch := range az.Challenges {
  233. l.LinkChallenge(ctx, ch, az.ID)
  234. }
  235. }
  236. // LinkOrdersByAccountID converts each order ID to an ACME link.
  237. func (l *linker) LinkOrdersByAccountID(ctx context.Context, orders []string) {
  238. for i, id := range orders {
  239. orders[i] = l.GetLink(ctx, OrderLinkType, id)
  240. }
  241. }