@@ -1,24 +1,36 @@
1−{-# LANGUAGE MultiWayIf #-}
21module Servant.QuickCheck.Internal.Predicates where
32
4−import Control.Monad
3+import Control.Exception (catch, throw)
4+import Control.Monad (liftM2, unless, when)
55import Data.Aeson (Object, decode)
6−import Data.Bifunctor (Bifunctor (..))
6+import Data.Bifunctor (first)
77import qualified Data.ByteString as SBS
88import qualified Data.ByteString.Char8 as SBSC
99import qualified Data.ByteString.Lazy as LBS
10−import Data.CaseInsensitive (mk)
10+import Data.CaseInsensitive (foldCase, foldedCase, mk)
1111import Data.Either (isRight)
1212import Data.List.Split (wordsBy)
13−import Data.Maybe (isJust)
14−import Data.Monoid ((<>))
15−import Data.Text (Text)
13+import Data.Maybe (fromMaybe, isJust)
14+import Data.Semigroup (Semigroup (..))
15+import qualified Data.Text as T
16+import Data.Time (UTCTime, defaultTimeLocale, parseTimeM,
17+ rfc822DateFormat)
1618import GHC.Generics (Generic)
1719import Network.HTTP.Client (Manager, Request, Response, httpLbs,
18− method, responseBody, responseHeaders,
20+ method, parseRequest, requestHeaders,
21+ responseBody, responseHeaders,
1922 responseStatus)
23+import Network.HTTP.Media (matchAccept)
2024import Network.HTTP.Types (methodGet, methodHead, parseMethod,
21− status401, renderStdMethod, status405, status500)
25+ renderStdMethod, status100, status200,
26+ status201, status300, status401,
27+ status405, status500)
28+import Prelude.Compat
29+import System.Clock (Clock (Monotonic), diffTimeSpec,
30+ getTime, toNanoSecs)
31+
32+import Servant.QuickCheck.Internal.ErrorTypes
33+
2234
2335-- | [__Best Practice__]
2436--
@@ -27,8 +39,27 @@ import Network.HTTP.Types (methodGet, methodHead, parseMethod,
2739-- indication of how to proceed or what went wrong.
2840--
2941-- This function checks that the response code is not 500.
30−not500 :: ResponsePredicate Text Bool
31−not500 = ResponsePredicate "not500" (\resp -> not $ responseStatus resp == status500)
42+--
43+-- /Since 0.0.0.0/
44+not500 :: ResponsePredicate
45+not500 = ResponsePredicate $ \resp ->
46+ when (responseStatus resp == status500) $ throw $ PredicateFailure "not500" Nothing resp
47+
48+-- | [__Optional__]
49+--
50+-- This function checks that the response from the server does not take longer
51+-- than the specified number of nanoseconds.
52+--
53+-- /Since 0.0.2.1/
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
62+ return []
3263
3364-- | [__Best Practice__]
3465--
@@ -49,11 +80,17 @@ not500 = ResponsePredicate "not500" (\resp -> not $ responseStatus resp == statu
4980--
5081-- * JSON Grammar: <https://tools.ietf.org/html/rfc7159#section-2 RFC 7159 Section 2>
5182-- * JSON Grammar: <https://tools.ietf.org/html/rfc4627#section-2 RFC 4627 Section 2>
52−onlyJsonObjects :: ResponsePredicate Text Bool
83+--
84+-- /Since 0.0.0.0/
85+onlyJsonObjects :: ResponsePredicate
5386onlyJsonObjects
54− = ResponsePredicate "onlyJsonObjects" (\resp -> case decode (responseBody resp) of
55− Nothing -> False
56− Just (_ :: Object) -> True)
87+ = ResponsePredicate (\resp -> do
88+ case lookup "content-type" (first foldedCase <$> responseHeaders resp) of
89+ Nothing -> return ()
90+ Just ctype -> when ("application/json" `SBS.isPrefixOf` ctype) $ do
91+ case (decode (responseBody resp) :: Maybe Object) of
92+ Nothing -> throw $ PredicateFailure "onlyJsonObjects" Nothing resp
93+ Just _ -> return ())
5794
5895-- | __Optional__
5996--
@@ -72,23 +109,61 @@ onlyJsonObjects
72109--
73110-- * 201 Created: <https://tools.ietf.org/html/rfc7231#section-6.3.2 RFC 7231 Section 6.3.2>
74111-- * Location header: <https://tools.ietf.org/html/rfc7231#section-7.1.2 RFC 7231 Section 7.1.2>
75−{-createContainsValidLocation :: RequestPredicate Text Bool-}
76−{-createContainsValidLocation-}
77− {-= RequestPredicate-}
78− {-{ reqPredName = "createContainsValidLocation"-}
79− {-, reqResps = \req mg -> do-}
80− {-resp <- httpLbs mgr req-}
81− {-if responseStatus resp == status201-}
82− {-then case lookup "Location" $ responseHeaders resp of-}
83− {-Nothing -> return []-}
84− {-Just l -> if-}
85−
86−{-
87−getsHaveLastModifiedHeader :: ResponsePredicate Text Bool
112+--
113+-- /Since 0.0.0.0/
114+createContainsValidLocation :: RequestPredicate
115+createContainsValidLocation
116+ = RequestPredicate $ \req mgr -> do
117+ let n = "createContainsValidLocation"
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
124+ Just x -> do
125+ resp2 <- httpLbs x mgr
126+ status2XX (Just req) resp2 n
127+ return [resp, resp2]
128+ else return [resp]
129+
130+-- | [__Optional__]
131+--
132+-- The @Last-Modified@ header represents the time a resource was last
133+-- modified. It is used to drive caching and conditional requests.
134+--
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.
140+--
141+-- The @Last-Modified@ header can also be used in conjunction with the
142+-- @If-Unmodified-Since@ header to drive optimistic concurrency.
143+--
144+-- The @Last-Modified@ date must be in RFC 822 format.
145+--
146+-- __References__:
147+--
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>
153+--
154+-- /Since 0.0.2.1/
155+getsHaveLastModifiedHeader :: RequestPredicate
88156getsHaveLastModifiedHeader
89− = ResponsePredicate "getsHaveLastModifiedHeader" (\resp ->
157+ = RequestPredicate $ \req mgr ->
158+ if (method req == methodGet)
159+ then do
160+ resp <- httpLbs req mgr
161+ unless (hasValidHeader "Last-Modified" isRFC822Date resp) $ do
162+ throw $ PredicateFailure "getsHaveLastModifiedHeader" (Just req) resp
163+ return [resp]
164+ else return []
165+
90166
91−-}
92167
93168-- | [__RFC Compliance__]
94169--
@@ -100,51 +175,61 @@ getsHaveLastModifiedHeader
100175-- This function checks that every @405 Method Not Allowed@ response contains
101176-- an @Allow@ header with a list of standard HTTP methods.
102177--
178+-- Note that 'servant' itself does not currently set the @Allow@ headers.
179+--
103180-- __References__:
104181--
105182-- * @Allow@ header: <https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html RFC 2616 Section 14.7>
106183-- * Status 405: <https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html RFC 2616 Section 10.4.6>
107−notAllowedContainsAllowHeader :: RequestPredicate Text Bool
184+-- * Servant Allow header issue: <https://github.com/haskell-servant/servant/issues/489 Issue #489>
185+--
186+-- /Since 0.0.0.0/
187+notAllowedContainsAllowHeader :: RequestPredicate
108188notAllowedContainsAllowHeader
109− = RequestPredicate
110− { reqPredName = "notAllowedContainsAllowHeader"
111− , reqResps = \req mgr -> do
112− resp <- mapM (flip httpLbs mgr) $ [ req { method = renderStdMethod m }
113− | m <- [minBound .. maxBound ]
114− , renderStdMethod m /= method req ]
115− return (all pred' resp, resp)
116− }
189+ = RequestPredicate $ \req mgr -> do
190+ let reqs = [ req { method = renderStdMethod m } | m <- [minBound .. maxBound]
191+ , renderStdMethod m /= method req ]
192+ resp <- mapM (flip httpLbs mgr) reqs
193+
194+ case filter pred' (zip reqs resp) of
195+ (x:_) -> throw $ PredicateFailure "notAllowedContainsAllowHeader" (Just $ fst x) (snd x)
196+ [] -> return resp
117197 where
118− pred' resp = responseStatus resp /= status405 || hasValidHeader "Allow" go resp
198+ pred' (_, resp) = responseStatus resp == status405 && not (hasValidHeader "Allow" go resp)
119199 where
120200 go x = all (\y -> isRight $ parseMethod $ SBSC.pack y)
121201 $ wordsBy (`elem` (", " :: [Char])) (SBSC.unpack x)
122202
123− {-
124−-- | When a request contains an @Accept@ header, the server must either return
203+
204+-- | [__RFC Compliance__]
205+--
206+-- When a request contains an @Accept@ header, the server must either return
125207-- content in one of the requested representations, or respond with @406 Not
126208-- Acceptable@.
127209--
128210-- This function checks that every *successful* response has a @Content-Type@
129−-- header that matches the @Accept@ header.
211+-- header that matches the @Accept@ header. It does *not* check that the server
212+-- matches the quality descriptions of the @Accept@ header correctly.
130213--
131214-- __References__:
132215--
133216-- * @Accept@ header: <https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html RFC 2616 Section 14.1>
134−honoursAcceptHeader :: RequestPredicate b Bool
217+--
218+-- /Since 0.0.0.0/
219+honoursAcceptHeader :: RequestPredicate
135220honoursAcceptHeader
136− = RequestPredicate name (ResponsePredicate name $ \req mgr -> do
137−
221+ = RequestPredicate $ \req mgr -> do
138222 resp <- httpLbs req mgr
139223 let scode = responseStatus resp
140− sctype = maybeToList $ lookup "Content-Type" $ responseHeaders resp
141− sacc = fromMaybe "*/*" $ lookup "Accept" $ requestHeaders req
142− if 100 < scode && scode < 300
143− then isJust matchAccept sacc sctype
144− else True)
145− where name = "honoursAcceptHeader"
224+ sctype = lookup "Content-Type" $ responseHeaders resp
225+ sacc = fromMaybe "*/*" $ lookup "Accept" (requestHeaders req)
226+ if status100 < scode && scode < status300
227+ then if isJust $ sctype >>= \x -> matchAccept [x] sacc
228+ then throw $ PredicateFailure "honoursAcceptHeader" (Just req) resp
229+ else return [resp]
230+ else return [resp]
231+
146232
147−-}
148233-- | [__Best Practice__]
149234--
150235-- Whether or not a representation should be cached, it is good practice to
@@ -157,32 +242,34 @@ honoursAcceptHeader
157242-- __References__:
158243--
159244-- * @Cache-Control@ header: <https://tools.ietf.org/html/rfc7234#section-5.2 RFC 7234 Section 5.2>
160−getsHaveCacheControlHeader :: RequestPredicate Text Bool
245+--
246+-- /Since 0.0.0.0/
247+getsHaveCacheControlHeader :: RequestPredicate
161248getsHaveCacheControlHeader
162− = RequestPredicate
163− { reqPredName = "getsHaveCacheControlHeader"
164− , reqResps = \req mgr -> if method req == methodGet
165− then do
166− resp <- httpLbs req mgr
167− let good = isJust $ lookup "Cache-Control" $ responseHeaders resp
168− return (good, [resp])
169− else return (True, [])
170− }
249+ = RequestPredicate $ \req mgr ->
250+ if (method req == methodGet)
251+ then do
252+ resp <- httpLbs req mgr
253+ unless (hasValidHeader "Cache-Control" (const True) resp) $ do
254+ throw $ PredicateFailure "getsHaveCacheControlHeader" (Just req) resp
255+ return [resp]
256+ else return []
171257
172258-- | [__Best Practice__]
173259--
174260-- Like 'getsHaveCacheControlHeader', but for @HEAD@ requests.
175−headsHaveCacheControlHeader :: RequestPredicate Text Bool
261+--
262+-- /Since 0.0.0.0/
263+headsHaveCacheControlHeader :: RequestPredicate
176264headsHaveCacheControlHeader
177− = RequestPredicate
178− { reqPredName = "headsHaveCacheControlHeader"
179− , reqResps = \req mgr -> if method req == methodHead
180− then do
181− resp <- httpLbs req mgr
182− let good = isJust $ lookup "Cache-Control" $ responseHeaders resp
183− return (good, [resp])
184− else return (True, [])
185− }
265+ = RequestPredicate $ \req mgr ->
266+ if (method req == methodHead)
267+ then do
268+ resp <- httpLbs req mgr
269+ unless (hasValidHeader "Cache-Control" (const True) resp) $
270+ throw $ PredicateFailure "headsHaveCacheControlHeader" (Just req) resp
271+ return [resp]
272+ else return []
186273{-
187274-- |
188275--
@@ -242,12 +329,37 @@ linkHeadersAreValid
242329-- __References__:
243330--
244331-- * @WWW-Authenticate@ header: <https://tools.ietf.org/html/rfc7235#section-4.1 RFC 7235 Section 4.1>
245−unauthorizedContainsWWWAuthenticate :: ResponsePredicate Text Bool
332+--
333+-- /Since 0.0.0.0/
334+unauthorizedContainsWWWAuthenticate :: ResponsePredicate
246335unauthorizedContainsWWWAuthenticate
247− = ResponsePredicate "unauthorizedContainsWWWAuthenticate" (\resp ->
336+ = ResponsePredicate $ \resp ->
248337 if responseStatus resp == status401
249− then hasValidHeader "WWW-Authenticate" (const True) resp
250− else True)
338+ then unless (hasValidHeader "WWW-Authenticate" (const True) resp) $
339+ throw $ PredicateFailure "unauthorizedContainsWWWAuthenticate" Nothing resp
340+ else return ()
341+
342+
343+-- | [__RFC Compliance__]
344+--
345+-- [An HTML] document will start with exactly this string: <!DOCTYPE html>
346+--
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`.
349+--
350+-- __References__:
351+--
352+-- * HTML5 Doctype: <https://tools.ietf.org/html/rfc7992#section-6.1 RFC 7992 Section 6.1>
353+-- /Since 0.3.0.0/
354+htmlIncludesDoctype :: ResponsePredicate
355+htmlIncludesDoctype
356+ = ResponsePredicate $ \resp ->
357+ if hasValidHeader "Content-Type" (SBS.isPrefixOf . foldCase $ "text/html") resp
358+ then do
359+ let htmlContent = foldCase . LBS.take 20 $ responseBody resp
360+ unless (LBS.isPrefixOf (foldCase "<!doctype html>") htmlContent) $
361+ throw $ PredicateFailure "htmlIncludesDoctype" Nothing resp
362+ else return ()
251363
252364-- * Predicate logic
253365
@@ -257,76 +369,77 @@ unauthorizedContainsWWWAuthenticate
257369--
258370-- Still, this is all kind of ugly.
259371
260−data ResponsePredicate n r = ResponsePredicate
261− { respPredName :: n
262− , respPred :: Response LBS.ByteString -> r
263− } deriving (Functor, Generic)
372+-- | A predicate that depends only on the response.
373+--
374+-- /Since 0.0.0.0/
375+newtype ResponsePredicate = ResponsePredicate
376+ { getResponsePredicate :: Response LBS.ByteString -> IO ()
377+ } deriving (Generic)
264378
265−instance Bifunctor ResponsePredicate where
266− first f (ResponsePredicate a b) = ResponsePredicate (f a) b
267− second = fmap
379+instance Semigroup ResponsePredicate where
380+ ResponsePredicate a <> ResponsePredicate b = ResponsePredicate $ \x -> a x >> b x
268381
269−instance (Monoid n, Monoid r) => Monoid (ResponsePredicate n r) where
270− mempty = ResponsePredicate mempty mempty
271− a `mappend` b = ResponsePredicate
272− { respPredName = respPredName a <> respPredName b
273− , respPred = respPred a <> respPred b
274− }
382+instance Monoid ResponsePredicate where
383+ mempty = ResponsePredicate $ const $ return ()
384+ mappend = (<>)
275385
276−data RequestPredicate n r = RequestPredicate
277− { reqPredName :: n
278− , reqResps :: Request -> Manager -> IO (r, [Response LBS.ByteString])
279− } deriving (Generic, Functor)
386+-- | A predicate that depends on both the request and the response.
387+--
388+-- /Since 0.0.0.0/
389+newtype RequestPredicate = RequestPredicate
390+ { getRequestPredicate :: Request -> Manager -> IO [Response LBS.ByteString]
391+ } deriving (Generic)
280392
281−instance Bifunctor RequestPredicate where
282− first f (RequestPredicate a b) = RequestPredicate (f a) b
283− second = fmap
393+-- TODO: This isn't actually a monoid
394+instance Monoid RequestPredicate where
395+ mempty = RequestPredicate (\r m -> httpLbs r m >>= \x -> return ([x]))
396+ mappend = (<>)
284397
285398-- TODO: This isn't actually a monoid
286−instance (Monoid n, Monoid r) => Monoid (RequestPredicate n r) where
287− mempty = RequestPredicate mempty (\r m -> httpLbs r m >>= \x -> return (mempty, [x]))
288− a `mappend` b = RequestPredicate
289− { reqPredName = reqPredName a <> reqPredName b
290− , reqResps = \x m -> liftM2 (<>) (reqResps a x m) (reqResps b x m)
291− }
292−
293−data Predicates n r = Predicates
294− { reqPreds :: RequestPredicate n r
295− , respPreds :: ResponsePredicate n r
296− } deriving (Generic, Functor)
297−
298−instance (Monoid n, Monoid r) => Monoid (Predicates n r) where
299− mempty = Predicates mempty mempty
300− a `mappend` b = Predicates (reqPreds a <> reqPreds b) (respPreds a <> respPreds b)
399+instance Semigroup RequestPredicate where
400+ RequestPredicate a <> RequestPredicate b = RequestPredicate $ \r mgr ->
401+ liftM2 (<>) (a r mgr) (b r mgr)
301402
403+-- | A set of predicates. Construct one with 'mempty' and '<%>'.
404+data Predicates = Predicates
405+ { requestPredicates :: RequestPredicate
406+ , responsePredicates :: ResponsePredicate
407+ } deriving (Generic)
302408
409+instance Semigroup Predicates where
410+ a <> b = Predicates (requestPredicates a <> requestPredicates b)
411+ (responsePredicates a <> responsePredicates b)
303412
304−class JoinPreds a where
305− joinPreds :: a -> Predicates [Text] [Text] -> Predicates [Text] [Text]
413+instance Monoid Predicates where
414+ mempty = Predicates mempty mempty
415+ mappend = (<>)
306416
307−instance JoinPreds (RequestPredicate Text Bool) where
308− joinPreds p (Predicates x y) = Predicates (go <> x) y
309− where go = let p' = first return p
310− in fmap (\z -> if z then [] else reqPredName p') p'
417+class JoinPreds a where
418+ joinPreds :: a -> Predicates -> Predicates
311419
312−instance JoinPreds (ResponsePredicate Text Bool) where
313− joinPreds p (Predicates x y) = Predicates x (go <> y)
314− where go = let p' = first return p
315− in fmap (\z -> if z then [] else respPredName p') p'
420+instance JoinPreds (RequestPredicate ) where
421+ joinPreds p (Predicates x y) = Predicates (p <> x) y
316422
423+instance JoinPreds (ResponsePredicate ) where
424+ joinPreds p (Predicates x y) = Predicates x (p <> y)
317425
318426-- | Adds a new predicate (either `ResponsePredicate` or `RequestPredicate`) to
319427-- the existing predicates.
320428--
321429-- > not500 <%> onlyJsonObjects <%> empty
322−(<%>) :: JoinPreds a => a -> Predicates [Text] [Text] -> Predicates [Text] [Text]
430+--
431+-- /Since 0.0.0.0/
432+(<%>) :: JoinPreds a => a -> Predicates -> Predicates
323433(<%>) = joinPreds
324434infixr 6 <%>
325435
326−finishPredicates :: Predicates [Text] [Text] -> Request -> Manager -> IO [Text]
327−finishPredicates p req mgr = do
328− (soFar, resps) <- reqResps (reqPreds p) req mgr
329− return $ soFar <> mconcat [respPred (respPreds p) r | r <- resps]
436+finishPredicates :: Predicates -> Request -> Manager -> IO (Maybe PredicateFailure)
437+finishPredicates p req mgr = go `catch` \(e :: PredicateFailure) -> return $ Just e
438+ where
439+ go = do
440+ resps <- getRequestPredicate (requestPredicates p) req mgr
441+ mapM_ (getResponsePredicate $ responsePredicates p) resps
442+ return Nothing
330443
331444-- * helpers
332445
@@ -334,3 +447,15 @@ hasValidHeader :: SBS.ByteString -> (SBS.ByteString -> Bool) -> Response b -> Bo
334447hasValidHeader hdr p r = case lookup (mk hdr) (responseHeaders r) of
335448 Nothing -> False
336449 Just v -> p v
450+
451+isRFC822Date :: SBS.ByteString -> Bool
452+isRFC822Date s
453+ = case parseTimeM True defaultTimeLocale rfc822DateFormat (SBSC.unpack s) of
454+ Nothing -> False
455+ Just (_ :: UTCTime) -> True
456+
457+status2XX :: Monad m => Maybe Request -> Response LBS.ByteString -> T.Text -> m ()
458+status2XX mreq resp t
459+ | status200 <= responseStatus resp && responseStatus resp < status300
460+ = return ()
461+ | otherwise = throw $ PredicateFailure t mreq resp