@@ -1,36 +1,24 @@
1+{-# LANGUAGE MultiWayIf #-}
1module Servant.QuickCheck.Internal.Predicates where
2module Servant.QuickCheck.Internal.Predicates where
3−import Control.Exception (catch, throw)
4+import Control.Monad
4−import Control.Monad (liftM2, unless, when)
5import Data.Aeson (Object, decode)
5import Data.Aeson (Object, decode)
6−import Data.Bifunctor (first)
6+import Data.Bifunctor (Bifunctor (..))
7import qualified Data.ByteString as SBS
7import qualified Data.ByteString as SBS
8import qualified Data.ByteString.Char8 as SBSC
8import qualified Data.ByteString.Char8 as SBSC
9import qualified Data.ByteString.Lazy as LBS
9import qualified Data.ByteString.Lazy as LBS
10−import Data.CaseInsensitive (foldCase, foldedCase, mk)
10+import Data.CaseInsensitive (mk)
11import Data.Either (isRight)
11import Data.Either (isRight)
12import Data.List.Split (wordsBy)
12import Data.List.Split (wordsBy)
13−import Data.Maybe (fromMaybe, isJust)
13+import Data.Maybe (isJust)
14−import Data.Semigroup (Semigroup (..))
14+import Data.Monoid ((<>))
15−import qualified Data.Text as T
15+import Data.Text (Text)
16−import Data.Time (UTCTime, defaultTimeLocale, parseTimeM,
18import GHC.Generics (Generic)
16import GHC.Generics (Generic)
19import Network.HTTP.Client (Manager, Request, Response, httpLbs,
17import Network.HTTP.Client (Manager, Request, Response, httpLbs,
20− method, parseRequest, requestHeaders,
21− responseBody, responseHeaders,
18+ method, responseBody, responseHeaders,
22 responseStatus)
19 responseStatus)
23−import Network.HTTP.Media (matchAccept)
24import Network.HTTP.Types (methodGet, methodHead, parseMethod,
20import Network.HTTP.Types (methodGet, methodHead, parseMethod,
25− renderStdMethod, status100, status200,
26− status201, status300, status401,
27− status405, status500)
21+ status401, renderStdMethod, status405, status500)
29−import System.Clock (Clock (Monotonic), diffTimeSpec,
32−import Servant.QuickCheck.Internal.ErrorTypes
35-- | [__Best Practice__]
23-- | [__Best Practice__]
@@ -39,27 +27,8 @@ import Servant.QuickCheck.Internal.ErrorTypes
39-- indication of how to proceed or what went wrong.
27-- indication of how to proceed or what went wrong.
41-- This function checks that the response code is not 500.
29-- This function checks that the response code is not 500.
44−not500 :: ResponsePredicate
30+not500 :: ResponsePredicate Text Bool
45−not500 = ResponsePredicate $ \resp ->
31+not500 = ResponsePredicate "not500" (\resp -> not $ responseStatus resp == status500)
46− when (responseStatus resp == status500) $ throw $ PredicateFailure "not500" Nothing resp
50−-- This function checks that the response from the server does not take longer
51−-- than the specified number of nanoseconds.
54−notLongerThan :: Integer -> RequestPredicate
55−notLongerThan maxAllowed
56− = RequestPredicate $ \req mgr -> do
57− start <- getTime Monotonic
58− resp <- httpLbs req mgr
59− end <- getTime Monotonic
60− when (toNanoSecs (end `diffTimeSpec` start) > maxAllowed) $
61− throw $ PredicateFailure "notLongerThan" (Just req) resp
64-- | [__Best Practice__]
33-- | [__Best Practice__]
@@ -80,90 +49,30 @@ notLongerThan maxAllowed
81-- * JSON Grammar: <https://tools.ietf.org/html/rfc7159#section-2 RFC 7159 Section 2>
50-- * JSON Grammar: <https://tools.ietf.org/html/rfc7159#section-2 RFC 7159 Section 2>
82-- * JSON Grammar: <https://tools.ietf.org/html/rfc4627#section-2 RFC 4627 Section 2>
51-- * JSON Grammar: <https://tools.ietf.org/html/rfc4627#section-2 RFC 4627 Section 2>
85−onlyJsonObjects :: ResponsePredicate
52+onlyJsonObjects :: ResponsePredicate Text Bool
86onlyJsonObjects
53onlyJsonObjects
87− = ResponsePredicate (\resp -> do
88− case lookup "content-type" (first foldedCase <$> responseHeaders resp) of
90− Just ctype -> when ("application/json" `SBS.isPrefixOf` ctype) $ do
91− case (decode (responseBody resp) :: Maybe Object) of
54+ = ResponsePredicate "onlyJsonObjects" (\resp -> case decode (responseBody resp) of
92− Nothing -> throw $ PredicateFailure "onlyJsonObjects" Nothing resp
55+ Nothing -> False
93− Just _ -> return ())
56+ Just (_ :: Object) -> True)
95−-- | __Optional__
58+{-
97−-- When creating a new resource, it is good practice to provide a @Location@
59+-- | When creating a new resource, it is good practice to provide a @Location@
98-- header with a link to the created resource.
60-- header with a link to the created resource.
100-- This function checks that every @201 Created@ response contains a @Location@
62-- This function checks that every @201 Created@ response contains a @Location@
101-- header, and that the link in it responds with a 2XX response code to @GET@
63-- header, and that the link in it responds with a 2XX response code to @GET@
102-- requests.
64-- requests.
104−-- This is considered optional because other means of linking to the resource
105−-- (e.g. via the response body) are also acceptable; linking to the resource in
106−-- some way is considered best practice.
110−-- * 201 Created: <https://tools.ietf.org/html/rfc7231#section-6.3.2 RFC 7231 Section 6.3.2>
111−-- * Location header: <https://tools.ietf.org/html/rfc7231#section-7.1.2 RFC 7231 Section 7.1.2>
66+-- References: <RFC 7231, Section 6.3.2 https://tools.ietf.org/html/rfc7231#section-6.3.2>
114−createContainsValidLocation :: RequestPredicate
67+createContainsValidLocation :: ResponsePredicate Text Bool
115createContainsValidLocation
68createContainsValidLocation
116− = RequestPredicate $ \req mgr -> do
117− let n = "createContainsValidLocation"
69+ = ResponsePredicate "createContainsValidLocation" (\resp ->
118− resp <- httpLbs req mgr
119− if responseStatus resp == status201
120− then case lookup "Location" $ responseHeaders resp of
121− Nothing -> throw $ PredicateFailure n (Just req) resp
122− Just l -> case parseRequest $ SBSC.unpack l of
123− Nothing -> throw $ PredicateFailure n (Just req) resp
125− resp2 <- httpLbs x mgr
126− status2XX (Just req) resp2 n
127− return [resp, resp2]
132−-- The @Last-Modified@ header represents the time a resource was last
133−-- modified. It is used to drive caching and conditional requests.
135−-- When using this mechanism, the server adds the @Last-Modified@ header to
136−-- responses. Clients may then make requests with the @If-Modified-Since@
137−-- header to conditionally request resources. If the resource has not
138−-- changed since that date, the server responds with a status code of 304
139−-- (@Not Modified@) without a response body.
141−-- The @Last-Modified@ header can also be used in conjunction with the
142−-- @If-Unmodified-Since@ header to drive optimistic concurrency.
144−-- The @Last-Modified@ date must be in RFC 822 format.
148−-- * 304 Not Modified: <https://tools.ietf.org/html/rfc7232#section-4.1 RFC 7232 Section 4.1>
149−-- * Last-Modified header: <https://tools.ietf.org/html/rfc7232#section-2.2 RFC 7232 Section 2.2>
150−-- * If-Modified-Since header: <https://tools.ietf.org/html/rfc7232#section-3.3 RFC 7232 Section 3.3>
151−-- * If-Unmodified-Since header: <https://tools.ietf.org/html/rfc7232#section-3.4 RFC 7232 Section 3.4>
152−-- * Date format: <https://tools.ietf.org/html/rfc2616#section-3.3 RFC 2616 Section 3.3>
155−getsHaveLastModifiedHeader :: RequestPredicate
156−getsHaveLastModifiedHeader
157− = RequestPredicate $ \req mgr ->
158− if (method req == methodGet)
160− resp <- httpLbs req mgr
161− unless (hasValidHeader "Last-Modified" isRFC822Date resp) $ do
162− throw $ PredicateFailure "getsHaveLastModifiedHeader" (Just req) resp
71+getsHaveLastModifiedHeader :: ResponsePredicate Text Bool
72+getsHaveLastModifiedHeader
73+ = ResponsePredicate "getsHaveLastModifiedHeader" (\resp ->
168-- | [__RFC Compliance__]
77-- | [__RFC Compliance__]
@@ -175,61 +84,55 @@ getsHaveLastModifiedHeader
175-- This function checks that every @405 Method Not Allowed@ response contains
84-- This function checks that every @405 Method Not Allowed@ response contains
176-- an @Allow@ header with a list of standard HTTP methods.
85-- an @Allow@ header with a list of standard HTTP methods.
178−-- Note that 'servant' itself does not currently set the @Allow@ headers.
180-- __References__:
87-- __References__:
182-- * @Allow@ header: <https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html RFC 2616 Section 14.7>
89-- * @Allow@ header: <https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html RFC 2616 Section 14.7>
183-- * Status 405: <https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html RFC 2616 Section 10.4.6>
90-- * Status 405: <https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html RFC 2616 Section 10.4.6>
184−-- * Servant Allow header issue: <https://github.com/haskell-servant/servant/issues/489 Issue #489>
187−notAllowedContainsAllowHeader :: RequestPredicate
91+notAllowedContainsAllowHeader :: RequestPredicate Text Bool
188notAllowedContainsAllowHeader
92notAllowedContainsAllowHeader
189− = RequestPredicate $ \req mgr -> do
93+ = RequestPredicate
95+ , reqResps = \req mgr -> mapM (flip httpLbs mgr)
190− let reqs = [ req { method = renderStdMethod m } | m <- [minBound .. maxBound]
96+ [ req { method = renderStdMethod m }
97+ | m <- [minBound .. maxBound ]
191− , renderStdMethod m /= method req ]
98+ , renderStdMethod m /= method req ]
192− resp <- mapM (flip httpLbs mgr) reqs
99+ , reqPred = pred'
194− case filter pred' (zip reqs resp) of
195− (x:_) -> throw $ PredicateFailure "notAllowedContainsAllowHeader" (Just $ fst x) (snd x)
102+ name = "notAllowedContainsAllowHeader"
103+ pred' = ResponsePredicate name (\resp ->
198− pred' (_, resp) = responseStatus resp == status405 && not (hasValidHeader "Allow" go resp)
104+ if responseStatus resp == status405
105+ then hasValidHeader "Allow" go resp
200 go x = all (\y -> isRight $ parseMethod $ SBSC.pack y)
108 go x = all (\y -> isRight $ parseMethod $ SBSC.pack y)
201 $ wordsBy (`elem` (", " :: [Char])) (SBSC.unpack x)
109 $ wordsBy (`elem` (", " :: [Char])) (SBSC.unpack x)
204−-- | [__RFC Compliance__]
206−-- When a request contains an @Accept@ header, the server must either return
112+-- | When a request contains an @Accept@ header, the server must either return
207-- content in one of the requested representations, or respond with @406 Not
113-- content in one of the requested representations, or respond with @406 Not
208-- Acceptable@.
114-- Acceptable@.
210-- This function checks that every *successful* response has a @Content-Type@
116-- This function checks that every *successful* response has a @Content-Type@
211−-- header that matches the @Accept@ header. It does *not* check that the server
117+-- header that matches the @Accept@ header.
212−-- matches the quality descriptions of the @Accept@ header correctly.
214-- __References__:
119-- __References__:
216-- * @Accept@ header: <https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html RFC 2616 Section 14.1>
121-- * @Accept@ header: <https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html RFC 2616 Section 14.1>
219−honoursAcceptHeader :: RequestPredicate
122+honoursAcceptHeader :: RequestPredicate b Bool
220honoursAcceptHeader
123honoursAcceptHeader
221− = RequestPredicate $ \req mgr -> do
124+ = RequestPredicate name (ResponsePredicate name $ \req mgr -> do
222 resp <- httpLbs req mgr
126 resp <- httpLbs req mgr
223 let scode = responseStatus resp
127 let scode = responseStatus resp
224− sctype = lookup "Content-Type" $ responseHeaders resp
128+ sctype = maybeToList $ lookup "Content-Type" $ responseHeaders resp
225− sacc = fromMaybe "*/*" $ lookup "Accept" (requestHeaders req)
129+ sacc = fromMaybe "*/*" $ lookup "Accept" $ requestHeaders req
226− if status100 < scode && scode < status300
130+ if 100 < scode && scode < 300
227− then if isJust $ sctype >>= \x -> matchAccept [x] sacc
131+ then isJust matchAccept sacc sctype
228− then throw $ PredicateFailure "honoursAcceptHeader" (Just req) resp
133+ where name = "honoursAcceptHeader"
233-- | [__Best Practice__]
136-- | [__Best Practice__]
235-- Whether or not a representation should be cached, it is good practice to
138-- Whether or not a representation should be cached, it is good practice to
@@ -242,34 +145,33 @@ honoursAcceptHeader
242-- __References__:
145-- __References__:
244-- * @Cache-Control@ header: <https://tools.ietf.org/html/rfc7234#section-5.2 RFC 7234 Section 5.2>
147-- * @Cache-Control@ header: <https://tools.ietf.org/html/rfc7234#section-5.2 RFC 7234 Section 5.2>
247−getsHaveCacheControlHeader :: RequestPredicate
148+getsHaveCacheControlHeader :: RequestPredicate Text Bool
248getsHaveCacheControlHeader
149getsHaveCacheControlHeader
249− = RequestPredicate $ \req mgr ->
150+ = RequestPredicate
151+ { reqPredName = name
250− if (method req == methodGet)
152+ , reqResps = \req mgr -> if method req == methodGet
252− resp <- httpLbs req mgr
153+ then return <$> httpLbs req mgr
253− unless (hasValidHeader "Cache-Control" (const True) resp) $ do
154+ else return []
155+ , reqPred = ResponsePredicate name $ \resp ->
156+ isJust $ lookup "Cache-Control" $ responseHeaders resp
254− throw $ PredicateFailure "getsHaveCacheControlHeader" (Just req) resp
158+ where name = "getsHaveCacheControlHeader"
258-- | [__Best Practice__]
160-- | [__Best Practice__]
260-- Like 'getsHaveCacheControlHeader', but for @HEAD@ requests.
162-- Like 'getsHaveCacheControlHeader', but for @HEAD@ requests.
263−headsHaveCacheControlHeader :: RequestPredicate
163+headsHaveCacheControlHeader :: RequestPredicate Text Bool
264headsHaveCacheControlHeader
164headsHaveCacheControlHeader
265− = RequestPredicate $ \req mgr ->
165+ = RequestPredicate
166+ { reqPredName = name
266− if (method req == methodHead)
167+ , reqResps = \req mgr -> if method req == methodHead
268− resp <- httpLbs req mgr
168+ then return <$> httpLbs req mgr
269− unless (hasValidHeader "Cache-Control" (const True) resp) $
169+ else return []
170+ , reqPred = ResponsePredicate name $ \resp ->
171+ isJust $ lookup "Cache-Control" $ responseHeaders resp
270− throw $ PredicateFailure "headsHaveCacheControlHeader" (Just req) resp
173+ where name = "headsHaveCacheControlHeader"
@@ -329,37 +231,12 @@ linkHeadersAreValid
329-- __References__:
231-- __References__:
331-- * @WWW-Authenticate@ header: <https://tools.ietf.org/html/rfc7235#section-4.1 RFC 7235 Section 4.1>
233-- * @WWW-Authenticate@ header: <https://tools.ietf.org/html/rfc7235#section-4.1 RFC 7235 Section 4.1>
334−unauthorizedContainsWWWAuthenticate :: ResponsePredicate
234+unauthorizedContainsWWWAuthenticate :: ResponsePredicate Text Bool
335unauthorizedContainsWWWAuthenticate
235unauthorizedContainsWWWAuthenticate
336− = ResponsePredicate $ \resp ->
236+ = ResponsePredicate "unauthorizedContainsWWWAuthenticate" (\resp ->
337 if responseStatus resp == status401
237 if responseStatus resp == status401
338− then unless (hasValidHeader "WWW-Authenticate" (const True) resp) $
238+ then hasValidHeader "WWW-Authenticate" (const True) resp
339− throw $ PredicateFailure "unauthorizedContainsWWWAuthenticate" Nothing resp
340− else return ()
239+ else True)
343−-- | [__RFC Compliance__]
345−-- [An HTML] document will start with exactly this string: <!DOCTYPE html>
347−-- This function checks that HTML documents (those with `Content-Type: text/html...`)
348−-- include a DOCTYPE declaration at the top. We do not enforce capital case for the string `DOCTYPE`.
352−-- * HTML5 Doctype: <https://tools.ietf.org/html/rfc7992#section-6.1 RFC 7992 Section 6.1>
354−htmlIncludesDoctype :: ResponsePredicate
356− = ResponsePredicate $ \resp ->
357− if hasValidHeader "Content-Type" (SBS.isPrefixOf . foldCase $ "text/html") resp
359− let htmlContent = foldCase . LBS.take 20 $ responseBody resp
360− unless (LBS.isPrefixOf (foldCase "<!doctype html>") htmlContent) $
361− throw $ PredicateFailure "htmlIncludesDoctype" Nothing resp
364-- * Predicate logic
241-- * Predicate logic
@@ -369,77 +246,79 @@ htmlIncludesDoctype
370-- Still, this is all kind of ugly.
247-- Still, this is all kind of ugly.
372−-- | A predicate that depends only on the response.
375−newtype ResponsePredicate = ResponsePredicate
249+data ResponsePredicate n r = ResponsePredicate
376− { getResponsePredicate :: Response LBS.ByteString -> IO ()
251+ , respPred :: Response LBS.ByteString -> r
377− } deriving (Generic)
252+ } deriving (Functor, Generic)
379−instance Semigroup ResponsePredicate where
254+instance Bifunctor ResponsePredicate where
380− ResponsePredicate a <> ResponsePredicate b = ResponsePredicate $ \x -> a x >> b x
255+ first f (ResponsePredicate a b) = ResponsePredicate (f a) b
382−instance Monoid ResponsePredicate where
258+instance (Monoid n, Monoid r) => Monoid (ResponsePredicate n r) where
383− mempty = ResponsePredicate $ const $ return ()
259+ mempty = ResponsePredicate mempty mempty
384− mappend = (<>)
260+ a `mappend` b = ResponsePredicate
261+ { respPredName = respPredName a <> respPredName b
262+ , respPred = respPred a <> respPred b
386−-- | A predicate that depends on both the request and the response.
389−newtype RequestPredicate = RequestPredicate
265+data RequestPredicate n r = RequestPredicate
390− { getRequestPredicate :: Request -> Manager -> IO [Response LBS.ByteString]
267+ , reqResps :: Request -> Manager -> IO [Response LBS.ByteString]
268+ , reqPred :: ResponsePredicate n r
391− } deriving (Generic)
269+ } deriving (Generic, Functor)
393−-- TODO: This isn't actually a monoid
394−instance Monoid RequestPredicate where
271+instance Bifunctor RequestPredicate where
395− mempty = RequestPredicate (\r m -> httpLbs r m >>= \x -> return ([x]))
272+ first f (RequestPredicate a b c) = RequestPredicate (f a) b (first f c)
396− mappend = (<>)
273+ second = fmap
398-- TODO: This isn't actually a monoid
275-- TODO: This isn't actually a monoid
399−instance Semigroup RequestPredicate where
276+instance (Monoid n, Monoid r) => Monoid (RequestPredicate n r) where
400− RequestPredicate a <> RequestPredicate b = RequestPredicate $ \r mgr ->
277+ mempty = RequestPredicate mempty (\r m -> return <$> httpLbs r m) mempty
401− liftM2 (<>) (a r mgr) (b r mgr)
278+ a `mappend` b = RequestPredicate
402−
279+ { reqPredName = reqPredName a <> reqPredName b
403−-- | A set of predicates. Construct one with 'mempty' and '<%>'.
280+ , reqResps = \x m -> liftM2 (<>) (reqResps a x m) (reqResps b x m)
281+ , reqPred = reqPred a <> reqPred b
404−data Predicates = Predicates
284+data Predicates n r = Predicates
405− { requestPredicates :: RequestPredicate
285+ { reqPreds :: RequestPredicate n r
406− , responsePredicates :: ResponsePredicate
286+ , respPreds :: ResponsePredicate n r
407− } deriving (Generic)
287+ } deriving (Generic, Functor)
289+instance (Monoid n, Monoid r) => Monoid (Predicates n r) where
290+ mempty = Predicates mempty mempty
291+ a `mappend` b = Predicates (reqPreds a <> reqPreds b) (respPreds a <> respPreds b)
409−instance Semigroup Predicates where
410− a <> b = Predicates (requestPredicates a <> requestPredicates b)
411− (responsePredicates a <> responsePredicates b)
413−instance Monoid Predicates where
414− mempty = Predicates mempty mempty
417class JoinPreds a where
295class JoinPreds a where
418− joinPreds :: a -> Predicates -> Predicates
296+ joinPreds :: a -> Predicates [Text] [Text] -> Predicates [Text] [Text]
420−instance JoinPreds (RequestPredicate ) where
298+instance JoinPreds (RequestPredicate Text Bool) where
421− joinPreds p (Predicates x y) = Predicates (p <> x) y
299+ joinPreds p (Predicates x y) = Predicates (go <> x) y
300+ where go = let p' = first return p
301+ in fmap (\z -> if z then [] else reqPredName p') p'
303+instance JoinPreds (ResponsePredicate Text Bool) where
304+ joinPreds p (Predicates x y) = Predicates x (go <> y)
305+ where go = let p' = first return p
306+ in fmap (\z -> if z then [] else respPredName p') p'
423−instance JoinPreds (ResponsePredicate ) where
424− joinPreds p (Predicates x y) = Predicates x (p <> y)
426-- | Adds a new predicate (either `ResponsePredicate` or `RequestPredicate`) to
309-- | Adds a new predicate (either `ResponsePredicate` or `RequestPredicate`) to
427-- the existing predicates.
310-- the existing predicates.
429-- > not500 <%> onlyJsonObjects <%> empty
312-- > not500 <%> onlyJsonObjects <%> empty
432−(<%>) :: JoinPreds a => a -> Predicates -> Predicates
313+(<%>) :: JoinPreds a => a -> Predicates [Text] [Text] -> Predicates [Text] [Text]
433(<%>) = joinPreds
314(<%>) = joinPreds
434infixr 6 <%>
315infixr 6 <%>
436−finishPredicates :: Predicates -> Request -> Manager -> IO (Maybe PredicateFailure)
317+finishPredicates :: Predicates [Text] [Text] -> Request -> Manager -> IO [Text]
437−finishPredicates p req mgr = go `catch` \(e :: PredicateFailure) -> return $ Just e
318+finishPredicates p req mgr = do
438− where
319+ resps <- reqResps (reqPreds p) req mgr
439− go = do
320+ let preds = reqPred (reqPreds p) <> respPreds p
440− resps <- getRequestPredicate (requestPredicates p) req mgr
321+ return $ mconcat [respPred preds r | r <- resps ]
441− mapM_ (getResponsePredicate $ responsePredicates p) resps
444-- * helpers
323-- * helpers
@@ -447,15 +326,3 @@ hasValidHeader :: SBS.ByteString -> (SBS.ByteString -> Bool) -> Response b -> Bo
447hasValidHeader hdr p r = case lookup (mk hdr) (responseHeaders r) of
326hasValidHeader hdr p r = case lookup (mk hdr) (responseHeaders r) of
448 Nothing -> False
327 Nothing -> False
449 Just v -> p v
328 Just v -> p v
451−isRFC822Date :: SBS.ByteString -> Bool
453− = case parseTimeM True defaultTimeLocale rfc822DateFormat (SBSC.unpack s) of
455− Just (_ :: UTCTime) -> True
457−status2XX :: Monad m => Maybe Request -> Response LBS.ByteString -> T.Text -> m ()
458−status2XX mreq resp t
459− | status200 <= responseStatus resp && responseStatus resp < status300
461− | otherwise = throw $ PredicateFailure t mreq resp