packages feed

streamly-websockets-tls-0.1.0.0: test/Main.hs

-- | WebSockets by URL and over TLS, between the client and the servers of
-- these libraries on the loopback interface.
module Main (main) where

import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (withAsync)
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
import Control.Concurrent.STM (atomically)
import Control.Exception (bracket, try)
import Data.ByteString qualified as BS (replicate)
import Data.ByteString.Char8 (pack)
import Network.Socket (Family (AF_INET), SockAddr (SockAddrInet),
                       SocketType (Stream), accept, close, connect,
                       defaultProtocol, socketPort, tupleToHostAddress)
import Network.Socket qualified as N (socket)
import Network.Socket.ByteString (recv, sendAll)
import Network.TLS (TLSException (HandshakeFailed))
import Streamly.Data.Fold (drainMapM)
import Streamly.Data.Stream (fold, toList)
import Streamly.Data.Stream qualified as S (take)
import Streamly.External.Network.HTTP (HttpError (..))
import Streamly.External.Network.WebSocket (Config (host, openTimeout, path, port),
                                            Connection,
                                            Message (BinaryMessage, TextMessage),
                                            WebSocketError (OpenTimedOut),
                                            config, messages, ping, pongCount,
                                            receive, send)
import Streamly.External.Network.WebSocket.Server (Upgrade (..),
                                                   defaultServerOptions, listen,
                                                   serveSocket)
import Streamly.External.Network.WebSocket.TLS (Certificates (CertificatesFrom),
                                                Scheme (Http, Https),
                                                loadCredentials,
                                                serveSecureSocket, urlConfig,
                                                withConnectionAt, withUrl)
import Test.Tasty (TestTree, defaultMain, localOption, mkTimeout, testGroup)
import Test.Tasty.HUnit (assertFailure, testCase, (@?=))

main :: IO ()
main = defaultMain tests

certificateFile, keyFile :: FilePath
certificateFile = "test/fixtures/localhost-cert.pem"
keyFile = "test/fixtures/localhost-key.pem"

-- | The certificate of the fixtures, trusted for itself.
local :: Certificates
local = CertificatesFrom certificateFile

-- | Send back every message received.
echoBack :: Upgrade -> Connection -> IO ()
echoBack _ connection = fold (drainMapM (send connection)) (messages connection)

-- | Serve over TLS with a handler on a free port of the loopback
-- interface, and run something against the port.
withSecureServer :: (Upgrade -> Connection -> IO ()) -> (Int -> IO a) -> IO a
withSecureServer handler run = do
  credentials <- loadCredentials certificateFile keyFile
  bracket (listen "127.0.0.1" 0) close $ \listener -> do
    port <- socketPort listener
    withAsync (serveSecureSocket credentials listener defaultServerOptions handler) $ \_ -> run (fromIntegral port)

-- | The same, in clear.
withClearServer :: (Upgrade -> Connection -> IO ()) -> (Int -> IO a) -> IO a
withClearServer handler run =
  bracket (listen "127.0.0.1" 0) close $ \listener -> do
    port <- socketPort listener
    withAsync (serveSocket listener defaultServerOptions handler) $ \_ -> run (fromIntegral port)

