packages feed

effectful-streamly-http-tls (empty) → 0.1.0.0

raw patch · 9 files changed

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

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

Files

+ CHANGELOG.md view
@@ -0,0 +1,8 @@+# Revision history for effectful-streamly-http-tls++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* `Effectful.HTTP.TLS`: `runHttp`, an interpreter of the `Http` effect of+  effectful-streamly-http in clear and over TLS, which keeps its+  connections, for each server, as long as it runs.
+ 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,42 @@+# effectful-streamly-http-tls++An interpreter for the HTTP effect of+[effectful-streamly-http](https://hackage.haskell.org/package/effectful-streamly-http)+that speaks in clear and over TLS, through+[streamly-http-tls](https://hackage.haskell.org/package/streamly-http-tls).+It is a package apart so that programs that only speak in clear need not+build a TLS stack.++```haskell+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}++import Effectful (runEff)+import Effectful.Error.Static (runErrorNoCallStack)+import Effectful.HTTP (HttpFailure, Response (..), Scheme (Https), defaultLimits,+                       fetch, get)+import Effectful.HTTP.TLS (Certificates (SystemCertificates), runHttp)++main :: IO ()+main = do+  outcome <- runEff . runErrorNoCallStack @HttpFailure . runHttp SystemCertificates defaultLimits $+    fetch Https (get "example.org" 443 "/")+  print (fmap (.status) outcome)+```++`runHttp` takes the authorities trusted to sign the certificates of the+servers (`SystemCertificates`, or `CertificatesFrom` a file in PEM) and the+limits of time and size. A certificate that is not accepted is a+`TlsFailed`. The connections are kept from one request to the next for+each server as long as the interpreter runs, which over TLS spares a+handshake each time.++## Building++To build against copies of the libraries this package is built on+([effectful-streamly-http](https://hackage.haskell.org/package/effectful-streamly-http),+[streamly-http-tls](https://hackage.haskell.org/package/streamly-http-tls)+and those under them) checked out next to this repository, pass+`--project-file=cabal.project.siblings`.++Tested with GHC 9.8.4, 9.10.3 and 9.12.4, and effectful 2.7.1.
+ effectful-streamly-http-tls.cabal view
@@ -0,0 +1,85 @@+cabal-version:   3.12+name:            effectful-streamly-http-tls+version:         0.1.0.0+synopsis:        The HTTP effect of effectful-streamly-http, over TLS too+description:+  An interpreter for the HTTP effect of effectful-streamly-http that+  speaks in clear and over TLS, through streamly-http-tls. It is apart so+  that programs that only speak in clear need not build a TLS stack.++homepage:        https://github.com/GuillaumedeVolpiano/effectful-streamly-http-tls+license:         BSD-3-Clause+license-file:    LICENSE+author:          Xavier Dectot+maintainer:      Xavier Dectot <xavier@wheredoibegin.fr>+category:        Network, Web, Control+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/effectful-streamly-http-tls.git++common shared+  default-language:   GHC2021+  default-extensions:+    DataKinds+    DerivingStrategies+    DisambiguateRecordFields+    DuplicateRecordFields+    ExplicitNamespaces+    GADTs+    LambdaCase+    MonoLocalBinds+    NoFieldSelectors+    OverloadedRecordDot+    OverloadedStrings+    RoleAnnotations+    TypeFamilies++  ghc-options:+    -Wall -Wcompat -Wredundant-constraints -Wmissing-deriving-strategies+    -Wunused-packages++library+  import:          shared+  hs-source-dirs:  src+  exposed-modules: Effectful.HTTP.TLS+  build-depends:+    , base                     >=4.19 && <4.22+    , bytestring               ^>=0.12+    , effectful-core           ^>=2.7.1+    , effectful-streamly-http  ^>=0.1+    , streamly-bytestring      ^>=0.2.3+    , streamly-core            ^>=0.3.3+    , streamly-http            ^>=0.1+    , streamly-http-tls        ^>=0.1+    , streamly-network-tls     ^>=0.1+    , text                     ^>=2.1+    , tls                      ^>=2.5++test-suite effectful-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+    , effectful-core+    , effectful-streamly-http+    , effectful-streamly-http-tls+    , network                      ^>=3.2+    , tasty                        ^>=1.5+    , tasty-hunit                  ^>=0.10+    , tls
+ src/Effectful/HTTP/TLS.hs view
@@ -0,0 +1,66 @@+-- |+-- Module      : Effectful.HTTP.TLS+-- Description : The HTTP effect, in clear and over TLS+-- License     : BSD-3-Clause+--+-- An interpreter for the effect of "Effectful.HTTP" that speaks in clear+-- and over TLS.+--+-- > {-# LANGUAGE OverloadedRecordDot #-}+-- > {-# LANGUAGE OverloadedStrings #-}+-- > import Effectful (runEff)+-- > import Effectful.Error.Static (runErrorNoCallStack)+-- > import Effectful.HTTP (HttpFailure, Response (..), Scheme (Https), defaultLimits,+-- >                        fetch, get)+-- > import Effectful.HTTP.TLS (Certificates (SystemCertificates), runHttp)+-- >+-- > main :: IO ()+-- > main = do+-- >   outcome <- runEff . runErrorNoCallStack @HttpFailure . runHttp SystemCertificates defaultLimits $+-- >     fetch Https (get "example.org" 443 "/")+-- >   print (fmap (.status) outcome)+module Effectful.HTTP.TLS+  ( runHttp+  , Certificates (..)+  ) where++import Control.Exception (IOException, displayException, try)+import Data.ByteString qualified as BS (concat)+import Data.Text (pack)+import Effectful (Eff, IOE, MonadIO (liftIO), UnliftStrategy (SeqUnlift),+                  withEffToIO, type (:>))+import Effectful.Dispatch.Dynamic (interpret_)+import Effectful.Error.Static (Error, throwError)+import Effectful.HTTP (Http (..), HttpError, HttpFailure (..), Limits,+                       Response (..))+import Network.TLS (TLSException)+import Streamly.Data.Stream (toList)+import Streamly.External.ByteString (fromArray)+import Streamly.External.Network.HTTP (Client, withResponseFrom)+import Streamly.External.Network.HTTP.TLS (withSecureClient)+import Streamly.External.Network.TLS (Certificates (..))++-- | Interpret the effect over connections in clear and over TLS, within+-- limits of time and size. The connections are kept from one request to+-- the next for each server, as long as the interpreter runs, which over+-- TLS spares a handshake each time; they are closed when it is done. The+-- servers reached over TLS must present a certificate signed by one of+-- the authorities trusted; for them the time to connect includes the TLS+-- handshake.+runHttp :: (IOE :> es, Error HttpFailure :> es) => Certificates -> Limits -> Eff (Http : es) a -> Eff es a+runHttp trusted limits action =+  withEffToIO SeqUnlift $ \runInIO ->+    withSecureClient trusted limits (\client -> runInIO (through client action))++through :: (IOE :> es, Error HttpFailure :> es) => Client -> Eff (Http : es) a -> Eff es a+through client = interpret_ $ \case+  Fetch scheme request ->+    liftIO (try (try (try (withResponseFrom client scheme request whole)))) >>= \case+      Left (problem :: IOException) -> throwError (ConnectFailed (pack (displayException problem)))+      Right (Left (problem :: TLSException)) -> throwError (TlsFailed (pack (displayException problem)))+      Right (Right (Left (problem :: HttpError))) -> throwError (RequestFailed problem)+      Right (Right (Right response)) -> pure response+  where+    whole response = do+      arrays <- toList response.body+      pure (BS.concat (map fromArray arrays) <$ response)
+ test/Main.hs view
@@ -0,0 +1,123 @@+-- | The interpreter against 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)+import Control.Monad (forever)+import Data.ByteString (ByteString, isInfixOf, pack)+import Data.ByteString qualified as BS (length, null, takeWhile)+import Data.ByteString.Lazy (fromStrict)+import Effectful (Eff, IOE, runEff)+import Effectful.Error.Static (Error, runErrorNoCallStack)+import Effectful.HTTP (Http, HttpError (BodyTooLarge, ConnectTimedOut),+                       HttpFailure (ConnectFailed, RequestFailed, TlsFailed),+                       Limits (connectTimeout, maxBodySize),+                       Response (body, status), Scheme (Http, Https),+                       defaultLimits, fetch, get)+import Effectful.HTTP.TLS (Certificates (..), runHttp)+import Network.Socket (Family (AF_INET), SockAddr (SockAddrInet),+                       SocketOption (ReuseAddr), SocketType (Stream), accept,+                       bind, close, defaultProtocol, listen, setSocketOption,+                       socketPort, tupleToHostAddress)+import Network.Socket qualified as N (socket)+import Network.Socket.ByteString (recv, sendAll)+import Network.TLS (Credentials (Credentials), ServerParams (serverShared),+                    Shared (sharedCredentials), TLSException, bye, contextClose,+                    contextNew, credentialLoadX509, defaultParamsServer,+                    handshake, recvData, sendData)+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"++-- | Run a server in clear and a server over TLS that answer every+-- connection with a function of the first line of the request. Gives+-- their ports.+withServers :: (ByteString -> ByteString) -> (Int -> Int -> 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}+  bracket listening close $ \plainListener ->+    bracket listening close $ \secureListener -> do+      plainPort <- fromIntegral <$> socketPort plainListener+      securePort <- fromIntegral <$> socketPort secureListener+      let servePlain = forever . bracket (fst <$> accept plainListener) close $ \peer -> do+            request <- readHead (recv peer 4096) ""+            sendAll peer (answer (BS.takeWhile (/= 13) 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) ""+              sendData context (fromStrict (answer (BS.takeWhile (/= 13) request)))+              bye context+      withAsync servePlain $ \_ -> withAsync serveSecure $ \_ -> run plainPort securePort+  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 5+      pure listener+    quietly action = action `catch` (\(_ :: TLSException) -> pure ()) `catch` (\(_ :: IOException) -> pure ())+    readHead receive seen+      | "\r\n\r\n" `isInfixOf` seen = pure seen+      | otherwise = do+          more <- receive+          if BS.null more then pure seen else readHead receive (seen <> more)++echoing :: ByteString -> ByteString+echoing line = "HTTP/1.1 200 OK\r\nContent-Length: " <> lengthOf line <> "\r\n\r\n" <> line+  where+    lengthOf = pack . map (fromIntegral . fromEnum) . show . BS.length++with :: Certificates -> Limits -> Eff '[Http, Error HttpFailure, IOE] a -> IO (Either HttpFailure a)+with trusted limits = runEff . runErrorNoCallStack . runHttp trusted limits++local :: Certificates+local = CertificatesFrom certificateFile++tests :: TestTree+tests =+  localOption (mkTimeout 20_000_000) $+    testGroup+      "effectful-streamly-http-tls"+      [ testCase "requests go in clear and over TLS, as each asks" $+          withServers echoing $ \plainPort securePort -> do+            outcome <- with local defaultLimits $ do+              inClear <- fetch Http (get "127.0.0.1" plainPort "/clear")+              overTls <- fetch Https (get "localhost" securePort "/secure")+              pure (inClear.body, overTls.body)+            outcome @?= Right ("GET /clear HTTP/1.1", "GET /secure HTTP/1.1")+      , testCase "a certificate signed by nobody the system trusts is a TLS failure" $+          withServers echoing $ \_ securePort -> do+            outcome <- with SystemCertificates defaultLimits (fetch Https (get "localhost" securePort "/"))+            case outcome of+              Left (TlsFailed _) -> pure ()+              other -> assertFailure ("expected TlsFailed, got " <> show (fmap (.status) other))+      , testCase "the limits apply over TLS" $+          withServers echoing $ \plainPort securePort -> do+            tooLarge <- with local defaultLimits {maxBodySize = Just 5} (fetch Https (get "localhost" securePort "/"))+            fmap (.status) tooLarge @?= Left (RequestFailed (BodyTooLarge 5))+            -- The server in clear waits for the end of a request while+            -- the client waits for the TLS handshake.+            stuck <- with local defaultLimits {connectTimeout = Just 200_000} (fetch Https (get "localhost" plainPort "/"))+            fmap (.status) stuck @?= Left (RequestFailed ConnectTimedOut)+      , testCase "a refused connection is reported" $ do+          port <- bracket (N.socket AF_INET Stream defaultProtocol) close $ \socket -> do+            bind socket (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+            fromIntegral <$> socketPort socket+          outcome <- with local defaultLimits (fetch Https (get "localhost" port "/"))+          case outcome of+            Left (ConnectFailed _) -> pure ()+            other -> assertFailure ("expected ConnectFailed, got " <> show (fmap (.status) other))+      ]
+ 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-----