packages feed

http-env-gen-0.0.0.0: test/Network/HTTP/Env/RateLimitSpec.hs

{-# LANGUAGE OverloadedStrings #-}

module Network.HTTP.Env.RateLimitSpec (spec) where

import qualified Data.Set as Set
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Network.HTTP.Client
  ( HttpException (..),
    HttpExceptionContent (..),
    defaultRequest,
  )
import Network.HTTP.Client.Internal (Response (..), ResponseClose (..))
import Network.HTTP.Env.LogPolicy (LogPolicy (..), defaultHeadersToLog, defaultLogPolicy, scrubHttpException)
import Network.HTTP.Env.RateLimit
import Network.HTTP.Types (http11, mkStatus)
import Test.Syd

spec :: Spec
spec = do
  describe "renderRateLimitHeaders" $
    it "is read back by parseRateLimitHeaders" $
      map (parseRateLimitHeaders . renderRateLimitHeaders) [minBound .. maxBound]
        `shouldBe` map Just [minBound .. maxBound]

  describe "parseRateLimitHeaders" $
    it "reads nothing it does not render" $
      parseRateLimitHeaders "github" `shouldBe` Nothing

  describe "conventions other than RateLimitHeadersXRateLimit" $ do
    let corroboratedForbidden = [("X-RateLimit-Remaining", "0"), ("Retry-After", "120")]
    it "do not read a 403 as a spent quota, however corroborated" $
      map (\convention -> isRateLimited convention 403 corroboratedForbidden) [RateLimitHeadersRateLimitReset, RateLimitHeadersStructured]
        `shouldBe` [False, False]
    it "do not read X-RateLimit-Limit" $
      map (\convention -> rateLimitLimit convention [("X-RateLimit-Limit", "5000")]) [RateLimitHeadersRateLimitReset, RateLimitHeadersStructured]
        `shouldBe` [Nothing, Nothing]
    it "do not read an exception for a corroborated 403 as a spent quota" $ do
      let response =
            Response
              { responseStatus = mkStatus 403 "Forbidden",
                responseVersion = http11,
                responseHeaders = corroboratedForbidden,
                responseBody = (),
                responseCookieJar = mempty,
                responseClose' = ResponseClose (pure ()),
                responseOriginalRequest = defaultRequest,
                responseEarlyHints = []
              }
      map
        (\convention -> httpExceptionRateLimitWait convention (posixSecondsToUTCTime 0) (HttpExceptionRequest defaultRequest (StatusCodeException response "")))
        [RateLimitHeadersRateLimitReset, RateLimitHeadersStructured]
        `shouldBe` [Nothing, Nothing]

  describe "RateLimitHeadersXRateLimit" $ do
    describe "isRateLimited" $ do
      it "recognises the primary hourly limit, which GitHub answers with 403" $
        isRateLimited
          RateLimitHeadersXRateLimit
          403
          [ ("X-RateLimit-Limit", "5000"),
            ("X-RateLimit-Remaining", "0"),
            ("X-RateLimit-Reset", "1790250380")
          ]
          `shouldBe` True

      it "takes a 429 at its word" $
        isRateLimited RateLimitHeadersXRateLimit 429 []
          `shouldBe` True

      it "recognises a refusal that only says to come back later" $
        isRateLimited RateLimitHeadersXRateLimit 403 [("X-RateLimit-Remaining", "4999"), ("Retry-After", "60")]
          `shouldBe` True

      it "does not mistake a missing permission for a spent quota" $
        isRateLimited RateLimitHeadersXRateLimit 403 [("X-RateLimit-Remaining", "4999")]
          `shouldBe` False

      it "counts a Retry-After given as an HTTP date" $
        isRateLimited RateLimitHeadersXRateLimit 403 [("X-RateLimit-Remaining", "4999"), ("Retry-After", "Mon, 12 Jan 1970 13:56:40 GMT")]
          `shouldBe` True

      it "does not count a Retry-After it cannot read" $
        isRateLimited RateLimitHeadersXRateLimit 403 [("X-RateLimit-Remaining", "4999"), ("Retry-After", "soon")]
          `shouldBe` False

      it "does not read a spent quota out of a successful response" $
        isRateLimited RateLimitHeadersXRateLimit 200 [("X-RateLimit-Remaining", "0")]
          `shouldBe` False

      it "does not read a spent quota out of a not-found" $
        isRateLimited RateLimitHeadersXRateLimit 404 []
          `shouldBe` False

    describe "rateLimitWait" $ do
      let answeredAt = posixSecondsToUTCTime 1000000

      it "prefers Retry-After to the primary window's reset" $
        rateLimitWait
          RateLimitHeadersXRateLimit
          answeredAt
          [("Retry-After", "600"), ("X-RateLimit-Reset", "1002000")]
          `shouldBe` 605

      it "waits out the primary window, and a little past it" $
        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("X-RateLimit-Reset", "1001000")]
          `shouldBe` 1005

      it "falls back to the floor when the reset has already passed" $
        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("X-RateLimit-Reset", "999000")]
          `shouldBe` 60

      it "falls back to the floor when neither header is there" $
        rateLimitWait RateLimitHeadersXRateLimit answeredAt []
          `shouldBe` 60

      it "falls back to the floor when the header is not a number" $
        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("X-RateLimit-Reset", "whenever")]
          `shouldBe` 60

      it "falls back to the floor when the header has trailing rubbish" $
        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("Retry-After", "60s")]
          `shouldBe` 60

      it "does not go below the floor when asked for less" $
        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("Retry-After", "1")]
          `shouldBe` 60

      it "does not go above a whole window plus the floor" $
        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("X-RateLimit-Reset", "9999999999")]
          `shouldBe` 3660

      it "survives a reset too large to fit in an Int" $
        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("X-RateLimit-Reset", "99999999999999999999999999")]
          `shouldBe` 60

      it "survives a Retry-After too large to fit in an Int" $
        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("Retry-After", "99999999999999999999999999")]
          `shouldBe` 60

    describe "httpExceptionRateLimitWait" $ do
      let answeredAt = posixSecondsToUTCTime 1789999000

      it "answers the wait GitHub asked for" $ do
        let response =
              Response
                { responseStatus = mkStatus 403 "Forbidden",
                  responseVersion = http11,
                  responseHeaders =
                    [ ("X-RateLimit-Limit", "5000"),
                      ("X-RateLimit-Remaining", "0"),
                      ("X-RateLimit-Reset", "1790000000")
                    ],
                  responseBody = (),
                  responseCookieJar = mempty,
                  responseClose' = ResponseClose (pure ()),
                  responseOriginalRequest = defaultRequest,
                  responseEarlyHints = []
                }
        httpExceptionRateLimitWait
          RateLimitHeadersXRateLimit
          answeredAt
          (HttpExceptionRequest defaultRequest (StatusCodeException response "irrelevant"))
          `shouldBe` Just 1005

      it "answers nothing for a refusal that is not a spent quota" $ do
        let response =
              Response
                { responseStatus = mkStatus 403 "Forbidden",
                  responseVersion = http11,
                  responseHeaders = [("X-RateLimit-Remaining", "4999")],
                  responseBody = (),
                  responseCookieJar = mempty,
                  responseClose' = ResponseClose (pure ()),
                  responseOriginalRequest = defaultRequest,
                  responseEarlyHints = []
                }
        httpExceptionRateLimitWait
          RateLimitHeadersXRateLimit
          answeredAt
          (HttpExceptionRequest defaultRequest (StatusCodeException response "irrelevant"))
          `shouldBe` Nothing

      it "answers nothing for a failure that never got a response" $
        httpExceptionRateLimitWait
          RateLimitHeadersXRateLimit
          answeredAt
          (HttpExceptionRequest defaultRequest ConnectionTimeout)
          `shouldBe` Nothing

    describe "rateLimitLimit" $ do
      it "reads the allowance GitHub reports" $
        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "12500")]
          `shouldBe` Just 12500

      it "reads the 5000 an App installation is guaranteed" $
        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "5000")]
          `shouldBe` Just 5000

      it "says nothing when the header is absent" $
        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Remaining", "4999")]
          `shouldBe` Nothing

      it "refuses an allowance of zero" $
        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "0")]
          `shouldBe` Nothing

      it "takes an allowance of one, which is slow rather than stopped" $
        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "1")]
          `shouldBe` Just 1

      it "refuses a negative allowance" $
        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "-1")]
          `shouldBe` Nothing

      it "refuses a value with trailing rubbish" $
        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "5000x")]
          `shouldBe` Nothing

      it "refuses a value that is not a number at all" $
        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "unlimited")]
          `shouldBe` Nothing

      it "refuses an allowance that is not the core one" $
        rateLimitLimit
          RateLimitHeadersXRateLimit
          [ ("X-RateLimit-Limit", "30"),
            ("X-RateLimit-Resource", "search")
          ]
          `shouldBe` Nothing

      it "refuses the graphql allowance" $
        rateLimitLimit
          RateLimitHeadersXRateLimit
          [ ("X-RateLimit-Limit", "5000"),
            ("X-RateLimit-Resource", "graphql")
          ]
          `shouldBe` Nothing

      it "reads the allowance when the resource says core" $
        rateLimitLimit
          RateLimitHeadersXRateLimit
          [ ("X-RateLimit-Limit", "12500"),
            ("X-RateLimit-Resource", "core")
          ]
          `shouldBe` Just 12500

      it "takes a response with no resource header as core" $
        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "12500")]
          `shouldBe` Just 12500

  describe "RateLimitHeadersRateLimitReset" $ do
    describe "isRateLimited" $ do
      it "recognises a throttled call" $
        isRateLimited RateLimitHeadersRateLimitReset 429 [] `shouldBe` True

      it "does not mistake a permission refusal for a spent quota" $
        isRateLimited RateLimitHeadersRateLimitReset 403 [] `shouldBe` False

      it "does not read a spent quota out of a successful response" $
        isRateLimited RateLimitHeadersRateLimitReset 200 [] `shouldBe` False

      it "does not read a spent quota out of a server fault" $
        isRateLimited RateLimitHeadersRateLimitReset 503 [] `shouldBe` False

    describe "rateLimitWait" $ do
      let answeredAt = posixSecondsToUTCTime 1000000

      it "reads a Retry-After given as an HTTP date" $
        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("Retry-After", "Mon, 12 Jan 1970 13:48:40 GMT")]
          `shouldBe` 125
      it "reads a Retry-After given as an RFC 850 date" $
        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("Retry-After", "Monday, 12-Jan-70 13:48:40 GMT")]
          `shouldBe` 125
      it "reads a Retry-After given as an asctime date" $
        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("Retry-After", "Mon Jan 12 13:48:40 1970")]
          `shouldBe` 125
      it "reads an HTTP date with space around it" $
        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("Retry-After", " Mon, 12 Jan 1970 13:48:40 GMT ")]
          `shouldBe` 125

      it "prefers Retry-After to the window's reset" $
        rateLimitWait
          RateLimitHeadersRateLimitReset
          answeredAt
          [("Retry-After", "600"), ("RateLimit-Reset", "1002000")]
          `shouldBe` 605

      it "waits out the window, and a little past it" $
        rateLimitWait
          RateLimitHeadersRateLimitReset
          answeredAt
          [ ("RateLimit-Limit", "500"),
            ("RateLimit-Observed", "500"),
            ("RateLimit-Remaining", "0"),
            ("RateLimit-Reset", "1001000")
          ]
          `shouldBe` 1005

      it "does not read the X-prefixed spelling" $
        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("X-RateLimit-Reset", "1001000")]
          `shouldBe` 60

      it "falls back to the floor when the reset has already passed" $
        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("RateLimit-Reset", "999000")]
          `shouldBe` 60

      it "falls back to the floor when neither header is there" $
        rateLimitWait RateLimitHeadersRateLimitReset answeredAt []
          `shouldBe` 60

      it "falls back to the floor when the header is not a number" $
        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("RateLimit-Reset", "whenever")]
          `shouldBe` 60

      it "falls back to the floor when the header has trailing rubbish" $
        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("Retry-After", "60s")]
          `shouldBe` 60

      it "does not go below the floor when asked for less" $
        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("Retry-After", "1")]
          `shouldBe` 60

      it "does not go above a whole window plus the floor" $
        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("RateLimit-Reset", "9999999999")]
          `shouldBe` 3660

      it "survives a reset too large to fit in an Int" $
        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("RateLimit-Reset", "99999999999999999999999999")]
          `shouldBe` 60

      it "survives a Retry-After too large to fit in an Int" $
        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("Retry-After", "99999999999999999999999999")]
          `shouldBe` 60

    describe "httpExceptionRateLimitWait" $ do
      let answeredAt = posixSecondsToUTCTime 1000000

      it "reads a spent quota out of a thrown refusal" $ do
        let response =
              Response
                { responseStatus = mkStatus 429 "Too Many Requests",
                  responseVersion = http11,
                  responseHeaders = [("RateLimit-Reset", "1001000")],
                  responseBody = (),
                  responseCookieJar = mempty,
                  responseClose' = ResponseClose (pure ()),
                  responseOriginalRequest = defaultRequest,
                  responseEarlyHints = []
                }
        httpExceptionRateLimitWait
          RateLimitHeadersRateLimitReset
          answeredAt
          (HttpExceptionRequest defaultRequest (StatusCodeException response "irrelevant"))
          `shouldBe` Just 1005

      it "answers nothing for a thrown refusal that is not a spent quota" $ do
        let response =
              Response
                { responseStatus = mkStatus 403 "Forbidden",
                  responseVersion = http11,
                  responseHeaders = [],
                  responseBody = (),
                  responseCookieJar = mempty,
                  responseClose' = ResponseClose (pure ()),
                  responseOriginalRequest = defaultRequest,
                  responseEarlyHints = []
                }
        httpExceptionRateLimitWait
          RateLimitHeadersRateLimitReset
          answeredAt
          (HttpExceptionRequest defaultRequest (StatusCodeException response "irrelevant"))
          `shouldBe` Nothing

      it "answers nothing for a failure that never got a response" $
        httpExceptionRateLimitWait
          RateLimitHeadersRateLimitReset
          answeredAt
          (HttpExceptionRequest defaultRequest ConnectionTimeout)
          `shouldBe` Nothing

  describe "RateLimitHeadersStructured" $ do
    describe "isRateLimited" $ do
      it "recognises a throttled call" $
        isRateLimited RateLimitHeadersStructured 429 [] `shouldBe` True

      it "does not mistake a permission refusal for a spent quota" $
        isRateLimited RateLimitHeadersStructured 403 [] `shouldBe` False

      it "does not read a spent quota out of a successful response" $
        isRateLimited RateLimitHeadersStructured 200 [] `shouldBe` False

      it "does not read a spent quota out of a server fault" $
        isRateLimited RateLimitHeadersStructured 503 [] `shouldBe` False

    describe "structuredParameter" $ do
      it "reads the seconds until the quota refills" $
        structuredParameter "t" [("RateLimit", "\"baseline\";r=1999;t=600")]
          `shouldBe` Just 600

      it "reads what is left of the quota" $
        structuredParameter "r" [("RateLimit", "\"baseline\";r=1999;t=600")]
          `shouldBe` Just 1999

      it "reads a value padded with whitespace" $
        structuredParameter "t" [("RateLimit", "\"baseline\" ; r=1999 ; t = 600 ")]
          `shouldBe` Just 600

      it "does not read the policy name as a parameter" $
        structuredParameter "t" [("RateLimit", "t=5;r=1999")]
          `shouldBe` Nothing

      it "answers nothing for a parameter that is not there" $
        structuredParameter "t" [("RateLimit", "\"baseline\";r=1999")]
          `shouldBe` Nothing

      it "answers nothing when the header is not there" $
        structuredParameter "t" []
          `shouldBe` Nothing

      it "answers nothing for a parameter that is not a whole number" $
        structuredParameter "t" [("RateLimit", "\"baseline\";t=600s")]
          `shouldBe` Nothing

    describe "rateLimitWait" $ do
      it "prefers Retry-After to the quota header" $
        rateLimitWait RateLimitHeadersStructured (posixSecondsToUTCTime 0) [("Retry-After", "60"), ("RateLimit", "\"baseline\";r=0;t=600")]
          `shouldBe` 65

      it "waits out the window Forgejo counts down, and a little past it" $
        rateLimitWait RateLimitHeadersStructured (posixSecondsToUTCTime 0) [("RateLimit", "\"baseline\";r=0;t=600")]
          `shouldBe` 605

      it "does not read the spellings the other forges use" $
        rateLimitWait RateLimitHeadersStructured (posixSecondsToUTCTime 0) [("X-RateLimit-Reset", "600"), ("RateLimit-Reset", "600")]
          `shouldBe` 60

      it "falls back to the floor when neither header is there" $
        rateLimitWait RateLimitHeadersStructured (posixSecondsToUTCTime 0) []
          `shouldBe` 60

      it "does not go below the floor when asked for less" $
        rateLimitWait RateLimitHeadersStructured (posixSecondsToUTCTime 0) [("Retry-After", "1")]
          `shouldBe` 60

      it "does not go above a whole window plus the floor" $
        rateLimitWait RateLimitHeadersStructured (posixSecondsToUTCTime 0) [("RateLimit", "\"baseline\";t=9999999")]
          `shouldBe` 3660

      it "survives a countdown too large to fit in an Int" $
        rateLimitWait RateLimitHeadersStructured (posixSecondsToUTCTime 0) [("RateLimit", "\"baseline\";t=99999999999999999999999999")]
          `shouldBe` 60

    describe "httpExceptionRateLimitWait" $ do
      it "answers the wait Codeberg asked for" $ do
        let response =
              Response
                { responseStatus = mkStatus 429 "Too Many Requests",
                  responseVersion = http11,
                  responseHeaders =
                    [ ("RateLimit-Policy", "\"baseline\";q=2000;w=600"),
                      ("RateLimit", "\"baseline\";r=0;t=600")
                    ],
                  responseBody = (),
                  responseCookieJar = mempty,
                  responseClose' = ResponseClose (pure ()),
                  responseOriginalRequest = defaultRequest,
                  responseEarlyHints = []
                }
        httpExceptionRateLimitWait
          RateLimitHeadersStructured
          (posixSecondsToUTCTime 0)
          (HttpExceptionRequest defaultRequest (StatusCodeException response "irrelevant"))
          `shouldBe` Just 605

      it "answers nothing for a refusal that is not a spent quota" $ do
        let response =
              Response
                { responseStatus = mkStatus 403 "Forbidden",
                  responseVersion = http11,
                  responseHeaders = [("RateLimit", "\"baseline\";r=1999;t=600")],
                  responseBody = (),
                  responseCookieJar = mempty,
                  responseClose' = ResponseClose (pure ()),
                  responseOriginalRequest = defaultRequest,
                  responseEarlyHints = []
                }
        httpExceptionRateLimitWait
          RateLimitHeadersStructured
          (posixSecondsToUTCTime 0)
          (HttpExceptionRequest defaultRequest (StatusCodeException response "irrelevant"))
          `shouldBe` Nothing

      it "answers nothing for a failure that never got a response" $
        httpExceptionRateLimitWait
          RateLimitHeadersStructured
          (posixSecondsToUTCTime 0)
          (HttpExceptionRequest defaultRequest ConnectionTimeout)
          `shouldBe` Nothing

      it "still reads the wait after a policy that logs the header has scrubbed the exception" $ do
        let response =
              Response
                { responseStatus = mkStatus 429 "Too Many Requests",
                  responseVersion = http11,
                  responseHeaders =
                    [ ("RateLimit", "\"baseline\";r=0;t=600"),
                      ("Set-Cookie", "session=wnxczrmtabdywlrw")
                    ],
                  responseBody = (),
                  responseCookieJar = mempty,
                  responseClose' = ResponseClose (pure ()),
                  responseOriginalRequest = defaultRequest,
                  responseEarlyHints = []
                }
        httpExceptionRateLimitWait
          RateLimitHeadersStructured
          (posixSecondsToUTCTime 0)
          ( scrubHttpException defaultLogPolicy {logPolicyHeadersToLog = Set.insert "RateLimit" defaultHeadersToLog} $
              HttpExceptionRequest defaultRequest (StatusCodeException response "irrelevant")
          )
          `shouldBe` Just 605