tests :: TestTree
tests =
  localOption (mkTimeout 20_000_000) $
    testGroup
      "streamly-websockets-tls"
      [ testCase "what a ws or wss URL stands for" $ do
          let summary = fmap (\(scheme, settings) -> (scheme, settings.host, settings.port, settings.path)) . urlConfig
          summary "ws://example.org/chat?room=1" @?= Right (Http, "example.org", 80, "/chat?room=1")
          summary "WSS://Example.org" @?= Right (Https, "example.org", 443, "/")
          summary "wss://[::1]:9443/api#top" @?= Right (Https, "::1", 9443, "/api")
          map summary ["", "example.org", "http://example.org/", "https://example.org/", "ws:/example.org", "ws://", "ws://user@example.org/", "wss://example.org/a b"]
            @?= replicate 8 (Left "not a ws or wss URL")
      , testCase "messages go over TLS and come back, of every length form" $ do
          let sizes = [0, 125, 126, 65535, 65536, 300_000]
          outcome <- withSecureServer echoBack $ \port ->
            withConnectionAt local Https (config "localhost" port "/") $ \connection -> do
              ping connection "x"
              send connection (TextMessage "héllo")
              mapM_ (\size -> send connection (BinaryMessage (BS.replicate size 7))) sizes
              answers <- toList (S.take (1 + length sizes) (messages connection))
              pongs <- atomically (pongCount connection)
              pure (answers, pongs)
          outcome @?= (TextMessage "héllo" : map (\size -> BinaryMessage (BS.replicate size 7)) sizes, 1)
      , testCase "a ws URL goes in clear, with its path" $ do
          asked <- newEmptyMVar
          answer <- withClearServer (\upgrade connection -> putMVar asked upgrade.path >> echoBack upgrade connection) $ \port ->
            withUrl ("ws://127.0.0.1:" <> pack (show port) <> "/chat?room=1") $ \connection ->
              send connection (TextMessage "in clear") >> receive connection
          takeMVar asked >>= (@?= "/chat?room=1")
          answer @?= Just (TextMessage "in clear")
      , testCase "a wss URL goes over TLS, and a server the system does not know is refused" $
          withSecureServer echoBack $ \port ->
            try (withUrl ("wss://localhost:" <> pack (show port) <> "/") (\_ -> pure ())) >>= \case
              Left (HandshakeFailed _) -> pure ()
              Left other -> assertFailure ("expected HandshakeFailed, got " <> show other)
              Right () -> assertFailure "the certificate was accepted"
      , testCase "what is not a ws or wss URL is refused before any connection" $
          try (withUrl "https://example.org/" (\_ -> pure ())) >>= \case
            Left (InvalidRequest _) -> pure ()
            Left other -> assertFailure ("expected InvalidRequest, got " <> show other)
            Right () -> assertFailure "no error, expected InvalidRequest"
      , testCase "a wss connection to a server that speaks in clear is a TLS failure" $
          -- The server in clear answers 400 to what it reads as a request.
          withClearServer echoBack $ \port ->
            try (withConnectionAt local Https (config "localhost" port "/") (\_ -> pure ())) >>= \case
              Left (HandshakeFailed _) -> pure ()
              Left other -> assertFailure ("expected HandshakeFailed, got " <> show other)
              Right () -> assertFailure "no error, expected HandshakeFailed"
      , testCase "a wss connection to a server that says nothing gives up in time" $
          bracket (listen "127.0.0.1" 0) close $ \listener -> do
            port <- socketPort listener
            let hold = bracket (fst <$> accept listener) close (\_ -> threadDelay 10_000_000)
            withAsync hold $ \_ ->
              try (withConnectionAt local Https (config "localhost" (fromIntegral port) "/") {openTimeout = Just 200_000} (\_ -> pure ())) >>= (@?= Left OpenTimedOut)
      , testCase "the secure server goes on after a client that does not speak TLS" $ do
          served <- withSecureServer echoBack $ \port -> do
            bracket (N.socket AF_INET Stream defaultProtocol) close $ \socket -> do
              connect socket (SockAddrInet (fromIntegral port) (tupleToHostAddress (127, 0, 0, 1)))
              sendAll socket "GET / HTTP/1.1\r\nHost: x\r\n\r\n"
              _ <- recv socket 4096
              pure ()
            withConnectionAt local Https (config "localhost" port "/") (\connection -> send connection (TextMessage "still serving") >> receive connection)
          served @?= Just (TextMessage "still serving")
      , testCase "the handler of a secure server may close first" $ do
          received <- withSecureServer (\_ connection -> send connection (TextMessage "bye")) $ \port ->
            withConnectionAt local Https (config "localhost" port "/") (toList . messages)
          received @?= [TextMessage "bye"]
      ]