wai-rate-limit (empty) → 0.1.0.0
raw patch · 6 files changed
+313/−0 lines, 6 filesdep +basedep +http-typesdep +wai
Dependencies added: base, http-types, wai
Files
- LICENSE +21/−0
- README.md +92/−0
- src/Network/Wai/RateLimit.hs +39/−0
- src/Network/Wai/RateLimit/Backend.hs +27/−0
- src/Network/Wai/RateLimit/Strategy.hs +90/−0
- wai-rate-limit.cabal +44/−0
+ LICENSE view
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2020 Michael B. Gale++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
+ README.md view
@@ -0,0 +1,92 @@+# Rate limiting as WAI middleware+++++This repository contains WAI middleware for rate limiting. The main library is `wai-rate-limit` which provides the WAI middleware as well as implementations of different rate limiting strategies. ++To limit dependencies introduced by `wai-rate-limit`, storage backends are split up into their own packages:++- A Redis backend is provided by `wai-rate-limit-redis`. ++## Usage++### Sliding Window++The following example demonstrates how to use the middleware with a sliding window strategy and a Redis backend. The resulting middleware will limit requests to 50 requests per sliding window of 29 seconds based on keys derived from the client's IP address. In other words, if we receive a request, we check whether the limit of 50 has been exceed for the client based on their IP and if not, the request is allowed, the request count is increased, and the window is extended by 29 seconds. If the limit is exceeded, the client will always have to wait 29 seconds before making another request.++```haskell+import qualified Data.ByteString.Char8 as C8++import Database.Redis as Redis++import Network.Wai.RateLimit+import Network.Wai.RateLimit.Strategy+import Network.Wai.RateLimit.Redis++middleware :: Redis.Connection -> Middleware+middleware conn = rateLimiting strategy + where backend = redisBackend conn + getKey = pure . C8.pack . show . remoteHost+ strategy = slidingWindow backend 29 50 getKey+```++The behaviour described above can be changed by altering the parameters to `slidingWindow` accordingly. In particular, for e.g. REST APIs, you may wish to use e.g. API keys or other user identifiers in place of IP addresses.++### Fixed Window++The following example demonstrates how to use the middleware with a fixed window strategy and a Redis backend. The resulting middleware will limit requests to 50 requests per window of 29 seconds based on keys derived from the client's IP address. ++```haskell+import qualified Data.ByteString.Char8 as C8++import Database.Redis as Redis++import Network.Wai.RateLimit+import Network.Wai.RateLimit.Strategy+import Network.Wai.RateLimit.Redis++middleware :: Redis.Connection -> Middleware+middleware conn = rateLimiting strategy + where backend = redisBackend conn + getKey = pure . C8.pack . show . remoteHost+ strategy = fixedWindow backend 29 50 getKey+```++The behaviour described above can be changed by altering the parameters to `fixedWindow` accordingly. In particular, for e.g. REST APIs, you may wish to use e.g. API keys or other user identifiers in place of IP addresses.++### Custom strategies++In addition to the provided strategies, you can implement your own `Strategy` values or customise existing ones. The `Strategy` type is currently defines as follows, so a custom strategy is essentially a function `Request -> IO Bool` which should return `True` if the request should proceed or `False` if it should be rejected:++```haskell+-- | Represents rate limiting strategies.+data Strategy = MkStrategy {+ -- | 'strategyOnRequest' @request@ is a computation which determines+ -- whether the request should be allowed or not, based on the rate+ -- limiting strategy.+ strategyOnRequest :: Request -> IO Bool+}+```++Modifying existing strategies makes it relatively easy to e.g. selectively apply rate limiting to some paths:++```haskell+import qualified Data.ByteString.Char8 as C8++import Database.Redis as Redis++import Network.Wai.RateLimit+import Network.Wai.RateLimit.Strategy+import Network.Wai.RateLimit.Redis++middleware :: Redis.Connection -> Middleware+middleware conn = rateLimiting strategy{ strategyOnRequest = customHandler } + where backend = redisBackend conn + getKey = pure . C8.pack . show . remoteHost+ strategy = fixedWindow backend 29 50 getKey+ customHandler req = + if rawPathInfo req == "/index.html" + then pure True -- always allow access to /index.html+ else strategyOnRequest strategy req+```
+ src/Network/Wai/RateLimit.hs view
@@ -0,0 +1,39 @@+--------------------------------------------------------------------------------+-- Rate Limiting Middleware for WAI --+--------------------------------------------------------------------------------+-- This source code is licensed under the MIT license found in the LICENSE --+-- file in the root directory of this source tree. --+--------------------------------------------------------------------------------++{-# LANGUAGE AllowAmbiguousTypes #-}++-- | Implements WAI 'Middleware' for rate limiting. +module Network.Wai.RateLimit (+ rateLimiting+) where ++--------------------------------------------------------------------------------++import Control.Monad++import Network.HTTP.Types+import Network.Wai+import Network.Wai.RateLimit.Strategy+import Network.Wai.RateLimit.Backend++--------------------------------------------------------------------------------++-- | 'rateLimiting' @strategy@ is a WAI 'Middleware' which limits requests+-- according to the configuration represented by @strategy@.+rateLimiting :: Strategy -> Middleware+rateLimiting MkStrategy{..} app req sendResponse = do+ -- check that the client has not exceeded + allowRequest <- strategyOnRequest req++ if allowRequest+ -- if not: process the request normally+ then app req sendResponse+ -- otherwise: return a 429 response with an appropriate message+ else sendResponse $ responseLBS status429 [] "Rate limit exceeded" ++--------------------------------------------------------------------------------
+ src/Network/Wai/RateLimit/Backend.hs view
@@ -0,0 +1,27 @@+--------------------------------------------------------------------------------+-- Rate Limiting Middleware for WAI --+--------------------------------------------------------------------------------+-- This source code is licensed under the MIT license found in the LICENSE --+-- file in the root directory of this source tree. --+--------------------------------------------------------------------------------++module Network.Wai.RateLimit.Backend (+ Backend(..)+) where++--------------------------------------------------------------------------------++-- | Represents storage backends for the rate limiting middleware.+data Backend key err = MkBackend {+ -- | 'backendGetUsage' @key@ is a computation which gets the usage + -- associated with @key@.+ backendGetUsage :: key -> IO (Either err Integer),+ -- | 'backendIncAndGetUsage' @key usage@ is a computation which increments + -- the usage associated with @key@ by @usage@ and returns the result.+ backendIncAndGetUsage :: key -> Integer -> IO (Either err Integer),+ -- | 'backendExpireIn' @key seconds@ is a computation which makes @key@+ -- expire in @seconds@ from now.+ backendExpireIn :: key -> Integer -> IO (Either err ())+}++--------------------------------------------------------------------------------
+ src/Network/Wai/RateLimit/Strategy.hs view
@@ -0,0 +1,90 @@+--------------------------------------------------------------------------------+-- Rate Limiting Middleware for WAI --+--------------------------------------------------------------------------------+-- This source code is licensed under the MIT license found in the LICENSE --+-- file in the root directory of this source tree. --+--------------------------------------------------------------------------------++module Network.Wai.RateLimit.Strategy (+ Strategy(..),+ fixedWindow,+ slidingWindow+) where++--------------------------------------------------------------------------------++import Control.Monad++import Network.Wai+import Network.Wai.RateLimit.Backend++--------------------------------------------------------------------------------++-- | Represents rate limiting strategies.+data Strategy = MkStrategy {+ -- | 'strategyOnRequest' @request@ is a computation which determines+ -- whether the request should be allowed or not, based on the rate+ -- limiting strategy.+ strategyOnRequest :: Request -> IO Bool+}+++-- | 'windowStrategy'+windowStrategy :: Backend key err + -> Integer + -> Integer + -> (Request -> IO key) + -> (Integer -> Bool)+ -> Request+ -> IO Bool+windowStrategy MkBackend{..} seconds capacity getKey cond req = do+ -- get a key to identify the usage bucket for the request: this is+ -- up the application and may be comprised of e.g. the IP of the client+ -- or a unique user id, followed by e.g. a timestamp+ key <- getKey req ++ -- get usage for the key and increment it by 1+ result <- backendIncAndGetUsage key 1++ case result of + -- a backend error occurred, deny the request+ Left err -> pure False + -- we got back the current usage: check whether it is within the+ -- acceptable limit and, if so, add to the expiry timer+ Right used + | used <= capacity -> do+ when (cond used) $ void $ backendExpireIn key seconds+ pure True + | otherwise -> pure False++-- | 'fixedWindow' @seconds limit@ is a 'Strategy' which limits the number+-- of requests made by a client to @limit@ within a window of @seconds@. +fixedWindow :: Backend key err + -> Integer + -> Integer + -> (Request -> IO key) + -> Strategy+fixedWindow backend seconds capacity getKey = MkStrategy{+ strategyOnRequest = + let cond = (==) 1+ in windowStrategy backend seconds capacity getKey cond+}++-- | 'slidingWindow' @seconds limit@ is a 'Strategy' which limits the number+-- of requests made by a client to @limit@ within a sliding window of +-- @seconds@. That is, for every successful request, the window is extended by+-- @seconds@ so that a "break" of @seconds@ is required after @limit@-many +-- requests have been made in a period during which the timeout has never+-- been exceeded.+slidingWindow :: Backend key err + -> Integer + -> Integer + -> (Request -> IO key) + -> Strategy+slidingWindow backend seconds capacity getKey = MkStrategy{+ strategyOnRequest = + let cond = const True+ in windowStrategy backend seconds capacity getKey cond+}++--------------------------------------------------------------------------------
+ wai-rate-limit.cabal view
@@ -0,0 +1,44 @@+cabal-version: 1.12++-- This file has been generated from package.yaml by hpack version 0.33.0.+--+-- see: https://github.com/sol/hpack+--+-- hash: cc5d5ebcfe3ffeb74b04de46a5e0c91cebb17900f85fbd1939ca33fc1593a9b3++name: wai-rate-limit+version: 0.1.0.0+synopsis: Rate limiting as WAI middleware+description: A Haskell library which implements rate limiting as WAI middleware+category: Security+homepage: https://github.com/mbg/wai-rate-limit#readme+bug-reports: https://github.com/mbg/wai-rate-limit/issues+author: Michael B. Gale+maintainer: m.gale@warwick.ac.uk+copyright: Copyright (c) Michael B. Gale+license: MIT+license-file: LICENSE+build-type: Simple+extra-source-files:+ README.md++source-repository head+ type: git+ location: https://github.com/mbg/wai-rate-limit++library+ exposed-modules:+ Network.Wai.RateLimit+ Network.Wai.RateLimit.Backend+ Network.Wai.RateLimit.Strategy+ other-modules:+ Paths_wai_rate_limit+ hs-source-dirs:+ src+ default-extensions: OverloadedStrings RecordWildCards+ ghc-options: -W+ build-depends:+ base >=4.8 && <5+ , http-types <1+ , wai >=3.0 && <4+ default-language: Haskell2010