rate_limiting.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. package cloudflare
  2. import (
  3. "encoding/json"
  4. "net/url"
  5. "strconv"
  6. "github.com/pkg/errors"
  7. )
  8. // RateLimit is a policy than can be applied to limit traffic within a customer domain
  9. type RateLimit struct {
  10. ID string `json:"id,omitempty"`
  11. Disabled bool `json:"disabled,omitempty"`
  12. Description string `json:"description,omitempty"`
  13. Match RateLimitTrafficMatcher `json:"match"`
  14. Bypass []RateLimitKeyValue `json:"bypass,omitempty"`
  15. Threshold int `json:"threshold"`
  16. Period int `json:"period"`
  17. Action RateLimitAction `json:"action"`
  18. Correlate *RateLimitCorrelate `json:"correlate,omitempty"`
  19. }
  20. // RateLimitTrafficMatcher contains the rules that will be used to apply a rate limit to traffic
  21. type RateLimitTrafficMatcher struct {
  22. Request RateLimitRequestMatcher `json:"request"`
  23. Response RateLimitResponseMatcher `json:"response"`
  24. }
  25. // RateLimitRequestMatcher contains the matching rules pertaining to requests
  26. type RateLimitRequestMatcher struct {
  27. Methods []string `json:"methods,omitempty"`
  28. Schemes []string `json:"schemes,omitempty"`
  29. URLPattern string `json:"url,omitempty"`
  30. }
  31. // RateLimitResponseMatcher contains the matching rules pertaining to responses
  32. type RateLimitResponseMatcher struct {
  33. Statuses []int `json:"status,omitempty"`
  34. OriginTraffic *bool `json:"origin_traffic,omitempty"` // api defaults to true so we need an explicit empty value
  35. Headers []RateLimitResponseMatcherHeader `json:"headers,omitempty"`
  36. }
  37. // RateLimitResponseMatcherHeader contains the structure of the origin
  38. // HTTP headers used in request matcher checks.
  39. type RateLimitResponseMatcherHeader struct {
  40. Name string `json:"name"`
  41. Op string `json:"op"`
  42. Value string `json:"value"`
  43. }
  44. // RateLimitKeyValue is k-v formatted as expected in the rate limit description
  45. type RateLimitKeyValue struct {
  46. Name string `json:"name"`
  47. Value string `json:"value"`
  48. }
  49. // RateLimitAction is the action that will be taken when the rate limit threshold is reached
  50. type RateLimitAction struct {
  51. Mode string `json:"mode"`
  52. Timeout int `json:"timeout"`
  53. Response *RateLimitActionResponse `json:"response"`
  54. }
  55. // RateLimitActionResponse is the response that will be returned when rate limit action is triggered
  56. type RateLimitActionResponse struct {
  57. ContentType string `json:"content_type"`
  58. Body string `json:"body"`
  59. }
  60. // RateLimitCorrelate pertainings to NAT support
  61. type RateLimitCorrelate struct {
  62. By string `json:"by"`
  63. }
  64. type rateLimitResponse struct {
  65. Response
  66. Result RateLimit `json:"result"`
  67. }
  68. type rateLimitListResponse struct {
  69. Response
  70. Result []RateLimit `json:"result"`
  71. ResultInfo ResultInfo `json:"result_info"`
  72. }
  73. // CreateRateLimit creates a new rate limit for a zone.
  74. //
  75. // API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-create-a-ratelimit
  76. func (api *API) CreateRateLimit(zoneID string, limit RateLimit) (RateLimit, error) {
  77. uri := "/zones/" + zoneID + "/rate_limits"
  78. res, err := api.makeRequest("POST", uri, limit)
  79. if err != nil {
  80. return RateLimit{}, errors.Wrap(err, errMakeRequestError)
  81. }
  82. var r rateLimitResponse
  83. if err := json.Unmarshal(res, &r); err != nil {
  84. return RateLimit{}, errors.Wrap(err, errUnmarshalError)
  85. }
  86. return r.Result, nil
  87. }
  88. // ListRateLimits returns Rate Limits for a zone, paginated according to the provided options
  89. //
  90. // API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-list-rate-limits
  91. func (api *API) ListRateLimits(zoneID string, pageOpts PaginationOptions) ([]RateLimit, ResultInfo, error) {
  92. v := url.Values{}
  93. if pageOpts.PerPage > 0 {
  94. v.Set("per_page", strconv.Itoa(pageOpts.PerPage))
  95. }
  96. if pageOpts.Page > 0 {
  97. v.Set("page", strconv.Itoa(pageOpts.Page))
  98. }
  99. uri := "/zones/" + zoneID + "/rate_limits"
  100. if len(v) > 0 {
  101. uri = uri + "?" + v.Encode()
  102. }
  103. res, err := api.makeRequest("GET", uri, nil)
  104. if err != nil {
  105. return []RateLimit{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError)
  106. }
  107. var r rateLimitListResponse
  108. err = json.Unmarshal(res, &r)
  109. if err != nil {
  110. return []RateLimit{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError)
  111. }
  112. return r.Result, r.ResultInfo, nil
  113. }
  114. // ListAllRateLimits returns all Rate Limits for a zone.
  115. //
  116. // API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-list-rate-limits
  117. func (api *API) ListAllRateLimits(zoneID string) ([]RateLimit, error) {
  118. pageOpts := PaginationOptions{
  119. PerPage: 100, // this is the max page size allowed
  120. Page: 1,
  121. }
  122. allRateLimits := make([]RateLimit, 0)
  123. for {
  124. rateLimits, resultInfo, err := api.ListRateLimits(zoneID, pageOpts)
  125. if err != nil {
  126. return []RateLimit{}, err
  127. }
  128. allRateLimits = append(allRateLimits, rateLimits...)
  129. // total pages is not returned on this call
  130. // if number of records is less than the max, this must be the last page
  131. // in case TotalCount % PerPage = 0, the last request will return an empty list
  132. if resultInfo.Count < resultInfo.PerPage {
  133. break
  134. }
  135. // continue with the next page
  136. pageOpts.Page = pageOpts.Page + 1
  137. }
  138. return allRateLimits, nil
  139. }
  140. // RateLimit fetches detail about one Rate Limit for a zone.
  141. //
  142. // API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-rate-limit-details
  143. func (api *API) RateLimit(zoneID, limitID string) (RateLimit, error) {
  144. uri := "/zones/" + zoneID + "/rate_limits/" + limitID
  145. res, err := api.makeRequest("GET", uri, nil)
  146. if err != nil {
  147. return RateLimit{}, errors.Wrap(err, errMakeRequestError)
  148. }
  149. var r rateLimitResponse
  150. err = json.Unmarshal(res, &r)
  151. if err != nil {
  152. return RateLimit{}, errors.Wrap(err, errUnmarshalError)
  153. }
  154. return r.Result, nil
  155. }
  156. // UpdateRateLimit lets you replace a Rate Limit for a zone.
  157. //
  158. // API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-update-rate-limit
  159. func (api *API) UpdateRateLimit(zoneID, limitID string, limit RateLimit) (RateLimit, error) {
  160. uri := "/zones/" + zoneID + "/rate_limits/" + limitID
  161. res, err := api.makeRequest("PUT", uri, limit)
  162. if err != nil {
  163. return RateLimit{}, errors.Wrap(err, errMakeRequestError)
  164. }
  165. var r rateLimitResponse
  166. if err := json.Unmarshal(res, &r); err != nil {
  167. return RateLimit{}, errors.Wrap(err, errUnmarshalError)
  168. }
  169. return r.Result, nil
  170. }
  171. // DeleteRateLimit deletes a Rate Limit for a zone.
  172. //
  173. // API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-delete-rate-limit
  174. func (api *API) DeleteRateLimit(zoneID, limitID string) error {
  175. uri := "/zones/" + zoneID + "/rate_limits/" + limitID
  176. res, err := api.makeRequest("DELETE", uri, nil)
  177. if err != nil {
  178. return errors.Wrap(err, errMakeRequestError)
  179. }
  180. var r rateLimitResponse
  181. err = json.Unmarshal(res, &r)
  182. if err != nil {
  183. return errors.Wrap(err, errUnmarshalError)
  184. }
  185. return nil
  186. }