@@ -1,36 +1,28 @@
1module Servant.QuickCheck.Internal.Predicates where
1module Servant.QuickCheck.Internal.Predicates where
3−import Control.Exception (catch, throw)
3+import Control.Monad (liftM2)
4−import Control.Monad (liftM2, unless, when)
5import Data.Aeson (Object, decode)
4import Data.Aeson (Object, decode)
6−import Data.Bifunctor (first)
5+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)
13import Data.Maybe (fromMaybe, isJust)
13import Data.Maybe (fromMaybe, 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,
18+ method, parseUrl, requestHeaders,
21 responseBody, responseHeaders,
19 responseBody, responseHeaders,
22 responseStatus)
20 responseStatus)
23import Network.HTTP.Media (matchAccept)
21import Network.HTTP.Media (matchAccept)
24import Network.HTTP.Types (methodGet, methodHead, parseMethod,
22import Network.HTTP.Types (methodGet, methodHead, parseMethod,
25− renderStdMethod, status100, status200,
23+ renderStdMethod, status200, status201,
26− status201, status300, status401,
24+ status300, status401, status405,
27− status405, status500)
25+ status500, status100)
29−import System.Clock (Clock (Monotonic), diffTimeSpec,
32−import Servant.QuickCheck.Internal.ErrorTypes
35-- | [__Best Practice__]
27-- | [__Best Practice__]
@@ -39,27 +31,8 @@ import Servant.QuickCheck.Internal.ErrorTypes
39-- indication of how to proceed or what went wrong.
31-- indication of how to proceed or what went wrong.
41-- This function checks that the response code is not 500.
33-- This function checks that the response code is not 500.
44−not500 :: ResponsePredicate
34+not500 :: ResponsePredicate Text Bool
45−not500 = ResponsePredicate $ \resp ->
35+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__]
37-- | [__Best Practice__]
@@ -80,17 +53,11 @@ notLongerThan maxAllowed
81-- * JSON Grammar: <https://tools.ietf.org/html/rfc7159#section-2 RFC 7159 Section 2>
54-- * 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>
55-- * JSON Grammar: <https://tools.ietf.org/html/rfc4627#section-2 RFC 4627 Section 2>
85−onlyJsonObjects :: ResponsePredicate
56+onlyJsonObjects :: ResponsePredicate Text Bool
86onlyJsonObjects
57onlyJsonObjects
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
58+ = ResponsePredicate "onlyJsonObjects" (\resp -> case decode (responseBody resp) of
92− Nothing -> throw $ PredicateFailure "onlyJsonObjects" Nothing resp
59+ Nothing -> False
93− Just _ -> return ())
60+ Just (_ :: Object) -> True)
95-- | __Optional__
62-- | __Optional__
@@ -109,61 +76,29 @@ onlyJsonObjects
110-- * 201 Created: <https://tools.ietf.org/html/rfc7231#section-6.3.2 RFC 7231 Section 6.3.2>
77-- * 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>
78-- * Location header: <https://tools.ietf.org/html/rfc7231#section-7.1.2 RFC 7231 Section 7.1.2>
114−createContainsValidLocation :: RequestPredicate
79+createContainsValidLocation :: RequestPredicate Text Bool
115createContainsValidLocation
80createContainsValidLocation
116− = RequestPredicate $ \req mgr -> do
81+ = RequestPredicate
117− let n = "createContainsValidLocation"
82+ { reqPredName = "createContainsValidLocation"
118− resp <- httpLbs req mgr
83+ , reqResps = \req mgr -> do
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
84 resp <- httpLbs req mgr
161− unless (hasValidHeader "Last-Modified" isRFC822Date resp) $ do
85+ if responseStatus resp == status201
162− throw $ PredicateFailure "getsHaveLastModifiedHeader" (Just req) resp
86+ then case lookup "Location" $ responseHeaders resp of
163− return [resp]
87+ Nothing -> return (False, [resp])
88+ Just l -> case parseUrl $ SBSC.unpack l of
89+ Nothing -> return (False, [resp])
91+ resp2 <- httpLbs x mgr
92+ return (status2XX resp2, [resp, resp2])
164− else return []
93+ else return (True, [resp])
97+getsHaveLastModifiedHeader :: ResponsePredicate Text Bool
98+getsHaveLastModifiedHeader
99+ = ResponsePredicate "getsHaveLastModifiedHeader" (\resp ->
168-- | [__RFC Compliance__]
103-- | [__RFC Compliance__]
@@ -175,27 +110,22 @@ getsHaveLastModifiedHeader
175-- This function checks that every @405 Method Not Allowed@ response contains
110-- This function checks that every @405 Method Not Allowed@ response contains
176-- an @Allow@ header with a list of standard HTTP methods.
111-- an @Allow@ header with a list of standard HTTP methods.
178−-- Note that 'servant' itself does not currently set the @Allow@ headers.
180-- __References__:
113-- __References__:
182-- * @Allow@ header: <https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html RFC 2616 Section 14.7>
115-- * @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>
116-- * 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
117+notAllowedContainsAllowHeader :: RequestPredicate Text Bool
188notAllowedContainsAllowHeader
118notAllowedContainsAllowHeader
189− = RequestPredicate $ \req mgr -> do
119+ = RequestPredicate
120+ { reqPredName = "notAllowedContainsAllowHeader"
121+ , reqResps = \req mgr -> do
190− let reqs = [ req { method = renderStdMethod m } | m <- [minBound .. maxBound]
122+ resp <- mapM (flip httpLbs mgr) $ [ req { method = renderStdMethod m }
123+ | m <- [minBound .. maxBound ]
191− , renderStdMethod m /= method req ]
124+ , renderStdMethod m /= method req ]
192− resp <- mapM (flip httpLbs mgr) reqs
125+ return (all pred' resp, resp)
194− case filter pred' (zip reqs resp) of
195− (x:_) -> throw $ PredicateFailure "notAllowedContainsAllowHeader" (Just $ fst x) (snd x)
198− pred' (_, resp) = responseStatus resp == status405 && not (hasValidHeader "Allow" go resp)
128+ pred' resp = responseStatus resp /= status405 || hasValidHeader "Allow" go resp
200 go x = all (\y -> isRight $ parseMethod $ SBSC.pack y)
130 go x = all (\y -> isRight $ parseMethod $ SBSC.pack y)
201 $ wordsBy (`elem` (", " :: [Char])) (SBSC.unpack x)
131 $ wordsBy (`elem` (", " :: [Char])) (SBSC.unpack x)
@@ -214,21 +144,19 @@ notAllowedContainsAllowHeader
214-- __References__:
144-- __References__:
216-- * @Accept@ header: <https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html RFC 2616 Section 14.1>
146-- * @Accept@ header: <https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html RFC 2616 Section 14.1>
219−honoursAcceptHeader :: RequestPredicate
147+honoursAcceptHeader :: RequestPredicate Text Bool
220honoursAcceptHeader
148honoursAcceptHeader
221− = RequestPredicate $ \req mgr -> do
149+ = RequestPredicate
150+ { reqPredName = "honoursAcceptHeader"
151+ , reqResps = \req mgr -> do
222− resp <- httpLbs req mgr
152+ resp <- httpLbs req mgr
223− let scode = responseStatus resp
153+ let scode = responseStatus resp
224− sctype = lookup "Content-Type" $ responseHeaders resp
154+ sctype = lookup "Content-Type" $ responseHeaders resp
225− sacc = fromMaybe "*/*" $ lookup "Accept" (requestHeaders req)
155+ sacc = fromMaybe "*/*" $ lookup "Accept" (requestHeaders req)
226− if status100 < scode && scode < status300
156+ if status100 < scode && scode < status300
227− then if isJust $ sctype >>= \x -> matchAccept [x] sacc
157+ then return (isJust $ sctype >>= \x -> matchAccept [x] sacc, [resp])
228− then throw $ PredicateFailure "honoursAcceptHeader" (Just req) resp
229− else return [resp]
158+ else return (True, [resp])
230− else return [resp]
159+ }
233-- | [__Best Practice__]
161-- | [__Best Practice__]
@@ -243,33 +171,35 @@ honoursAcceptHeader
244-- * @Cache-Control@ header: <https://tools.ietf.org/html/rfc7234#section-5.2 RFC 7234 Section 5.2>
172-- * @Cache-Control@ header: <https://tools.ietf.org/html/rfc7234#section-5.2 RFC 7234 Section 5.2>
246−-- /Since 0.0.0.0/
174+-- #SINCE#
247−getsHaveCacheControlHeader :: RequestPredicate
175+getsHaveCacheControlHeader :: RequestPredicate Text Bool
248getsHaveCacheControlHeader
176getsHaveCacheControlHeader
249− = RequestPredicate $ \req mgr ->
177+ = RequestPredicate
178+ { reqPredName = "getsHaveCacheControlHeader"
250− if (method req == methodGet)
179+ , reqResps = \req mgr -> if method req == methodGet
252− resp <- httpLbs req mgr
181+ resp <- httpLbs req mgr
253− unless (hasValidHeader "Cache-Control" (const True) resp) $ do
182+ let good = isJust $ lookup "Cache-Control" $ responseHeaders resp
254− throw $ PredicateFailure "getsHaveCacheControlHeader" (Just req) resp
183+ return (good, [resp])
256− else return []
184+ else return (True, [])
258-- | [__Best Practice__]
187-- | [__Best Practice__]
260-- Like 'getsHaveCacheControlHeader', but for @HEAD@ requests.
189-- Like 'getsHaveCacheControlHeader', but for @HEAD@ requests.
262−-- /Since 0.0.0.0/
191+-- #SINCE#
263−headsHaveCacheControlHeader :: RequestPredicate
192+headsHaveCacheControlHeader :: RequestPredicate Text Bool
264headsHaveCacheControlHeader
193headsHaveCacheControlHeader
265− = RequestPredicate $ \req mgr ->
194+ = RequestPredicate
195+ { reqPredName = "headsHaveCacheControlHeader"
266− if (method req == methodHead)
196+ , reqResps = \req mgr -> if method req == methodHead
268− resp <- httpLbs req mgr
198+ resp <- httpLbs req mgr
269− unless (hasValidHeader "Cache-Control" (const True) resp) $
199+ let good = hasValidHeader "Cache-Control" (const True) resp
270− throw $ PredicateFailure "headsHaveCacheControlHeader" (Just req) resp
200+ return (good, [resp])
272− else return []
201+ else return (True, [])
@@ -330,36 +260,13 @@ linkHeadersAreValid
331-- * @WWW-Authenticate@ header: <https://tools.ietf.org/html/rfc7235#section-4.1 RFC 7235 Section 4.1>
261-- * @WWW-Authenticate@ header: <https://tools.ietf.org/html/rfc7235#section-4.1 RFC 7235 Section 4.1>
333−-- /Since 0.0.0.0/
263+-- #SINCE#
334−unauthorizedContainsWWWAuthenticate :: ResponsePredicate
264+unauthorizedContainsWWWAuthenticate :: ResponsePredicate Text Bool
335unauthorizedContainsWWWAuthenticate
265unauthorizedContainsWWWAuthenticate
336− = ResponsePredicate $ \resp ->
266+ = ResponsePredicate "unauthorizedContainsWWWAuthenticate" (\resp ->
337 if responseStatus resp == status401
267 if responseStatus resp == status401
338− then unless (hasValidHeader "WWW-Authenticate" (const True) resp) $
268+ then hasValidHeader "WWW-Authenticate" (const True) resp
339− throw $ PredicateFailure "unauthorizedContainsWWWAuthenticate" Nothing resp
340− else return ()
269+ 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
271-- * Predicate logic
@@ -369,77 +276,78 @@ htmlIncludesDoctype
370-- Still, this is all kind of ugly.
277-- Still, this is all kind of ugly.
372−-- | A predicate that depends only on the response.
375−newtype ResponsePredicate = ResponsePredicate
279+data ResponsePredicate n r = ResponsePredicate
376− { getResponsePredicate :: Response LBS.ByteString -> IO ()
281+ , respPred :: Response LBS.ByteString -> r
377− } deriving (Generic)
282+ } deriving (Functor, Generic)
379−instance Semigroup ResponsePredicate where
284+instance Bifunctor ResponsePredicate where
380− ResponsePredicate a <> ResponsePredicate b = ResponsePredicate $ \x -> a x >> b x
285+ first f (ResponsePredicate a b) = ResponsePredicate (f a) b
382−instance Monoid ResponsePredicate where
288+instance (Monoid n, Monoid r) => Monoid (ResponsePredicate n r) where
383− mempty = ResponsePredicate $ const $ return ()
289+ mempty = ResponsePredicate mempty mempty
384− mappend = (<>)
290+ a `mappend` b = ResponsePredicate
291+ { respPredName = respPredName a <> respPredName b
292+ , respPred = respPred a <> respPred b
386−-- | A predicate that depends on both the request and the response.
389−newtype RequestPredicate = RequestPredicate
295+data RequestPredicate n r = RequestPredicate
390− { getRequestPredicate :: Request -> Manager -> IO [Response LBS.ByteString]
297+ , reqResps :: Request -> Manager -> IO (r, [Response LBS.ByteString])
391− } deriving (Generic)
298+ } deriving (Generic, Functor)
393−-- TODO: This isn't actually a monoid
394−instance Monoid RequestPredicate where
300+instance Bifunctor RequestPredicate where
395− mempty = RequestPredicate (\r m -> httpLbs r m >>= \x -> return ([x]))
301+ first f (RequestPredicate a b) = RequestPredicate (f a) b
396− mappend = (<>)
302+ second = fmap
398-- TODO: This isn't actually a monoid
304-- TODO: This isn't actually a monoid
399−instance Semigroup RequestPredicate where
305+instance (Monoid n, Monoid r) => Monoid (RequestPredicate n r) where
306+ mempty = RequestPredicate mempty (\r m -> httpLbs r m >>= \x -> return (mempty, [x]))
400− RequestPredicate a <> RequestPredicate b = RequestPredicate $ \r mgr ->
307+ a `mappend` b = RequestPredicate
401− liftM2 (<>) (a r mgr) (b r mgr)
308+ { reqPredName = reqPredName a <> reqPredName b
309+ , reqResps = \x m -> liftM2 (<>) (reqResps a x m) (reqResps b x m)
312+data Predicates n r = Predicates
313+ { reqPreds :: RequestPredicate n r
314+ , respPreds :: ResponsePredicate n r
315+ } deriving (Generic, Functor)
317+instance (Monoid n, Monoid r) => Monoid (Predicates n r) where
318+ mempty = Predicates mempty mempty
319+ a `mappend` b = Predicates (reqPreds a <> reqPreds b) (respPreds a <> respPreds b)
403−-- | A set of predicates. Construct one with 'mempty' and '<%>'.
404−data Predicates = Predicates
405− { requestPredicates :: RequestPredicate
406− , responsePredicates :: ResponsePredicate
407− } deriving (Generic)
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
323class JoinPreds a where
418− joinPreds :: a -> Predicates -> Predicates
324+ joinPreds :: a -> Predicates [Text] [Text] -> Predicates [Text] [Text]
326+instance JoinPreds (RequestPredicate Text Bool) where
327+ joinPreds p (Predicates x y) = Predicates (go <> x) y
328+ where go = let p' = first return p
329+ in fmap (\z -> if z then [] else reqPredName p') p'
420−instance JoinPreds (RequestPredicate ) where
331+instance JoinPreds (ResponsePredicate Text Bool) where
421− joinPreds p (Predicates x y) = Predicates (p <> x) y
332+ joinPreds p (Predicates x y) = Predicates x (go <> y)
333+ where go = let p' = first return p
334+ 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
337-- | Adds a new predicate (either `ResponsePredicate` or `RequestPredicate`) to
427-- the existing predicates.
338-- the existing predicates.
429-- > not500 <%> onlyJsonObjects <%> empty
340-- > not500 <%> onlyJsonObjects <%> empty
431−-- /Since 0.0.0.0/
342+-- #SINCE#
432−(<%>) :: JoinPreds a => a -> Predicates -> Predicates
343+(<%>) :: JoinPreds a => a -> Predicates [Text] [Text] -> Predicates [Text] [Text]
433(<%>) = joinPreds
344(<%>) = joinPreds
434infixr 6 <%>
345infixr 6 <%>
436−finishPredicates :: Predicates -> Request -> Manager -> IO (Maybe PredicateFailure)
347+finishPredicates :: Predicates [Text] [Text] -> Request -> Manager -> IO [Text]
437−finishPredicates p req mgr = go `catch` \(e :: PredicateFailure) -> return $ Just e
348+finishPredicates p req mgr = do
438− where
349+ (soFar, resps) <- reqResps (reqPreds p) req mgr
439− go = do
350+ return $ soFar <> mconcat [respPred (respPreds p) r | r <- resps]
440− resps <- getRequestPredicate (requestPredicates p) req mgr
441− mapM_ (getResponsePredicate $ responsePredicates p) resps
444-- * helpers
352-- * helpers
@@ -448,14 +356,5 @@ hasValidHeader hdr p r = case lookup (mk hdr) (responseHeaders r) of
448 Nothing -> False
356 Nothing -> False
449 Just v -> p v
357 Just v -> p v
451−isRFC822Date :: SBS.ByteString -> Bool
359+status2XX :: Response b -> 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
360+status2XX r = status200 <= responseStatus r && responseStatus r < status300
461− | otherwise = throw $ PredicateFailure t mreq resp