packages feed

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

-- | The client against a TLS server on the loopback interface, which
-- presents the certificate of the fixtures.
module Main (main) where

import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (wait, withAsync)
import Control.Exception (SomeException, bracket, try)
import Data.ByteString (ByteString, pack)
import Data.ByteString qualified as BS (concat, length, null, splitAt)
import Data.ByteString.Lazy (fromStrict)
import Network.Socket (Family (AF_INET), SockAddr (SockAddrInet),
                       SocketOption (ReuseAddr), SocketType (Stream), accept,
                       bind, close, connect, defaultProtocol, listen,
                       setSocketOption, socketPort, tupleToHostAddress)
import Network.Socket qualified as N (socket)
import Network.Socket.ByteString (recv, sendAll)
import Network.TLS (Context, Credentials (Credentials),
                    ServerParams (serverShared), Shared (sharedCredentials),
                    TLSException (HandshakeFailed), bye, contextClose,
                    contextNew, credentialLoadX509, defaultParamsServer,
                    handshake, recvData, sendData)
import Streamly.Data.Array qualified as A (length)
import Streamly.Data.Stream (fold, fromList, toList, unfoldrM)
import Streamly.Data.StreamK (fromStream, uncons)
import Streamly.External.ByteString (fromArray, toArray)
import Streamly.External.Network.TLS (Certificates (CertificatesFrom),
                                      Config (certificates, connectTimeout, host, port, serverName),
                                      ConnectTimedOut (ConnectTimedOut),
                                      acceptConnection, config, loadCredentials,
                                      received, send, withConnection, write)
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"

-- | Serve one connection over TLS with the certificate of the fixtures,
-- and run a client against the port. Returns what both return; the
-- server gives 'Nothing' when its side failed, as it does when the client
-- refuses the certificate.
withServer :: (Context -> IO a) -> (Int -> IO b) -> IO (Maybe a, b)
withServer serve run = do
  credential <- credentialLoadX509 certificateFile keyFile >>= either fail pure
  let shared = (serverShared defaultParamsServer) {sharedCredentials = Credentials [credential]}
      parameters = defaultParamsServer {serverShared = shared}
  bracket listening close $ \listener -> do
    port <- socketPort listener
    let accepted = bracket (fst <$> accept listener) close $ \peer ->
          bracket (contextNew peer parameters) contextClose $ \context -> do
            handshake context
            value <- serve context
            bye context
            pure value
    withAsync (try @SomeException accepted) $ \server -> do
      result <- run (fromIntegral port)
      served <- wait server
      pure (either (const Nothing) Just served, result)
  where
    listening = do
      listener <- N.socket AF_INET Stream defaultProtocol
      setSocketOption listener ReuseAddr 1
      bind listener (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))
      listen listener 1
      pure listener

-- | The server of the fixtures, reached by its name and trusted through
-- its own certificate.
local :: Int -> Config
local port = (config "localhost" port) {certificates = CertificatesFrom certificateFile}

-- | Read until a number of bytes came.
receiveExactly :: Context -> Int -> IO ByteString
receiveExactly context = go ""
  where
    go seen wanted
      | BS.length seen >= wanted = pure seen
      | otherwise = do
          more <- recvData context
          if BS.null more then pure seen else go (seen <> more) wanted

refusedByClient :: Config -> IO ()
refusedByClient settings = do
  (_, outcome) <- withServer (\_ -> pure ()) $ \port ->
    try (withConnection settings {port} (\_ -> pure ()))
  case outcome of
    Left (HandshakeFailed _) -> pure ()
    Left other -> assertFailure ("expected HandshakeFailed, got " <> show other)
    Right () -> assertFailure "the certificate was accepted"

