File: RunSpec.hs

package info (click to toggle)
haskell-warp 3.4.9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 456 kB
  • sloc: haskell: 4,873; makefile: 10
file content (518 lines) | stat: -rw-r--r-- 20,923 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}

module RunSpec (main, spec, withApp, MySocket, msWrite, msRead, withMySocket) where

import Control.Concurrent (forkIO, killThread, threadDelay)
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
import Control.Concurrent.STM
import Control.Monad (forM_, replicateM_, unless)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import Data.ByteString.Builder (byteString)
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as L
import qualified Data.IORef as I
import Data.Streaming.Network (bindPortTCP, getSocketTCP, safeRecv)
import Network.HTTP.Types
import Network.Socket
import Network.Socket.ByteString (sendAll)
import Network.Wai hiding (responseHeaders)
import Network.Wai.Handler.Warp
import System.IO.Unsafe (unsafePerformIO)
import System.Timeout (timeout)
import Test.Hspec
import Control.Exception (IOException, bracket, onException, try)
import qualified Control.Exception as E

import HTTP

main :: IO ()
main = hspec spec

type Counter = I.IORef (Either String Int)
type CounterApplication = Counter -> Application

data MySocket = MySocket
    { msSocket :: !Socket
    , msBuffer :: !(I.IORef ByteString)
    }

msWrite :: MySocket -> ByteString -> IO ()
msWrite = sendAll . msSocket

msRead :: MySocket -> Int -> IO ByteString
msRead (MySocket s ref) expected = do
    bs <- I.readIORef ref
    inner (bs :) (S.length bs)
  where
    inner front total =
        case compare total expected of
            EQ -> do
                I.writeIORef ref mempty
                pure $ S.concat $ front []
            GT -> do
                let bs = S.concat $ front []
                    (x, y) = S.splitAt expected bs
                I.writeIORef ref y
                pure x
            LT -> do
                bs <- safeRecv s 4096
                if S.null bs
                    then do
                        I.writeIORef ref mempty
                        pure $ S.concat $ front []
                    else inner (front . (bs :)) (total + S.length bs)

msClose :: MySocket -> IO ()
msClose = Network.Socket.close . msSocket

connectTo :: Int -> IO MySocket
connectTo port = do
    s <- fst <$> getSocketTCP "127.0.0.1" port
    ref <- I.newIORef mempty
    return
        MySocket
            { msSocket = s
            , msBuffer = ref
            }

withMySocket :: (MySocket -> IO a) -> Int -> IO a
withMySocket body port = bracket (connectTo port) msClose body

incr :: MonadIO m => Counter -> m ()
incr icount = liftIO $ I.atomicModifyIORef icount $ \ecount ->
    ( case ecount of
        Left s -> Left s
        Right i -> Right $ i + 1
    , ()
    )

err :: (MonadIO m, Show a) => Counter -> a -> m ()
err icount msg = liftIO $ I.writeIORef icount $ Left $ show msg

readBody :: CounterApplication
readBody icount req f = do
    body <- consumeBody $ getRequestBodyChunk req
    case () of
        ()
            | pathInfo req == ["hello"] && L.fromChunks body /= "Hello" ->
                err icount ("Invalid hello" :: String, body)
            | requestMethod req == "GET" && L.fromChunks body /= "" ->
                err icount ("Invalid GET" :: String, body)
            | requestMethod req `notElem` ["GET", "POST"] ->
                err icount ("Invalid request method (readBody)" :: String, requestMethod req)
            | otherwise -> incr icount
    f $ responseLBS status200 [] "Read the body"

ignoreBody :: CounterApplication
ignoreBody icount req f = do
    if requestMethod req `elem` ["GET", "POST"]
        then incr icount
        else err icount ("Invalid request method" :: String, requestMethod req)
    f $ responseLBS status200 [] "Ignored the body"

doubleConnect :: CounterApplication
doubleConnect icount req f = do
    _ <- consumeBody $ getRequestBodyChunk req
    _ <- consumeBody $ getRequestBodyChunk req
    incr icount
    f $ responseLBS status200 [] "double connect"

