streamly-network-tls (empty) → 0.1.0.0
raw patch · 9 files changed
+674/−0 lines, 9 filesdep +asyncdep +basedep +bytestring
Dependencies added: async, base, bytestring, crypton-x509-store, crypton-x509-system, network, streamly-bytestring, streamly-core, streamly-network-tcp, streamly-network-tls, tasty, tasty-hunit, tls
Files
- CHANGELOG.md +13/−0
- LICENSE +29/−0
- README.md +86/−0
- src/Streamly/External/Network/TLS.hs +229/−0
- streamly-network-tls.cabal +87/−0
- test/Main.hs +205/−0
- test/fixtures/README.md +9/−0
- test/fixtures/localhost-cert.pem +11/−0
- test/fixtures/localhost-key.pem +5/−0
+ CHANGELOG.md view
@@ -0,0 +1,13 @@+# Revision history for streamly-network-tls++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* TLS connections to a server (`withConnection`; `open` and `close` for a+ connection that outlives a function), checked against the certificates+ of the system or of a file, within a time (`connectTimeout`).+* The side of a server: `loadCredentials` reads a certificate and its key,+ `acceptConnection` does the handshake on a connection already accepted.+* Bytes sent (`send`, `write`) and received as a stream (`received`);+ `transport` gives a connection as the `Transport` of+ streamly-network-tcp, which streamly-http and streamly-websockets take.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, Xavier Dectot+++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above+ copyright notice, this list of conditions and the following+ disclaimer in the documentation and/or other materials provided+ with the distribution.++ * Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived+ from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,86 @@+# streamly-network-tls++TLS for [Streamly](https://streamly.composewell.com/), for clients and for+servers, over the+[tls](https://hackage.haskell.org/package/tls) package. A connection gives+the bytes received as a stream of arrays and takes the bytes to send+through a function or a fold. It knows nothing of the protocol carried.++```haskell+{-# LANGUAGE OverloadedStrings #-}++import Streamly.Data.Stream (toList)+import Streamly.External.ByteString (toArray)+import Streamly.External.Network.TLS (config, received, send, withConnection)++main :: IO ()+main = withConnection (config "example.org" 443) $ \connection -> do+ send connection (toArray "GET / HTTP/1.0\r\nHost: example.org\r\n\r\n")+ toList (received connection) >>= print . length+```++## Certificates++The server must present a certificate valid for the name asked and signed+by a trusted authority: those of the system (`SystemCertificates`, the+default) or those of a file or a directory in PEM (`CertificatesFrom`),+which is how a server with a certificate of its own making is reached.+There is no way to skip the check.++## Servers++`acceptConnection` does the handshake of a server on a connection it has+accepted, with the certificate and the key read by `loadCredentials`:++```haskell+credentials <- loadCredentials "certificate.pem" "key.pem"+(peer, _) <- Network.Socket.accept listener+acceptConnection credentials (Just 30000000) peer $ \connection ->+ fold (write connection) (received connection)+```++## HTTPS and secure WebSockets++[streamly-http](https://github.com/GuillaumedeVolpiano/streamly-http) and+[streamly-websockets](https://github.com/GuillaumedeVolpiano/streamly-websockets)+take a connection opened by other means, as a `Transport`: `transport`+gives one from a connection of this library, which depends on neither of+them. The packages+[streamly-http-tls](https://github.com/GuillaumedeVolpiano/streamly-http-tls)+and+[streamly-websockets-tls](https://github.com/GuillaumedeVolpiano/streamly-websockets-tls)+put them together; by hand it reads:++```haskell+import Streamly.External.Network.HTTP (defaultLimits, fetchOver, get)+import Streamly.External.Network.TLS (transport, withConnection)+import Streamly.External.Network.TLS qualified as NT (config)+import Streamly.External.Network.WebSocket (Message (TextMessage), send,+ withConnectionOver)+import Streamly.External.Network.WebSocket qualified as WS (config)++page = withConnection (NT.config "example.org" 443) $ \connection ->+ fetchOver defaultLimits (transport connection) (get "example.org" 443 "/")++chat = withConnection (NT.config "example.org" 443) $ \connection ->+ withConnectionOver (transport connection) (WS.config "example.org" 443 "/chat") $ \socket ->+ send socket (TextMessage "hello")+```++## Building++To build against a copy of+[streamly-network-tcp](https://hackage.haskell.org/package/streamly-network-tcp)+checked out next to this repository, pass+`--project-file=cabal.project.siblings`.++## Limits of this version++- The connection and its handshake are limited in time (`connectTimeout`,+ thirty seconds by default); once open, nothing limits the waits.+- A server proves its name with a certificate and its key+ (`loadCredentials`, `acceptConnection`); it does not ask clients for+ certificates.+- No client certificate, no session resumption, no choice of protocol+ versions or ciphers: the defaults of the tls package.+- No application protocol negotiation (ALPN).
+ src/Streamly/External/Network/TLS.hs view
@@ -0,0 +1,229 @@+-- |+-- Module : Streamly.External.Network.TLS+-- Description : TLS connections to a server, as streams+-- License : BSD-3-Clause+--+-- A TLS client for Streamly, over the @tls@ package. A connection gives+-- the bytes received as a stream of arrays, and takes the bytes to send+-- through a function or a fold. It knows nothing of the protocol carried.+--+-- > {-# LANGUAGE OverloadedStrings #-}+-- > import Streamly.Data.Stream (toList)+-- > import Streamly.External.ByteString (toArray)+-- > import Streamly.External.Network.TLS (config, received, send, withConnection)+-- >+-- > main :: IO ()+-- > main = withConnection (config "example.org" 443) $ \connection -> do+-- > send connection (toArray "GET / HTTP/1.0\r\nHost: example.org\r\n\r\n")+-- > toList (received connection) >>= print . length+--+-- The server must present a certificate that is valid for the name asked+-- and signed by an authority that is trusted: those of the system, or+-- those of a file. There is no way to skip the check.+--+-- For the side of a server, 'acceptConnection' does the handshake on a+-- connection already accepted, with the t'Credentials' of the server.+module Streamly.External.Network.TLS+ ( -- * Connections+ Config (..)+ , config+ , Certificates (..)+ , Connection+ , withConnection+ , open+ , close+ , ConnectTimedOut (..)++ -- * The side of a server+ , Credentials+ , loadCredentials+ , acceptConnection++ -- * Bytes+ , send+ , write+ , received+ , transport+ ) where++import Control.Exception (Exception, IOException, SomeException, bracketOnError,+ finally, mask, throwIO, try)+import Control.Monad (void)+import Control.Monad.IO.Class (MonadIO (..))+import Data.ByteString qualified as BS (null)+import Data.ByteString.Lazy (fromStrict)+import Data.Word (Word8)+import Data.X509.CertificateStore (CertificateStore, readCertificateStore)+import Network.Socket (Socket)+import Network.Socket qualified as N (close)+import Network.TLS (ClientParams (clientShared), Context, Credential,+ ServerParams (serverShared),+ Shared (sharedCAStore, sharedCredentials), bye,+ contextClose, contextNew, credentialLoadX509,+ defaultParamsClient, defaultParamsServer, handshake,+ recvData, sendData)+import Network.TLS qualified as TLS (Credentials (Credentials))+import Streamly.Data.Array (Array)+import Streamly.Data.Fold (Fold, drainMapM)+import Streamly.Data.Stream (Stream, unfoldrM)+import Streamly.External.ByteString (fromArray, toArray)+import Streamly.External.Network.TCP (Transport (Transport, receive, send),+ connect)+import System.Timeout (timeout)+import System.X509 (getSystemCertificateStore)++-- | The authorities trusted to sign the certificate of the server.+data Certificates+ = -- | Those the system trusts.+ SystemCertificates+ | -- | Those of a file of certificates in PEM, or of a directory of such+ -- files, and no other. A server with a certificate of its own making+ -- is reached by giving that certificate here.+ CertificatesFrom FilePath+ deriving stock (Eq, Show)++-- | Where to connect, and whom to expect there.+data Config = Config+ { host :: String+ -- ^ A host name or an address, to connect to.+ , port :: Int+ , serverName :: String+ -- ^ The name the certificate of the server must be valid for; also+ -- sent to the server, which may hold several (server name indication).+ , certificates :: Certificates+ , connectTimeout :: Maybe Int+ -- ^ Microseconds allowed for the TCP connection and the TLS handshake+ -- together. 'Nothing' waits without end.+ }+ deriving stock (Eq, Show)++-- | A host and a port; the certificate must be valid for the host, and+-- signed by an authority the system trusts; thirty seconds to connect.+config :: String -> Int -> Config+config host port = Config {host, port, serverName = host, certificates = SystemCertificates, connectTimeout = Just 30_000_000}++-- | The connection was not ready within the time allowed: the server did+-- not accept it, or did not finish the TLS handshake.+data ConnectTimedOut = ConnectTimedOut+ deriving stock (Eq, Show)++instance Exception ConnectTimedOut++-- | An open connection, past its handshake: the TLS session, and what+-- frees the connection under it when this library opened it.+data Connection = Connection Context (IO ())++-- | Connect, do the TLS handshake and use the connection. When the+-- function returns, the server is told that nothing more comes, and the+-- connection is closed.+--+-- Throws 'TLS.TLSException' when the handshake fails, among others for a+-- certificate that is not accepted; t'ConnectTimedOut' when the connection+-- is not ready in time; and 'IOError' when the TCP connection fails or the+-- certificates cannot be read.+--+-- Once the connection is open nothing limits the waits: a caller that+-- needs it wraps @send@ and 'received' (the @limitTransport@ of+-- @streamly-http@ does, for the transports made of them).+withConnection :: Config -> (Connection -> IO a) -> IO a+withConnection settings use =+ -- The connection is opened unmasked, so that its time limit can stop+ -- it; open closes what it opened when it is stopped.+ mask $ \restore -> do+ connection <- restore (open settings)+ restore (use connection) `finally` close connection++-- | Connect and do the TLS handshake, for a connection that outlives a+-- function: 'close' it when it is no longer needed. Prefer+-- 'withConnection', which cannot forget to. Throws like 'withConnection'.+open :: Config -> IO Connection+open settings = do+ store <- trusted settings.certificates+ let defaults = defaultParamsClient settings.serverName ""+ parameters = defaults {clientShared = (clientShared defaults) {sharedCAStore = store}}+ within (ready parameters)+ where+ within action = case settings.connectTimeout of+ Nothing -> action+ Just microseconds -> timeout microseconds action >>= maybe (throwIO ConnectTimedOut) pure+ ready parameters =+ bracketOnError (connect settings.host settings.port) N.close $ \socket -> do+ context <- contextNew socket parameters+ handshake context+ pure (Connection context (contextClose context `finally` N.close socket))++-- | Tell the other side that nothing more comes, and free a connection+-- got from 'open'. Never throws; closing twice does no harm.+close :: Connection -> IO ()+close (Connection context release) = do+ -- The other side may already be gone.+ void (try @SomeException (bye context))+ void (try @SomeException release)++trusted :: Certificates -> IO CertificateStore+trusted = \case+ SystemCertificates -> getSystemCertificateStore+ CertificatesFrom path ->+ readCertificateStore path >>= maybe (throwIO (userError ("no certificate could be read from " <> path))) pure++-- | What a server proves its name with: a certificate and its private key.+newtype Credentials = Credentials Credential++-- | Read a certificate, with the certificates that sign it if any, and+-- its private key, from two files in PEM. Throws 'IOError' when they+-- cannot be read.+loadCredentials :: FilePath -> FilePath -> IO Credentials+loadCredentials certificateFile keyFile =+ credentialLoadX509 certificateFile keyFile+ >>= either (\problem -> throwIO (userError ("no credentials could be read from " <> certificateFile <> " and " <> keyFile <> ": " <> problem))) (pure . Credentials)++-- | Do the TLS handshake of a server on a connection it has accepted,+-- within a number of microseconds ('Nothing' waits without end), and use+-- the connection. When the function returns, the client is told that+-- nothing more comes. The socket stays open: closing it is up to the+-- caller.+--+-- Throws 'TLS.TLSException' when the handshake fails, t'ConnectTimedOut'+-- when it is not done in time, and 'IOError' when the connection fails.+acceptConnection :: Credentials -> Maybe Int -> Socket -> (Connection -> IO a) -> IO a+acceptConnection (Credentials credential) limit socket use =+ -- The handshake runs unmasked, so that its time limit can stop it.+ mask $ \restore -> do+ context <- contextNew socket parameters+ ( do+ restore (within (handshake context))+ value <- restore (use (Connection context (pure ())))+ -- The client may already be gone.+ void (try @IOException (bye context))+ pure value+ )+ `finally` contextClose context+ where+ shared = (serverShared defaultParamsServer) {sharedCredentials = TLS.Credentials [credential]}+ parameters = defaultParamsServer {serverShared = shared}+ within action = case limit of+ Nothing -> action+ Just microseconds -> timeout microseconds action >>= maybe (throwIO ConnectTimedOut) pure++-- | Send bytes. Throws 'TLS.TLSException' or 'IOError' when the+-- connection fails.+send :: MonadIO m => Connection -> Array Word8 -> m ()+send (Connection context _) bytes = sendData context (fromStrict (fromArray bytes))++-- | The connection as a transport, for the protocols written against+-- one: @streamly-http@ and @streamly-websockets@ take it as it is.+transport :: Connection -> Transport+transport connection = Transport {send = send connection, receive = received connection}++-- | Send each array.+write :: MonadIO m => Connection -> Fold m (Array Word8) ()+write connection = drainMapM (send connection)++-- | The bytes received, until the server ends the connection. Throws+-- like @send@, from the stream.+received :: MonadIO m => Connection -> Stream m (Array Word8)+received (Connection context _) = unfoldrM next ()+ where+ next () = do+ bytes <- recvData context+ pure (if BS.null bytes then Nothing else Just (toArray bytes, ()))
+ streamly-network-tls.cabal view
@@ -0,0 +1,87 @@+cabal-version: 3.12+name: streamly-network-tls+version: 0.1.0.0+synopsis: TLS connections as Streamly streams+description:+ TLS for Streamly, over the tls package, for clients and for servers: a+ connection whose received bytes are a stream of arrays, and whose sent+ bytes go through a function or a fold. A client checks the server+ against the certificates of the system, or against certificates of your+ own; a server presents its certificate. It knows nothing of the+ protocols carried: a connection gives a transport, for streamly-http+ (HTTPS), for streamly-websockets (secure WebSockets) or for anything+ else.++homepage: https://github.com/GuillaumedeVolpiano/streamly-network-tls+license: BSD-3-Clause+license-file: LICENSE+author: Xavier Dectot+maintainer: Xavier Dectot <xavier@wheredoibegin.fr>+category: Network, Streamly+build-type: Simple+tested-with: GHC ==9.8.4 || ==9.10.3 || ==9.12.4+extra-doc-files:+ CHANGELOG.md+ README.md++extra-source-files:+ test/fixtures/README.md+ test/fixtures/localhost-cert.pem+ test/fixtures/localhost-key.pem++source-repository head+ type: git+ location: https://github.com/GuillaumedeVolpiano/streamly-network-tls.git++common shared+ default-language: GHC2021+ default-extensions:+ DataKinds+ DerivingStrategies+ DisambiguateRecordFields+ DuplicateRecordFields+ ExplicitNamespaces+ GADTs+ LambdaCase+ MonoLocalBinds+ NoFieldSelectors+ OverloadedRecordDot+ OverloadedStrings+ RoleAnnotations++ ghc-options:+ -Wall -Wcompat -Wredundant-constraints -Wmissing-deriving-strategies+ -Wunused-packages++library+ import: shared+ hs-source-dirs: src+ exposed-modules: Streamly.External.Network.TLS+ build-depends:+ , base >=4.19 && <4.22+ , bytestring ^>=0.12+ , crypton-x509-store ^>=1.10+ , crypton-x509-system ^>=1.10+ , network ^>=3.2+ , streamly-bytestring ^>=0.2.3+ , streamly-core ^>=0.3.3+ , streamly-network-tcp ^>=0.1+ , tls ^>=2.5++test-suite streamly-network-tls-test+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Main.hs+ ghc-options: -threaded+ build-depends:+ , async ^>=2.2+ , base+ , bytestring+ , network+ , streamly-bytestring+ , streamly-core+ , streamly-network-tls+ , tasty ^>=1.5+ , tasty-hunit ^>=0.10+ , tls
+ test/Main.hs view
@@ -0,0 +1,205 @@+-- | 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
+ test/fixtures/README.md view
@@ -0,0 +1,9 @@+# Test fixtures++`localhost-cert.pem` and `localhost-key.pem` are a self-signed certificate+for `localhost` and `127.0.0.1` and its private key, made for the tests+only. The key is public: never trust this certificate outside the tests.++ openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \+ -keyout localhost-key.pem -out localhost-cert.pem -days 36500 \+ -subj "/CN=localhost" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"
+ test/fixtures/localhost-cert.pem view
@@ -0,0 +1,11 @@+-----BEGIN CERTIFICATE-----+MIIBmjCCAUGgAwIBAgIUdg7Rd8sr48g7SW0X2EYHEXIvSkQwCgYIKoZIzj0EAwIw+FDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTI2MTEyMTExMzMxOFoYDzIxMjYxMDI4+MTEzMzE4WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwWTATBgcqhkjOPQIBBggqhkjO+PQMBBwNCAAQoxQWuQQo8x5PONeY5nkaWCPodfLCAWt0TAlUqEDmfXBA+ByWPIe7a+7IhtRsl44ZPK7Enh2WFXSmxpYb4/KHJho28wbTAdBgNVHQ4EFgQUWXsJpAz5T19M+SThOH82fZnhYhagwHwYDVR0jBBgwFoAUWXsJpAz5T19MSThOH82fZnhYhagwDwYD+VR0TAQH/BAUwAwEB/zAaBgNVHREEEzARgglsb2NhbGhvc3SHBH8AAAEwCgYIKoZI+zj0EAwIDRwAwRAIgL9UZACUzIlfgKGTnKGhLgcADHyzctetDHpPMlAhzVoICICVs+QCus1LFcel/XEiKHMDD4hYWl/MG8OMHp3yIIp+w4+-----END CERTIFICATE-----
+ test/fixtures/localhost-key.pem view
@@ -0,0 +1,5 @@+-----BEGIN PRIVATE KEY-----+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgfIfnNfTky/BkemSQ+E/79aIBgcORX3HsDvYJaEioObmqhRANCAAQoxQWuQQo8x5PONeY5nkaWCPodfLCA+Wt0TAlUqEDmfXBA+ByWPIe7a7IhtRsl44ZPK7Enh2WFXSmxpYb4/KHJh+-----END PRIVATE KEY-----