tests :: TestTree
tests =
  localOption (mkTimeout 20_000_000) $
    testGroup
      "streamly-network-tls"
      [ testCase "bytes go both ways, and the stream ends when the server ends" $ do
          let serve context = do
                question <- receiveExactly context 5
                sendData context (fromStrict ("you said " <> question))
                pure question
          (question, answer) <- withServer serve $ \port ->
            withConnection (local port) $ \connection -> do
              send connection (toArray "hello")
              BS.concat . map fromArray <$> toList (received connection)
          (question, answer) @?= (Just "hello", "you said hello")
      , testCase "a megabyte each way" $ do
          let payload = pack (take 1_000_000 (cycle [0 .. 250]))
              serve context = do
                got <- receiveExactly context (BS.length payload)
                sendData context (fromStrict got)
                pure (BS.length got)
          (size, echoed) <- withServer serve $ \port ->
            withConnection (local port) $ \connection -> do
              fold (write connection) (fromList (map toArray (pieces 70_000 payload)))
              BS.concat . map fromArray <$> toList (received connection)
          size @?= Just (BS.length payload)
          echoed @?= payload
      , testCase "the server sees when the client is done" $ do
          let serve context = (,) <$> receiveExactly context 3 <*> recvData context
          (seen, ()) <- withServer serve $ \port ->
            withConnection (local port) (\connection -> send connection (toArray "end"))
          seen @?= Just ("end", "")
      , testCase "a certificate signed by nobody the system trusts is refused" $
          refusedByClient (config "localhost" 0)
      , testCase "a certificate for another name is refused" $
          refusedByClient (local 0) {host = "127.0.0.1", serverName = "example.org"}
      , testCase "the name checked can differ from the host connected to" $ do
          (_, outcome) <- withServer (\_ -> pure ()) $ \port ->
            try @SomeException (withConnection (local port) {host = "127.0.0.1", serverName = "localhost"} (\_ -> pure ()))
          either (assertFailure . show) pure outcome
      , testCase "certificates that cannot be read are an IOError" $
          try (withConnection (config "localhost" 1) {certificates = CertificatesFrom "test/fixtures/missing.pem"} (\_ -> pure ())) >>= \case
            Left (_ :: IOError) -> pure ()
            Right () -> assertFailure "no error, expected an IOError"
      , testCase "nothing listening is an IOError" $ do
          port <- bracket (N.socket AF_INET Stream defaultProtocol) close $ \socket -> do
            bind socket (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))
            fromIntegral <$> socketPort socket
          try (withConnection (local port) (\_ -> pure ())) >>= \case
            Left (_ :: IOError) -> pure ()
            Right () -> assertFailure "no error, expected an IOError"
      , testCase "a server that accepts and never starts the handshake" $
          bracket plainServer close $ \listener -> do
            port <- socketPort listener
            let hold = bracket (fst <$> accept listener) close (\_ -> threadDelay 10_000_000)
            withAsync hold $ \_ ->
              try (withConnection (local (fromIntegral port)) {connectTimeout = Just 150_000} (\_ -> pure ())) >>= (@?= Left ConnectTimedOut)
      , testCase "the server of this library: bytes go both ways, several megabytes" $ do
          let payload = pack (take 3_000_000 (cycle [0 .. 250]))
          credentials <- loadCredentials certificateFile keyFile
          bracket plainServer close $ \listener -> do
            port <- socketPort listener
            let serve = bracket (fst <$> accept listener) close $ \peer ->
                  acceptConnection credentials (Just 5_000_000) peer $ \connection -> do
                    -- Send back what comes, as it comes.
                    fold (write connection) (received connection)
            withAsync serve $ \server -> do
              echoed <- withConnection (local (fromIntegral port)) $ \connection ->
                withAsync (fold (write connection) (fromList (map toArray (pieces 70_000 payload)))) $ \_ ->
                  BS.concat . map fromArray <$> toList (takeBytes (BS.length payload) (received connection))
              wait server
              echoed @?= payload
      , testCase "the server gives up on a client that never starts the handshake" $ do
          credentials <- loadCredentials certificateFile keyFile
          bracket plainServer close $ \listener -> do
            port <- socketPort listener
            let silent = bracket (N.socket AF_INET Stream defaultProtocol) close $ \socket -> do
                  connect socket (SockAddrInet port (tupleToHostAddress (127, 0, 0, 1)))
                  threadDelay 10_000_000
            withAsync silent $ \_ ->
              bracket (fst <$> accept listener) close $ \peer ->
                try (acceptConnection credentials (Just 150_000) peer (\_ -> pure ())) >>= (@?= Left ConnectTimedOut)
      , testCase "credentials that cannot be read are an IOError" $
          try (loadCredentials "test/fixtures/missing.pem" keyFile) >>= \case
            Left (_ :: IOError) -> pure ()
            Right _ -> assertFailure "no error, expected an IOError"
      , testCase "a server that does not speak TLS is refused" $
          bracket plainServer close $ \listener -> do
            port <- socketPort listener
            let answer = bracket (fst <$> accept listener) close $ \peer -> do
                  _ <- recv peer 4096
                  sendAll peer "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n"
            withAsync (try @SomeException answer) $ \_ ->
              try (withConnection (local (fromIntegral port)) (\_ -> pure ())) >>= \case
                Left (_ :: TLSException) -> pure ()
                Right () -> assertFailure "no error, expected a TLSException"
      ]
  where
    pieces size bytes
      | BS.null bytes = []
      | otherwise = let (front, back) = BS.splitAt size bytes in front : pieces size back
    -- The arrays of a stream until a number of bytes came.
    takeBytes wanted stream = unfoldrM step (wanted, fromStream stream)
      where
        step (left, from)
          | left <= (0 :: Int) = pure Nothing
          | otherwise = fmap (\(array, rest) -> (array, (left - A.length array, rest))) <$> uncons from
    plainServer = do
      listener <- N.socket AF_INET Stream defaultProtocol
      bind listener (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))
      listen listener 1
      pure listener