nextPort :: I.IORef Int
nextPort = unsafePerformIO $ I.newIORef 5000
{-# NOINLINE nextPort #-}

getPort :: IO Int
getPort = do
    port <- I.atomicModifyIORef nextPort $ \p -> (p + 1, p)
    esocket <- try $ bindPortTCP port "127.0.0.1"
    case esocket of
        Left (_ :: IOException) -> RunSpec.getPort
        Right sock -> do
            close sock
            return port

withApp :: Settings -> Application -> (Int -> IO a) -> IO a
withApp settings app f = do
    port <- RunSpec.getPort
    baton <- newEmptyMVar
    let settings' =
            setPort port $
                setHost "127.0.0.1" $
                    setBeforeMainLoop
                        (putMVar baton ())
                        settings
    bracket
        (forkIO $ runSettings settings' app `onException` putMVar baton ())
        killThread
        ( const $ do
            takeMVar baton
            -- use timeout to make sure we don't take too long
            mres <- timeout (60 * 1000 * 1000) (f port)
            case mres of
                Nothing -> error "Timeout triggered, too slow!"
                Just a -> pure a
        )

runTest
    :: Int
    -- ^ expected number of requests
    -> CounterApplication
    -> [ByteString]
    -- ^ chunks to send
    -> IO ()
runTest expected app chunks = do
    ref <- I.newIORef (Right 0)
    withApp defaultSettings (app ref) $ withMySocket $ \ms -> do
        forM_ chunks $ \chunk -> msWrite ms chunk
        _ <- timeout 100000 $ replicateM_ expected $ msRead ms 4096
        res <- I.readIORef ref
        case res of
            Left s -> error s
            Right i -> i `shouldBe` expected

dummyApp :: Application
dummyApp _ f = f $ responseLBS status200 [] "foo"

runTerminateTest
    :: InvalidRequest
    -> ByteString
    -> IO ()
runTerminateTest expected input = do
    ref <- I.newIORef Nothing
    let onExc _ = I.writeIORef ref . Just
    withApp (setOnException onExc defaultSettings) dummyApp $ withMySocket $ \ms -> do
        msWrite ms input
        msClose ms -- explicitly
        threadDelay 5000
        res <- I.readIORef ref
        show res `shouldBe` show (Just expected)

singleGet :: ByteString
singleGet = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"

singlePostHello :: ByteString
singlePostHello = "POST /hello HTTP/1.1\r\nHost: localhost\r\nContent-length: 5\r\n\r\nHello"

singleChunkedPostHello :: [ByteString]
singleChunkedPostHello =
    [ "POST /hello HTTP/1.1\r\nHost: localhost\r\nTransfer-Encoding: chunked\r\n\r\n"
    , "5\r\nHello\r\n0\r\n"
    ]

spec :: Spec
spec = do
    describe "non-pipelining" $ do
        it "no body, read" $ runTest 5 readBody $ replicate 5 singleGet
        it "no body, ignore" $ runTest 5 ignoreBody $ replicate 5 singleGet
        it "has body, read" $
            runTest
                2
                readBody
                [ singlePostHello
                , singleGet
                ]
        it "has body, ignore" $
            runTest
                2
                ignoreBody
                [ singlePostHello
                , singleGet
                ]
        it "chunked body, read" $
            runTest 2 readBody $
                singleChunkedPostHello ++ [singleGet]
        it "chunked body, ignore" $
            runTest 2 ignoreBody $
                singleChunkedPostHello ++ [singleGet]
    describe "pipelining" $ do
        it "no body, read" $ runTest 5 readBody [S.concat $ replicate 5 singleGet]
        it "no body, ignore" $ runTest 5 ignoreBody [S.concat $ replicate 5 singleGet]
        it "has body, read" $
            runTest 2 readBody $
                return $
                    S.concat
                        [ singlePostHello
                        , singleGet
                        ]
        it "has body, ignore" $
            runTest 2 ignoreBody $
                return $
                    S.concat
                        [ singlePostHello
                        , singleGet
                        ]
        it "chunked body, read" $
            runTest 2 readBody $
                return $
                    S.concat
                        [ S.concat singleChunkedPostHello
                        , singleGet
                        ]
        it "chunked body, ignore" $
            runTest 2 ignoreBody $
                return $
                    S.concat
                        [ S.concat singleChunkedPostHello
                        , singleGet
                        ]
    describe "no hanging" $ do
        it "has body, read" $
            runTest 1 readBody $
                map S.singleton $
                    S.unpack singlePostHello
        it "double connect" $ runTest 1 doubleConnect [singlePostHello]

    describe "connection termination" $ do
        -- it "ConnectionClosedByPeer" $ runTerminateTest ConnectionClosedByPeer "GET / HTTP/1.1\r\ncontent-length: 10\r\n\r\nhello"
        it "IncompleteHeaders" $ do
            runTerminateTest IncompleteHeaders "GET / HTTP/1.1\r\ncontent-length: 10\r\n\r"
            runTerminateTest IncompleteHeaders "GET / HTTP/1.1\r\ncontent-length: 10\r\n"
            runTerminateTest IncompleteHeaders "GET / HTTP/1.1\r\ncontent-length: 10\r"
            runTerminateTest IncompleteHeaders "GET / HTTP/1.1\r\ncontent-lengt"

    describe "special input" $ do
        let appWithSocket f = do
                iheaders <- I.newIORef []
                let app req respond = do
                        liftIO $ I.writeIORef iheaders $ requestHeaders req
                        respond $ responseLBS status200 [] ""
                withApp defaultSettings app $ withMySocket $ f iheaders

        it "multiline headers" $ do
            appWithSocket $ \iheaders ms -> do
                let input = "GET / HTTP/1.1\r\nfoo:    bar\r\n baz\r\n\tbin\r\n\r\n"
                msWrite ms input
                threadDelay 5000
                headers <- I.readIORef iheaders
                headers
                    `shouldBe` [ ("foo", "bar")
                               , (" baz", "")
                               , ("\tbin", "")
                               ]
        it "no space between colon and value" $ do
            appWithSocket $ \iheaders ms -> do
                let input = "GET / HTTP/1.1\r\nfoo:bar\r\n\r\n"
                msWrite ms input
                threadDelay 5000
                headers <- I.readIORef iheaders
                headers `shouldBe` [("foo", "bar")]
        it "does not recognize multiline headers" $ do
            appWithSocket $ \iheaders ms -> do
                msWrite ms "GET / HTTP/1.1\r\nfoo: and\r\n"
                msWrite ms " baz as well\r\n\r\n"
                threadDelay 5000
                headers <- I.readIORef iheaders
                headers
                    `shouldBe` [ ("foo", "and")
                               , (" baz as well", "")
                               ]

    describe "chunked bodies" $ do
        it "works" $ do
            countVar <- newTVarIO (0 :: Int)
            ifront <- I.newIORef id
            let app req f = do
                    bss <- consumeBody $ getRequestBodyChunk req
                    liftIO $ I.atomicModifyIORef ifront $ \front -> (front . (S.concat bss :), ())
                    atomically $ modifyTVar countVar (+ 1)
                    f $ responseLBS status200 [] ""
            withApp defaultSettings app $ withMySocket $ \ms -> do
                let input =
                        S.concat
                            [ "POST / HTTP/1.1\r\nTransfer-Encoding: Chunked\r\n\r\n"
                            , "c\r\nHello World\n\r\n3\r\nBye\r\n0\r\n\r\n"
                            , "POST / HTTP/1.1\r\nTransfer-Encoding: Chunked\r\n\r\n"
                            , "b\r\nHello World\r\n0\r\n\r\n"
                            ]
                msWrite ms input
                atomically $ do
                    count <- readTVar countVar
                    check $ count == 2
                front <- I.readIORef ifront
                front []
                    `shouldBe` [ "Hello World\nBye"
                               , "Hello World"
                               ]
        it "lots of chunks" $ do
            ifront <- I.newIORef id
            countVar <- newTVarIO (0 :: Int)
            let app req f = do
                    bss <- consumeBody $ getRequestBodyChunk req
                    I.atomicModifyIORef ifront $ \front -> (front . (S.concat bss :), ())
                    atomically $ modifyTVar countVar (+ 1)
                    f $ responseLBS status200 [] ""
            withApp defaultSettings app $ withMySocket $ \ms -> do
                let input =
                        concat $
                            replicate 2 $
                                ["POST / HTTP/1.1\r\nTransfer-Encoding: Chunked\r\n\r\n"]
                                    ++ replicate 50 "5\r\n12345\r\n"
                                    ++ ["0\r\n\r\n"]
                mapM_ (msWrite ms) input
                atomically $ do
                    count <- readTVar countVar
                    check $ count == 2
                front <- I.readIORef ifront
                front [] `shouldBe` replicate 2 (S.concat $ replicate 50 "12345")
        -- For some reason, the following test on Windows causes the socket
        -- to be killed prematurely. Worth investigating in the future if possible.
        it "in chunks" $ do
            ifront <- I.newIORef id
            countVar <- newTVarIO (0 :: Int)
            let app req f = do
                    bss <- consumeBody $ getRequestBodyChunk req
                    liftIO $ I.atomicModifyIORef ifront $ \front -> (front . (S.concat bss :), ())
                    atomically $ modifyTVar countVar (+ 1)
                    f $ responseLBS status200 [] ""
            withApp defaultSettings app $ withMySocket $ \ms -> do
                let input =
                        S.concat
                            [ "POST / HTTP/1.1\r\nTransfer-Encoding: Chunked\r\n\r\n"
                            , "c\r\nHello World\n\r\n3\r\nBye\r\n0\r\n"
                            , "POST / HTTP/1.1\r\nTransfer-Encoding: Chunked\r\n\r\n"
                            , "b\r\nHello World\r\n0\r\n\r\n"
                            ]
                mapM_ (msWrite ms . S.singleton) $ S.unpack input
                atomically $ do
                    count <- readTVar countVar
                    check $ count == 2
                front <- I.readIORef ifront
                front []
                    `shouldBe` [ "Hello World\nBye"
                               , "Hello World"
                               ]
        it "timeout in request body" $ do
            ifront <- I.newIORef id
            let app req f = do
                    bss <-
                        consumeBody (getRequestBodyChunk req)
                            `onException` liftIO
                                (I.atomicModifyIORef ifront (\front -> (front . ("consume interrupted" :), ())))
                    liftIO $
                        threadDelay 4000000 `E.catch` \e -> do
                            I.atomicModifyIORef
                                ifront
                                ( \front ->
                                    ( front . ((S8.pack $ "threadDelay interrupted: " ++ show e) :)
                                    , ()
                                    )
                                )
                            E.throwIO (e :: E.SomeException)
                    liftIO $ I.atomicModifyIORef ifront $ \front -> (front . (S.concat bss :), ())
                    f $ responseLBS status200 [] ""
            withApp (setTimeout 1 defaultSettings) app $ withMySocket $ \ms -> do
                let bs1 = S.replicate 2048 88
                    bs2 = "This is short"
                    bs = S.append bs1 bs2
                msWrite ms "POST / HTTP/1.1\r\n"
                msWrite ms "content-length: "
                msWrite ms $ S8.pack $ show $ S.length bs
                msWrite ms "\r\n\r\n"
                threadDelay 100000
                msWrite ms bs1
                threadDelay 100000
                msWrite ms bs2
                threadDelay 5000000
                front <- I.readIORef ifront
                S.concat (front []) `shouldBe` bs
    describe "raw body" $ do
        it "works" $ do
            let app _req f = do
                    let backup = responseLBS status200 [] "Not raw"
                    f $ flip responseRaw backup $ \src sink -> do
                        let loop = do
                                bs <- src
                                unless (S.null bs) $ do
                                    sink $ doubleBS bs
                                    loop
                        loop
                doubleBS = S.concatMap $ \w -> S.pack [w, w]
            withApp defaultSettings app $ withMySocket $ \ms -> do
                msWrite ms "POST / HTTP/1.1\r\n\r\n12345"
                timeout 100000 (msRead ms 10) `shouldReturn` Just "1122334455"
                msWrite ms "67890"
                timeout 100000 (msRead ms 10) `shouldReturn` Just "6677889900"
    it "only one date and server header" $ do
        let app _ f =
                f $
                    responseLBS
                        status200
                        [ ("server", "server")
                        , ("date", "date")
                        ]
                        ""
            getValues key =
                map snd
                    . filter (\(key', _) -> key == key')
                    . responseHeaders
        withApp defaultSettings app $ \port -> do
            res <- sendGET $ "http://127.0.0.1:" ++ show port
            getValues hServer res `shouldBe` ["server"]
            getValues hDate res `shouldBe` ["date"]

    it "streaming echo #249" $ do
        countVar <- newTVarIO (0 :: Int)
        let app req f = f $ responseStream status200 [] $ \write _ -> do
                let loop = do
                        bs <- getRequestBodyChunk req
                        unless (S.null bs) $ do
                            write $ byteString bs
                            atomically $ modifyTVar countVar (+ 1)
                            loop
                loop
        withApp defaultSettings app $ withMySocket $ \ms -> do
            msWrite ms "POST / HTTP/1.1\r\ntransfer-encoding: chunked\r\n\r\n"
            threadDelay 10000
            msWrite ms "5\r\nhello\r\n0\r\n\r\n"
            atomically $ do
                count <- readTVar countVar
                check $ count >= 1
            bs <- safeRecv (msSocket ms) 4096 -- must not use msRead
            S.takeWhile (/= 13) bs `shouldBe` "HTTP/1.1 200 OK"

    it "streaming response with length" $ do
        let app _ f = f $ responseStream status200 [("content-length", "20")] $ \write _ -> do
                replicateM_ 4 $ write $ byteString "Hello"
        withApp defaultSettings app $ \port -> do
            res <- sendGET $ "http://127.0.0.1:" ++ show port
            responseBody res `shouldBe` "HelloHelloHelloHello"

    describe "head requests" $ do
        let fp = "test/head-response"
        let app req f =
                f $ case pathInfo req of
                    ["builder"] -> responseBuilder status200 [] $ error "should never be evaluated"
                    ["streaming"] -> responseStream status200 [] $ \write _ ->
                        write $ error "should never be evaluated"
                    ["file"] -> responseFile status200 [] fp Nothing
                    _ -> error "invalid path"
        it "builder" $ withApp defaultSettings app $ \port -> do
            res <- sendHEAD $ concat ["http://127.0.0.1:", show port, "/builder"]
            responseBody res `shouldBe` ""
        it "streaming" $ withApp defaultSettings app $ \port -> do
            res <- sendHEAD $ concat ["http://127.0.0.1:", show port, "/streaming"]
            responseBody res `shouldBe` ""
        it "file, no range" $ withApp defaultSettings app $ \port -> do
            bs <- S.readFile fp
            res <- sendHEAD $ concat ["http://127.0.0.1:", show port, "/file"]
            getHeaderValue hContentLength (responseHeaders res)
                `shouldBe` Just (S8.pack $ show $ S.length bs)
        it "file, with range" $ withApp defaultSettings app $ \port -> do
            res <-
                sendHEADwH
                    (concat ["http://127.0.0.1:", show port, "/file"])
                    [(hRange, "bytes=0-1")]
            getHeaderValue hContentLength (responseHeaders res) `shouldBe` Just "2"

consumeBody :: IO ByteString -> IO [ByteString]
consumeBody body =
    loop id
  where
    loop front = do
        bs <- body
        if S.null bs
            then return $ front []
            else loop $ front . (bs :)