packages feed

streamly-http-tls (empty) → 0.1.0.0

raw patch · 9 files changed

+758/−0 lines, 9 filesdep +asyncdep +basedep +bytestring

Dependencies added: async, base, bytestring, network, streamly-bytestring, streamly-core, streamly-http, streamly-http-tls, streamly-network-tls, tasty, tasty-hunit, tls

Files

+ CHANGELOG.md view
@@ -0,0 +1,13 @@+# Revision history for streamly-http-tls++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* URLs fetched with the scheme choosing between TCP and TLS, redirects+  followed: `fetchUrl`, `withUrl`, and their variants with `Options`+  (certificates, limits of time and size, number of redirects, headers).+* One exchange in clear or over TLS (`withResponseAt`), and a session of+  streamly-http in clear or over TLS (`withSessionAt`).+* `withSecureClient`: a client of streamly-http that speaks in clear and+  over TLS; `fetchUrlIn` and `withUrlIn` fetch URLs through one, sharing+  its connections.
+ 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,67 @@+# streamly-http-tls++Fetch `http` and `https` URLs with+[Streamly](https://streamly.composewell.com/). This is the convenient face+of [streamly-http](https://hackage.haskell.org/package/streamly-http):+give a URL, get the response. The scheme chooses between plain TCP and TLS+(through+[streamly-network-tls](https://hackage.haskell.org/package/streamly-network-tls)),+and redirects are followed.++```haskell+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}++import Streamly.Data.Fold qualified as F (length)+import Streamly.Data.Stream (fold)+import Streamly.External.Network.HTTP (Response (..), header)+import Streamly.External.Network.HTTP.TLS (fetchUrl, withUrl)++main :: IO ()+main = do+  -- The whole response in memory.+  response <- fetchUrl "https://example.org/"+  print (response.status, header "content-type" response)++  -- The body as a stream, read while the connection is open.+  arrays <- withUrl "https://example.org/" $ \streamed ->+    fold F.length streamed.body+  print arrays+```++## What it does++- `fetchUrl` and `withUrl` send a `GET` request and follow the redirects+  (statuses 301, 302, 303, 307 and 308 with a `Location`), ten at most.+- `fetchUrlWith` and `withUrlWith` take `Options`: the certificates+  trusted for `https`, the limits of time and size, the number of+  redirects, and headers for every+  request. When a redirect leads to another host, `Authorization`,+  `Proxy-Authorization` and `Cookie` are left out.+- `withResponseAt` sends one request of any method, with any body, in+  clear or over TLS, without following redirects.+- `withSecureClient` keeps the connections to every server from one URL+  to the next: `fetchUrlIn` and `withUrlIn` fetch through it. Without a+  client, each call opens its connections and closes them; the redirects+  of one call to the same server still share one.+- `withSessionAt` keeps one connection to a server, in clear or over TLS,+  for several requests (`fetchIn` and `withResponseIn` of streamly-http):+  over TLS it spares a handshake for each request after the first.++## Limits of this version++- Those of streamly-http: no content coding decoded, a status is never an+  error.+- Each wait is limited, and so is the head of a response (`limits` in+  `Options`). The whole exchange is not: use `System.Timeout.timeout`. The+  body is not either by default: set `maxBodySize` when the server is not+  trusted.+- No proxy, no cookie jar.++## Building++To build against copies of+[streamly-http](https://hackage.haskell.org/package/streamly-http) and+[streamly-network-tls](https://hackage.haskell.org/package/streamly-network-tls)+checked out next to this repository, pass+`--project-file=cabal.project.siblings`.
+ src/Streamly/External/Network/HTTP/TLS.hs view
@@ -0,0 +1,237 @@+-- |+-- Module      : Streamly.External.Network.HTTP.TLS+-- Description : Fetching http and https URLs+-- License     : BSD-3-Clause+--+-- Give a URL, get the response: the scheme chooses between plain TCP and+-- TLS, and redirects are followed.+--+-- > {-# LANGUAGE OverloadedRecordDot #-}+-- > {-# LANGUAGE OverloadedStrings #-}+-- > import Streamly.External.Network.HTTP (Response (..), header)+-- > import Streamly.External.Network.HTTP.TLS (fetchUrl)+-- >+-- > main :: IO ()+-- > main = do+-- >   response <- fetchUrl "https://example.org/"+-- >   print (response.status, header "content-type" response)+--+-- As with @streamly-http@, a status is never an error. Each call opens+-- its connections and closes them; to keep them from one URL to the next,+-- see 'withSecureClient'. Each wait is limited, and so is the size of+-- the head of a response (see 'limits'); the whole time taken is not, nor+-- the size of a body unless a limit is set.+module Streamly.External.Network.HTTP.TLS+  ( -- * Fetching a URL+    fetchUrl+  , withUrl++    -- * Options+  , Options (..)+  , defaultOptions+  , fetchUrlWith+  , withUrlWith++    -- * One exchange+  , withResponseAt++    -- * Several requests over one connection+  , withSessionAt++    -- * Several URLs, their connections kept+  , withSecureClient+  , fetchUrlIn+  , withUrlIn++    -- * Errors+  , UrlError (..)+  ) where++import Control.Exception (Exception, throwIO, try)+import Data.ByteString (ByteString)+import Data.ByteString.Char8 qualified as BS8 (map)+import Data.Char (toLower)+import Data.Word (Word8)+import Streamly.Data.Array (Array, create, reader)+import Streamly.Data.Fold (drain)+import Streamly.Data.Stream (Stream, fold, unfoldEach)+import Streamly.Data.Stream qualified as S (take)+import Streamly.External.Network.HTTP (Client, Header,+                                       HttpError (ConnectTimedOut),+                                       Limits (connectTimeout),+                                       Request (host, port),+                                       Response (body, status), Session,+                                       connectWithin, defaultLimits, header,+                                       opened, withClientOver, withHeaders,+                                       withResponseFrom, withResponseOver,+                                       withResponseWithin, withSession,+                                       withSessionOver)+import Streamly.External.Network.HTTP.URL (Scheme (..),+                                           Url (host, port, scheme), parseUrl,+                                           renderUrl, resolve, urlRequest)+import Streamly.External.Network.HTTP.Wire (validateRequest)+import Streamly.External.Network.TLS (Certificates (SystemCertificates),+                                      Config (certificates, connectTimeout),+                                      close, config, open, transport,+                                      withConnection)+import Streamly.External.Network.TLS qualified as NT (ConnectTimedOut (ConnectTimedOut))++-- | How URLs are fetched.+data Options = Options+  { certificates :: Certificates+  -- ^ The authorities trusted to sign the certificates of @https@+  -- servers. Not looked at by 'fetchUrlIn' and 'withUrlIn', which have+  -- those of their client.+  , limits :: Limits+  -- ^ How long to wait for each connection and for each server to go on+  -- once connected, and how large a head and a body to accept. For+  -- @https@ the time to connect includes the TLS handshake.+  , maxRedirects :: Int+  -- ^ How many redirects are followed before giving up.+  , requestHeaders :: [Header]+  -- ^ Headers for every request. When a redirect leads to another host,+  -- @Authorization@, @Proxy-Authorization@ and @Cookie@ are left out.+  }+  deriving stock (Eq, Show)++-- | The certificates of the system, 'defaultLimits' (thirty seconds to+-- connect, thirty seconds of silence, a head of at most 64 KiB, a body of+-- any size), ten redirects, no header.+defaultOptions :: Options+defaultOptions = Options {certificates = SystemCertificates, limits = defaultLimits, maxRedirects = 10, requestHeaders = []}++-- | What can go wrong with a URL, besides what @streamly-http@ and+-- @streamly-network-tls@ throw.+data UrlError+  = -- | Not an @http@ or @https@ URL: the text, and why.+    InvalidUrl ByteString String+  | -- | More redirects than allowed: the limit, and the URL that was not+    -- fetched.+    TooManyRedirects Int ByteString+  | -- | A redirect to something that cannot be followed: the URL that+    -- redirected, and its @Location@.+    InvalidLocation ByteString ByteString+  deriving stock (Eq, Show)++instance Exception UrlError++-- | Fetch a URL with a @GET@ request, following redirects, and read the+-- whole response into memory.+--+-- Throws 'UrlError'; 'HttpError' for a response that cannot be read, and+-- for a server that takes too long to connect to (@ConnectTimedOut@) or+-- goes silent (@ResponseTimedOut@), or sends more than allowed+-- (@HeadTooLarge@, @BodyTooLarge@);+-- @TLSException@ (of the @tls@ package) when a TLS connection fails, among+-- others for a certificate that is not accepted; and 'IOError' when a+-- connection fails.+fetchUrl :: ByteString -> IO (Response (Array Word8))+fetchUrl = fetchUrlWith defaultOptions++-- | Like 'fetchUrl', with options.+fetchUrlWith :: Options -> ByteString -> IO (Response (Array Word8))+fetchUrlWith options text = withUrlWith options text whole++-- | Fetch a URL with a @GET@ request, following redirects, and use the+-- response while its connection is open: consume the body inside the+-- function, and only once. Throws like 'fetchUrl'.+withUrl :: ByteString -> (Response (Stream IO (Array Word8)) -> IO a) -> IO a+withUrl = withUrlWith defaultOptions++-- | Like 'withUrl', with options.+--+-- Responses with the status 301, 302, 303, 307 or 308 and a @Location@+-- are redirects; one without a @Location@ is given as it is. Redirects to+-- the same server go over the same connection.+withUrlWith :: Options -> ByteString -> (Response (Stream IO (Array Word8)) -> IO a) -> IO a+withUrlWith options text use =+  withSecureClient options.certificates options.limits (\client -> withUrlIn client options text use)++-- | Use a client that speaks in clear and over TLS: the requests sent+-- through it ('fetchUrlIn', 'withUrlIn', and @fetchFrom@ and+-- 'withResponseFrom' of @streamly-http@) reuse the connections it keeps+-- for each server, which over TLS spares a handshake each time. The+-- servers reached over TLS must present a certificate signed by one of+-- the authorities trusted. The connections kept are closed at the end.+withSecureClient :: Certificates -> Limits -> (Client -> IO a) -> IO a+withSecureClient trusted within = withClientOver within $ \scheme host port -> case scheme of+  Http -> connectWithin within.connectTimeout host port >>= opened+  Https -> do+    let settings = (config host port) {certificates = trusted, connectTimeout = within.connectTimeout}+    -- One error for a connection that is not ready in time, whatever the+    -- scheme.+    connection <- try (open settings) >>= either (\NT.ConnectTimedOut -> throwIO ConnectTimedOut) pure+    pure (transport connection, close connection)++-- | Like 'fetchUrlWith', through a client: several URLs fetched this way+-- share its connections. The certificates and the limits are those of the+-- client; those of the options are not looked at.+fetchUrlIn :: Client -> Options -> ByteString -> IO (Response (Array Word8))+fetchUrlIn client options text = withUrlIn client options text whole++-- | Like 'withUrlWith', through a client. See 'fetchUrlIn'.+withUrlIn :: Client -> Options -> ByteString -> (Response (Stream IO (Array Word8)) -> IO a) -> IO a+withUrlIn client options text use = do+  start <- either (throwIO . InvalidUrl text) pure (parseUrl text)+  follow start start 0+  where+    follow start current followed = do+      let request = withHeaders (headersFor start current) (urlRequest current)+      outcome <- withResponseFrom client current.scheme request $ \response ->+        case redirection response of+          Nothing -> Right <$> use response+          Just location -> do+            -- Read the body of the redirect, so that its connection can+            -- serve the next request; a long one is not worth it.+            fold drain (S.take 16 response.body)+            pure (Left location)+      case outcome of+        Right value -> pure value+        Left location -> do+          next <- either (const (throwIO (InvalidLocation (renderUrl current) location))) pure (resolve current location)+          if followed >= options.maxRedirects+            then throwIO (TooManyRedirects options.maxRedirects (renderUrl next))+            else follow start next (followed + 1 :: Int)+    redirection response+      | response.status `elem` [301, 302, 303, 307, 308] = header "location" response+      | otherwise = Nothing+    -- What identifies the caller stays with the server it was meant for.+    headersFor start current+      | (current.scheme, current.host, current.port) == (start.scheme, start.host, start.port) = options.requestHeaders+      | otherwise = filter (\(name, _) -> BS8.map toLower name `notElem` ["authorization", "proxy-authorization", "cookie"]) options.requestHeaders++whole :: Response (Stream IO (Array Word8)) -> IO (Response (Array Word8))+whole response = do+  bytes <- fold create (unfoldEach reader response.body)+  pure (bytes <$ response)++-- | Send one request to its host and port, in clear or over TLS, and use+-- the response while the connection is open. No redirect is followed.+-- This is @withResponse@ with the scheme as one more argument: it takes+-- any method and any body.+withResponseAt :: Certificates -> Limits -> Scheme -> Request -> (Response (Stream IO (Array Word8)) -> IO a) -> IO a+withResponseAt trusted within scheme request use = case scheme of+  Http -> withResponseWithin within request use+  Https -> do+    either throwIO pure (validateRequest request)+    let settings = (config request.host request.port) {certificates = trusted, connectTimeout = within.connectTimeout}+    connected <- try (withConnection settings (\connection -> withResponseOver within (transport connection) request use))+    -- One error for a connection that is not ready in time, whatever the+    -- scheme.+    either (\NT.ConnectTimedOut -> throwIO ConnectTimedOut) pure connected++-- | Use a session with a host and a port, in clear or over TLS: its+-- requests (@withResponseIn@, @fetchIn@) reuse one connection when they+-- can. No redirect is followed. For TLS, the time to connect covers the+-- handshake, done again each time the connection has to be opened anew.+withSessionAt :: Certificates -> Limits -> Scheme -> String -> Int -> (Session -> IO a) -> IO a+withSessionAt trusted within scheme host port use = case scheme of+  Http -> withSession within host port use+  Https -> withSessionOver within secure use+  where+    settings = (config host port) {certificates = trusted, connectTimeout = within.connectTimeout}+    secure = do+      -- One error for a connection that is not ready in time, whatever+      -- the scheme.+      connection <- try (open settings) >>= either (\NT.ConnectTimedOut -> throwIO ConnectTimedOut) pure+      pure (transport connection, close connection)
+ streamly-http-tls.cabal view
@@ -0,0 +1,80 @@+cabal-version:   3.12+name:            streamly-http-tls+version:         0.1.0.0+synopsis:        Fetch http and https URLs with Streamly+description:+  The convenient face of streamly-http: give a URL, get the response. The+  scheme chooses between plain TCP and TLS (through streamly-network-tls),+  and redirects are followed.++homepage:        https://github.com/GuillaumedeVolpiano/streamly-http-tls+license:         BSD-3-Clause+license-file:    LICENSE+author:          Xavier Dectot+maintainer:      Xavier Dectot <xavier@wheredoibegin.fr>+category:        Network, Web, 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-http-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.HTTP.TLS+  build-depends:+    , base                  >=4.19 && <4.22+    , bytestring            ^>=0.12+    , streamly-core         ^>=0.3.3+    , streamly-http         ^>=0.1+    , streamly-network-tls  ^>=0.1++test-suite streamly-http-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               ^>=3.2+    , streamly-bytestring   ^>=0.2.3+    , streamly-core+    , streamly-http+    , streamly-http-tls+    , streamly-network-tls+    , tasty                 ^>=1.5+    , tasty-hunit           ^>=0.10+    , tls                   ^>=2.5
+ test/Main.hs view
@@ -0,0 +1,307 @@+-- | Fetching URLs from two servers on the loopback interface: one in+-- clear, one over TLS with the certificate of the fixtures.+module Main (main) where++import Control.Concurrent.Async (withAsync)+import Control.Exception (IOException, bracket, catch, try)+import Control.Monad (forever, void)+import Data.ByteString (ByteString, breakSubstring, isInfixOf)+import Data.ByteString qualified as BS (concat, drop, length, null, takeWhile)+import Data.ByteString.Char8 (dropSpace, pack, readInt)+import Data.ByteString.Char8 qualified as BS8 (takeWhile)+import Data.ByteString.Lazy (fromStrict)+import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef)+import Network.Socket (Family (AF_INET), SockAddr (SockAddrInet),+                       SocketOption (ReuseAddr), SocketType (Stream), accept,+                       bind, close, defaultProtocol, listen, setSocketOption,+                       socket, socketPort, tupleToHostAddress)+import Network.Socket.ByteString (recv, sendAll)+import Network.TLS (Credentials (Credentials), ServerParams (serverShared),+                    Shared (sharedCredentials), TLSException (HandshakeFailed),+                    bye, contextClose, contextNew, credentialLoadX509,+                    defaultParamsServer, handshake, recvData, sendData)+import Streamly.Data.Stream (toList)+import Streamly.External.ByteString (fromArray)+import Streamly.External.Network.HTTP (HttpError (..), Limits (..),+                                       Request (..), RequestBody (..),+                                       Response (..), defaultLimits, fetchIn,+                                       get, header, withBody)+import Streamly.External.Network.HTTP.TLS (Options (certificates, limits, maxRedirects, requestHeaders),+                                           UrlError (InvalidLocation, InvalidUrl, TooManyRedirects),+                                           defaultOptions, fetchUrl, fetchUrlIn,+                                           fetchUrlWith, withResponseAt,+                                           withSecureClient, withSessionAt,+                                           withUrlWith)+import Streamly.External.Network.HTTP.URL (Scheme (..))+import Streamly.External.Network.TLS (Certificates (..))+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 ports of the two servers, and the requests they received, the+-- latest first: which server, then the bytes.+data Servers = Servers+  { plain :: Int+  , secure :: Int+  , requests :: IORef [(Scheme, ByteString)]+  }++-- | Run a server in clear and a server over TLS that answer every+-- connection with a function of the ports and of the request.+withServers :: (Servers -> ByteString -> ByteString) -> (Servers -> IO a) -> IO a+withServers answer run = do+  credential <- credentialLoadX509 certificateFile keyFile >>= either fail pure+  let shared = (serverShared defaultParamsServer) {sharedCredentials = Credentials [credential]}+      parameters = defaultParamsServer {serverShared = shared}+  seen <- newIORef []+  bracket listening close $ \plainListener ->+    bracket listening close $ \secureListener -> do+      servers <- Servers <$> portOf plainListener <*> portOf secureListener <*> pure seen+      let record scheme request = atomicModifyIORef' seen (\earlier -> ((scheme, request) : earlier, ()))+          servePlain = forever . bracket (fst <$> accept plainListener) close $ \peer -> do+            request <- readHead (recv peer 4096) ""+            record Http request+            sendAll peer (answer servers request)+          serveSecure = forever . bracket (fst <$> accept secureListener) close $ \peer ->+            -- A client that refuses the certificate ends the handshake.+            -- Only these failures are passed over: catching everything+            -- would swallow the cancellation that stops the server.+            quietly . bracket (contextNew peer parameters) contextClose $ \context -> do+              handshake context+              request <- readHead (recvData context) ""+              record Https request+              sendData context (fromStrict (answer servers request))+              bye context+      withAsync servePlain $ \_ -> withAsync serveSecure $ \_ -> run servers+  where+    listening = do+      listener <- socket AF_INET Stream defaultProtocol+      setSocketOption listener ReuseAddr 1+      bind listener (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+      listen listener 5+      pure listener+    portOf listener = fromIntegral <$> socketPort listener+    quietly action = action `catch` (\(_ :: TLSException) -> pure ()) `catch` (\(_ :: IOException) -> pure ())+    -- Read a request with its body, so that nothing is left unread when+    -- the connection is closed: the system would reset it.+    readHead receive seen+      | complete seen = pure seen+      | otherwise = do+          more <- receive+          if BS.null more then pure seen else readHead receive (seen <> more)+    complete seen =+      let (requestHead, rest) = breakSubstring "\r\n\r\n" seen+          announced = readInt (dropSpace (BS.drop 15 (snd (breakSubstring "Content-Length:" requestHead))))+       in not (BS.null rest) && BS.length rest - 4 >= maybe 0 fst announced++-- | Run a server over TLS that keeps its connections: on each, it answers+-- request after request with a function of the request. Gives its port+-- and the count of the TLS handshakes it has done.+withKeepingSecureServer :: (ByteString -> ByteString) -> (Int -> IORef Int -> IO a) -> IO a+withKeepingSecureServer answer run = do+  credential <- credentialLoadX509 certificateFile keyFile >>= either fail pure+  let shared = (serverShared defaultParamsServer) {sharedCredentials = Credentials [credential]}+      parameters = defaultParamsServer {serverShared = shared}+  handshakes <- newIORef (0 :: Int)+  bracket (socket AF_INET Stream defaultProtocol) close $ \listener -> do+    bind listener (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+    listen listener 5+    securePort <- fromIntegral <$> socketPort listener+    let answerAll context buffered = case breakSubstring "\r\n\r\n" buffered of+          (found, rest) | not (BS.null rest) -> do+            sendData context (fromStrict (answer found))+            answerAll context (BS.drop 4 rest)+          _ -> do+            more <- recvData context+            if BS.null more then pure () else answerAll context (buffered <> more)+        serve = forever . bracket (fst <$> accept listener) close $ \peer ->+          ( bracket (contextNew peer parameters) contextClose $ \context -> do+              handshake context+              atomicModifyIORef' handshakes (\count -> (count + 1, ()))+              answerAll context ""+          )+            `catch` (\(_ :: TLSException) -> pure ())+            `catch` (\(_ :: IOException) -> pure ())+    withAsync serve $ \_ -> run securePort handshakes++-- | The first line of each request received, the earliest first.+requestLines :: Servers -> IO [(Scheme, ByteString)]+requestLines servers = reverse . map (fmap (BS.takeWhile (/= 13))) <$> readIORef servers.requests++ok :: ByteString -> ByteString+ok content = "HTTP/1.1 200 OK\r\nContent-Length: " <> pack (show (BS.length content)) <> "\r\n\r\n" <> content++redirect :: ByteString -> ByteString -> ByteString+redirect status location = "HTTP/1.1 " <> status <> " Moved\r\nLocation: " <> location <> "\r\nContent-Length: 5\r\n\r\nmoved"++targetOf :: ByteString -> ByteString+targetOf request = BS8.takeWhile (/= ' ') (BS.drop 4 request)++port :: Int -> ByteString+port = pack . show++-- | Options that trust the certificate of the fixtures.+local :: Options+local = defaultOptions {certificates = CertificatesFrom certificateFile}++bodyOf :: Response a -> (a -> ByteString) -> (Int, ByteString)+bodyOf response convert = (response.status, convert response.body)++tests :: TestTree+tests =+  localOption (mkTimeout 20_000_000) $+    testGroup+      "streamly-http-tls"+      [ testCase "an http URL goes in clear" $+          withServers (\_ request -> ok ("clear " <> targetOf request)) $ \servers -> do+            response <- fetchUrl ("http://127.0.0.1:" <> port servers.plain <> "/a?b=c")+            bodyOf response fromArray @?= (200, "clear /a?b=c")+            requestLines servers >>= (@?= [(Http, "GET /a?b=c HTTP/1.1")])+      , testCase "an https URL goes over TLS" $+          withServers (\_ request -> ok ("secure " <> targetOf request)) $ \servers -> do+            response <- fetchUrlWith local ("https://localhost:" <> port servers.secure <> "/a")+            bodyOf response fromArray @?= (200, "secure /a")+            requestLines servers >>= (@?= [(Https, "GET /a HTTP/1.1")])+      , testCase "an https server the system does not know is refused" $+          withServers (\_ _ -> ok "never sent") $ \servers ->+            try (fetchUrl ("https://localhost:" <> port servers.secure <> "/")) >>= \case+              Left (HandshakeFailed _) -> pure ()+              Left other -> assertFailure ("expected HandshakeFailed, got " <> show other)+              Right _ -> assertFailure "the certificate was accepted"+      , testCase "the body is a stream inside withUrl" $+          withServers (\_ _ -> "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n2\r\nde\r\n0\r\n\r\n") $ \servers -> do+            arrays <- withUrlWith local ("https://localhost:" <> port servers.secure <> "/") $ \response ->+              map fromArray <$> toList response.body+            BS.concat arrays @?= "abcde"+      , testCase "redirects are followed: to another scheme, to a path, to a relative reference" $ do+          let answer servers request = case targetOf request of+                "/start" -> redirect "302" ("https://localhost:" <> port servers.secure <> "/over/tls")+                "/over/tls" -> redirect "301" "/a/b/c"+                "/a/b/c" -> redirect "307" "../d?e=f#g"+                "/a/d?e=f" -> redirect "308" ("//localhost:" <> port servers.secure <> "/back")+                "/back" -> redirect "303" "end"+                other -> ok ("arrived at " <> other)+          withServers answer $ \servers -> do+            response <- fetchUrlWith local ("http://127.0.0.1:" <> port servers.plain <> "/start")+            bodyOf response fromArray @?= (200, "arrived at /end")+            requestLines servers+              >>= ( @?=+                      [ (Http, "GET /start HTTP/1.1")+                      , (Https, "GET /over/tls HTTP/1.1")+                      , (Https, "GET /a/b/c HTTP/1.1")+                      , (Https, "GET /a/d?e=f HTTP/1.1")+                      , (Https, "GET /back HTTP/1.1")+                      , (Https, "GET /end HTTP/1.1")+                      ]+                  )+      , testCase "no more redirects than allowed" $ do+          let answer _ request = redirect "302" (targetOf request <> "x")+          withServers answer $ \servers -> do+            let start = "http://127.0.0.1:" <> port servers.plain <> "/"+            outcome <- try (fetchUrlWith local {maxRedirects = 3} start)+            outcome @?= Left (TooManyRedirects 3 (start <> "xxxx"))+            length <$> readIORef servers.requests >>= (@?= 4)+            none <- try (fetchUrlWith local {maxRedirects = 0} start)+            none @?= Left (TooManyRedirects 0 (start <> "x"))+      , testCase "a redirect without a Location, and other statuses, are given as they are" $ do+          let answer _ request = case targetOf request of+                "/nowhere" -> "HTTP/1.1 302 Found\r\nContent-Length: 0\r\n\r\n"+                "/unchanged" -> "HTTP/1.1 304 Not Modified\r\nLocation: /elsewhere\r\n\r\n"+                _ -> "HTTP/1.1 404 Not Found\r\nContent-Length: 4\r\n\r\ngone"+          withServers answer $ \servers -> do+            let at path = fetchUrl ("http://127.0.0.1:" <> port servers.plain <> path)+            nowhere <- at "/nowhere"+            unchanged <- at "/unchanged"+            missing <- at "/missing"+            (nowhere.status, unchanged.status, bodyOf missing fromArray) @?= (302, 304, (404, "gone"))+      , testCase "a Location that cannot be followed" $ do+          withServers (\_ _ -> redirect "302" "ftp://example.org/file") $ \servers -> do+            let start = "http://127.0.0.1:" <> port servers.plain <> "/"+            outcome <- try (fetchUrl start)+            outcome @?= Left (InvalidLocation start "ftp://example.org/file")+      , testCase "headers go with every request, but credentials stay with their server" $ do+          let answer servers request = case targetOf request of+                "/start" -> redirect "302" "/same"+                "/same" -> redirect "302" ("http://localhost:" <> port servers.plain <> "/other")+                _ -> ok "done"+              options = local {requestHeaders = [("Accept", "text/plain"), ("Authorization", "Bearer secret"), ("cookie", "a=b")]}+              has name request = (name <> ":") `isInfixOf` request+          withServers answer $ \servers -> do+            void (fetchUrlWith options ("http://127.0.0.1:" <> port servers.plain <> "/start"))+            received <- reverse . map snd <$> readIORef servers.requests+            map (has "Accept") received @?= [True, True, True]+            map (has "Authorization") received @?= [True, True, False]+            map (has "cookie") received @?= [True, True, False]+      , testCase "what is not an http or https URL" $ do+          let refused text =+                try (fetchUrl text) >>= \case+                  Left (InvalidUrl found _) -> found @?= text+                  Left other -> assertFailure ("expected InvalidUrl, got " <> show other)+                  Right _ -> assertFailure "no error, expected InvalidUrl"+          mapM_ refused ["", "example.org", "ftp://example.org/", "http://user@example.org/", "http://example.org/a b"]+      , testCase "one exchange with any method and body, over TLS" $+          withServers (\_ request -> ok (BS.takeWhile (/= 13) request)) $ \servers -> do+            let request = withBody (BodyBytes "hello") (get "localhost" servers.secure "/submit") {method = "POST"}+            answer <- withResponseAt (CertificatesFrom certificateFile) defaultLimits Https request $ \response ->+              BS.concat . map fromArray <$> toList response.body+            answer @?= "POST /submit HTTP/1.1"+            sent <- readIORef servers.requests+            map (isInfixOf "Content-Length: 5" . snd) sent @?= [True]+      , testCase "an https URL on a port that speaks in clear gives up in time" $+          -- The server in clear waits for the end of a request while the+          -- client waits for the TLS handshake.+          withServers (\_ _ -> ok "never sent") $ \servers -> do+            let hurried = local {limits = defaultLimits {connectTimeout = Just 200_000, idleTimeout = Just 200_000}}+            outcome <- try (fetchUrlWith hurried ("https://localhost:" <> port servers.plain <> "/"))+            outcome @?= Left ConnectTimedOut+      , testCase "the sizes allowed apply in clear and over TLS" $+          withServers (\_ _ -> ok "0123456789") $ \servers -> do+            let small = local {limits = defaultLimits {maxBodySize = Just 9}}+            clear <- try (fetchUrlWith small ("http://127.0.0.1:" <> port servers.plain <> "/"))+            fmap (.status) clear @?= Left (BodyTooLarge 9)+            overTls <- try (fetchUrlWith small ("https://localhost:" <> port servers.secure <> "/"))+            fmap (.status) overTls @?= Left (BodyTooLarge 9)+            fits <- fetchUrlWith local {limits = defaultLimits {maxBodySize = Just 10}} ("https://localhost:" <> port servers.secure <> "/")+            bodyOf fits fromArray @?= (200, "0123456789")+      , testCase "a session over TLS shares one connection, and one handshake" $+          withKeepingSecureServer (ok . targetOf) $ \securePort handshakes -> do+            answers <- withSessionAt (CertificatesFrom certificateFile) defaultLimits Https "localhost" securePort $ \session ->+              mapM (\target -> fetchIn session (get "localhost" securePort target)) ["/a", "/b", "/c"]+            map (\response -> fromArray response.body) answers @?= ["/a", "/b", "/c"]+            readIORef handshakes >>= (@?= 1)+      , testCase "the redirects of a URL to its own server go over one connection" $ do+          let answer request = case targetOf request of+                "/start" -> redirect "302" "/middle"+                "/middle" -> redirect "301" "end"+                other -> ok ("arrived at " <> other)+          withKeepingSecureServer answer $ \securePort handshakes -> do+            response <- fetchUrlWith local ("https://localhost:" <> port securePort <> "/start")+            bodyOf response fromArray @?= (200, "arrived at /end")+            readIORef handshakes >>= (@?= 1)+      , testCase "URLs fetched through one client share its connections" $+          withKeepingSecureServer (ok . targetOf) $ \securePort handshakes -> do+            answers <- withSecureClient (CertificatesFrom certificateFile) defaultLimits $ \client ->+              mapM (\path -> fetchUrlIn client defaultOptions ("https://localhost:" <> port securePort <> path)) ["/a", "/b", "/c"]+            map (\response -> fromArray response.body) answers @?= ["/a", "/b", "/c"]+            readIORef handshakes >>= (@?= 1)+            -- Without a client, each URL has its own.+            mapM_ (\path -> fetchUrlWith local ("https://localhost:" <> port securePort <> path)) ["/d", "/e"]+            readIORef handshakes >>= (@?= 3)+      , testCase "a session in clear goes through the sessions of streamly-http" $+          withServers (\_ request -> ok (targetOf request)) $ \servers -> do+            answer <- withSessionAt SystemCertificates defaultLimits Http "127.0.0.1" servers.plain $ \session ->+              fetchIn session (get "127.0.0.1" servers.plain "/clear")+            fromArray answer.body @?= "/clear"+      , testCase "the Host header names the server of each URL" $+          withServers (\_ _ -> ok "") $ \servers -> do+            response <- fetchUrlWith local ("https://localhost:" <> port servers.secure <> "/")+            header "content-length" response @?= Just "0"+            sent <- readIORef servers.requests+            map (isInfixOf ("Host: localhost:" <> port servers.secure <> "\r\n") . snd) sent @?= [True]+      ]
+ 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-----