-- | 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]
]