webhook.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. package webhook
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/hmac"
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "encoding/hex"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "log"
  13. "net/http"
  14. "time"
  15. "github.com/ryboe/q"
  16. )
  17. type Controller struct {
  18. client *http.Client
  19. webhook *Webhook
  20. }
  21. func New(options ...ControllerOption) (*Controller, error) {
  22. c := &Controller{
  23. client: http.DefaultClient,
  24. webhook: &Webhook{},
  25. }
  26. for _, apply := range options {
  27. if err := apply(c); err != nil {
  28. return nil, err
  29. }
  30. }
  31. return c, nil
  32. }
  33. func (c *Controller) Validate(challenge string) (bool, error) {
  34. req := &Request{
  35. Challenge: challenge,
  36. }
  37. client := c.client
  38. if client == nil {
  39. client = http.DefaultClient
  40. }
  41. resp, err := c.webhook.Do(client, req)
  42. if err != nil {
  43. q.Q(err)
  44. return false, fmt.Errorf("failed performing webhook request: %w", err)
  45. }
  46. if resp == nil {
  47. return false, nil
  48. }
  49. return true, nil
  50. }
  51. type Webhook struct {
  52. URL string
  53. DisableTLSClientAuth bool
  54. Secret string
  55. BearerToken string
  56. BasicAuth struct {
  57. Username string
  58. Password string
  59. }
  60. }
  61. func (w *Webhook) Do(client *http.Client, req *Request) (*Response, error) {
  62. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  63. defer cancel()
  64. reqBytes, err := json.Marshal(req)
  65. if err != nil {
  66. return nil, err
  67. }
  68. retries := 1
  69. retry:
  70. r, err := http.NewRequestWithContext(ctx, "POST", w.URL, bytes.NewReader(reqBytes))
  71. if err != nil {
  72. return nil, err
  73. }
  74. if w.Secret != "" {
  75. secret, err := base64.StdEncoding.DecodeString(w.Secret)
  76. if err != nil {
  77. return nil, err
  78. }
  79. sig := hmac.New(sha256.New, secret).Sum(reqBytes)
  80. r.Header.Set("X-Smallstep-Signature", hex.EncodeToString(sig))
  81. //req.Header.Set("X-Smallstep-Webhook-ID", w.ID)
  82. }
  83. if w.BearerToken != "" {
  84. r.Header.Set("Authorization", fmt.Sprintf("Bearer %s", w.BearerToken))
  85. } else if w.BasicAuth.Username != "" || w.BasicAuth.Password != "" {
  86. r.SetBasicAuth(w.BasicAuth.Username, w.BasicAuth.Password)
  87. }
  88. if w.DisableTLSClientAuth {
  89. transport, ok := client.Transport.(*http.Transport)
  90. if !ok {
  91. return nil, errors.New("client transport is not a *http.Transport")
  92. }
  93. transport = transport.Clone()
  94. tlsConfig := transport.TLSClientConfig.Clone()
  95. tlsConfig.GetClientCertificate = nil
  96. tlsConfig.Certificates = nil
  97. transport.TLSClientConfig = tlsConfig
  98. client = &http.Client{
  99. Transport: transport,
  100. }
  101. }
  102. resp, err := client.Do(r)
  103. if err != nil {
  104. if errors.Is(err, context.DeadlineExceeded) {
  105. return nil, err
  106. } else if retries > 0 {
  107. retries--
  108. time.Sleep(time.Second)
  109. goto retry
  110. }
  111. return nil, err
  112. }
  113. defer func() {
  114. if err := resp.Body.Close(); err != nil {
  115. // TODO: return this error instead of (just) logging?
  116. log.Printf("failed to close body of response from %s", w.URL)
  117. }
  118. }()
  119. if resp.StatusCode >= 500 && retries > 0 {
  120. retries--
  121. time.Sleep(time.Second)
  122. goto retry
  123. }
  124. if resp.StatusCode >= 400 {
  125. return nil, fmt.Errorf("webhook server responded with %d", resp.StatusCode)
  126. }
  127. respBody := &Response{}
  128. // TODO: decide on the JSON structure for the response (if any); HTTP status code may be enough.
  129. // if err := json.NewDecoder(resp.Body).Decode(respBody); err != nil {
  130. // return nil, err
  131. // }
  132. return respBody, nil
  133. }
  134. type Request struct {
  135. Challenge string `json:"challenge"`
  136. }
  137. type Response struct {
  138. // TODO: define expected response format? Or do we consider 200 OK enough?
  139. Allow bool `json:"allow"`
  140. }