linker.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. var (
  134. v Linker
  135. ok bool
  136. )
  137. if v, ok = LinkerFromContext(ctx); !ok {
  138. panic("acme linker is not the context")
  139. }
  140. return v
  141. }
  142. type baseURLKey struct{}
  143. func newBaseURLContext(ctx context.Context, r *http.Request) context.Context {
  144. var u *url.URL
  145. if r.Host != "" {
  146. u = &url.URL{Scheme: "https", Host: r.Host}
  147. }
  148. return context.WithValue(ctx, baseURLKey{}, u)
  149. }
  150. func baseURLFromContext(ctx context.Context) *url.URL {
  151. if u, ok := ctx.Value(baseURLKey{}).(*url.URL); ok {
  152. return u
  153. }
  154. return nil
  155. }
  156. // linker generates ACME links.
  157. type linker struct {
  158. prefix string
  159. dns string
  160. }
  161. // Middleware gets the provisioner and current url from the request and sets
  162. // them in the context so we can use the linker to create ACME links.
  163. func (l *linker) Middleware(next http.Handler) http.Handler {
  164. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  165. // Add base url to the context.
  166. ctx := newBaseURLContext(r.Context(), r)
  167. // Add provisioner to the context.
  168. nameEscaped := chi.URLParam(r, "provisionerID")
  169. name, err := url.PathUnescape(nameEscaped)
  170. if err != nil {
  171. render.Error(w, WrapErrorISE(err, "error url unescaping provisioner name '%s'", nameEscaped))
  172. return
  173. }
  174. p, err := authority.MustFromContext(ctx).LoadProvisionerByName(name)
  175. if err != nil {
  176. render.Error(w, err)
  177. return
  178. }
  179. acmeProv, ok := p.(*provisioner.ACME)
  180. if !ok {
  181. render.Error(w, NewError(ErrorAccountDoesNotExistType, "provisioner must be of type ACME"))
  182. return
  183. }
  184. ctx = NewProvisionerContext(ctx, Provisioner(acmeProv))
  185. next.ServeHTTP(w, r.WithContext(ctx))
  186. })
  187. }
  188. // GetLink is a helper for GetLinkExplicit.
  189. func (l *linker) GetLink(ctx context.Context, typ LinkType, inputs ...string) string {
  190. var name string
  191. if p, ok := ProvisionerFromContext(ctx); ok {
  192. name = p.GetName()
  193. }
  194. var u url.URL
  195. if baseURL := baseURLFromContext(ctx); baseURL != nil {
  196. u = *baseURL
  197. }
  198. if u.Scheme == "" {
  199. u.Scheme = "https"
  200. }
  201. if u.Host == "" {
  202. u.Host = l.dns
  203. }
  204. u.Path = l.prefix + GetUnescapedPathSuffix(typ, name, inputs...)
  205. return u.String()
  206. }
  207. // LinkOrder sets the ACME links required by an ACME order.
  208. func (l *linker) LinkOrder(ctx context.Context, o *Order) {
  209. o.AuthorizationURLs = make([]string, len(o.AuthorizationIDs))
  210. for i, azID := range o.AuthorizationIDs {
  211. o.AuthorizationURLs[i] = l.GetLink(ctx, AuthzLinkType, azID)
  212. }
  213. o.FinalizeURL = l.GetLink(ctx, FinalizeLinkType, o.ID)
  214. if o.CertificateID != "" {
  215. o.CertificateURL = l.GetLink(ctx, CertificateLinkType, o.CertificateID)
  216. }
  217. }
  218. // LinkAccount sets the ACME links required by an ACME account.
  219. func (l *linker) LinkAccount(ctx context.Context, acc *Account) {
  220. acc.OrdersURL = l.GetLink(ctx, OrdersByAccountLinkType, acc.ID)
  221. }
  222. // LinkChallenge sets the ACME links required by an ACME challenge.
  223. func (l *linker) LinkChallenge(ctx context.Context, ch *Challenge, azID string) {
  224. ch.URL = l.GetLink(ctx, ChallengeLinkType, azID, ch.ID)
  225. }
  226. // LinkAuthorization sets the ACME links required by an ACME authorization.
  227. func (l *linker) LinkAuthorization(ctx context.Context, az *Authorization) {
  228. for _, ch := range az.Challenges {
  229. l.LinkChallenge(ctx, ch, az.ID)
  230. }
  231. }
  232. // LinkOrdersByAccountID converts each order ID to an ACME link.
  233. func (l *linker) LinkOrdersByAccountID(ctx context.Context, orders []string) {
  234. for i, id := range orders {
  235. orders[i] = l.GetLink(ctx, OrderLinkType, id)
  236. }
  237. }