client.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package acme
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "net"
  6. "net/http"
  7. "time"
  8. )
  9. // Client is the interface used to verify ACME challenges.
  10. type Client interface {
  11. // Get issues an HTTP GET to the specified URL.
  12. Get(url string) (*http.Response, error)
  13. // LookupTXT returns the DNS TXT records for the given domain name.
  14. LookupTxt(name string) ([]string, error)
  15. // TLSDial connects to the given network address using net.Dialer and then
  16. // initiates a TLS handshake, returning the resulting TLS connection.
  17. TLSDial(network, addr string, config *tls.Config) (*tls.Conn, error)
  18. }
  19. type clientKey struct{}
  20. // NewClientContext adds the given client to the context.
  21. func NewClientContext(ctx context.Context, c Client) context.Context {
  22. return context.WithValue(ctx, clientKey{}, c)
  23. }
  24. // ClientFromContext returns the current client from the given context.
  25. func ClientFromContext(ctx context.Context) (c Client, ok bool) {
  26. c, ok = ctx.Value(clientKey{}).(Client)
  27. return
  28. }
  29. // MustClientFromContext returns the current client from the given context. It will
  30. // return a new instance of the client if it does not exist.
  31. func MustClientFromContext(ctx context.Context) Client {
  32. c, ok := ClientFromContext(ctx)
  33. if !ok {
  34. return NewClient()
  35. }
  36. return c
  37. }
  38. type client struct {
  39. http *http.Client
  40. dialer *net.Dialer
  41. }
  42. // NewClient returns an implementation of Client for verifying ACME challenges.
  43. func NewClient() Client {
  44. return &client{
  45. http: &http.Client{
  46. Timeout: 30 * time.Second,
  47. Transport: &http.Transport{
  48. Proxy: http.ProxyFromEnvironment,
  49. TLSClientConfig: &tls.Config{
  50. //nolint:gosec // used on tls-alpn-01 challenge
  51. InsecureSkipVerify: true, // lgtm[go/disabled-certificate-check]
  52. },
  53. },
  54. },
  55. dialer: &net.Dialer{
  56. Timeout: 30 * time.Second,
  57. },
  58. }
  59. }
  60. func (c *client) Get(url string) (*http.Response, error) {
  61. return c.http.Get(url)
  62. }
  63. func (c *client) LookupTxt(name string) ([]string, error) {
  64. return net.LookupTXT(name)
  65. }
  66. func (c *client) TLSDial(network, addr string, config *tls.Config) (*tls.Conn, error) {
  67. return tls.DialWithDialer(c.dialer, network, addr, config)
  68. }