packages feed

effectful-websockets-tls (empty) → 0.1.0.0

raw patch · 9 files changed

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

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

Files

+ CHANGELOG.md view
@@ -0,0 +1,8 @@+# Revision history for effectful-websockets-tls++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* `Effectful.WebSocket.Client.TLS`: `runWebSocketSecure`, over TLS;+  `runWebSocketAt`, in clear or over TLS as a scheme says; and+  `urlClientConfig`, for a `ws` or `wss` URL.
+ 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,48 @@+# effectful-websockets-tls++Interpreters for the WebSocket effect of+[effectful-websockets](https://hackage.haskell.org/package/effectful-websockets)+that open secure WebSockets, through+[streamly-websockets-tls](https://hackage.haskell.org/package/streamly-websockets-tls).+A package apart, so that programs that only speak in clear need not build+a TLS stack.++```haskell+{-# LANGUAGE OverloadedStrings #-}++import Effectful (runEff)+import Effectful.Error.Static (runErrorNoCallStack)+import Effectful.WebSocket (Message, receiveMessage, sendText)+import Effectful.WebSocket.Client (WebSocketError, clientConfig)+import Effectful.WebSocket.Client.TLS (Certificates (SystemCertificates),+                                       runWebSocketSecure)++hello :: IO (Either WebSocketError (Maybe Message))+hello = runEff . runErrorNoCallStack . runWebSocketSecure SystemCertificates (clientConfig "example.org" 443 "/chat") $ do+  _ <- sendText "hello"+  receiveMessage+```++## What it gives++- `runWebSocketSecure`: the connection over TLS, the server checked+  against the certificates of the system (`SystemCertificates`) or of a+  file in PEM (`CertificatesFrom`).+- `runWebSocketAt`: in clear or over TLS, as a scheme says.+- `urlClientConfig`: the scheme and the configuration of a `ws` or `wss`+  URL, to give to `runWebSocketAt`.++They behave as `runWebSocketClient` does in clear: the action runs in the+calling thread, the server is pinged, and a connection that the server+closes, or that breaks, is not an error. A certificate that is not accepted+is a `ConnectFailed`.++## Building++To build against copies of the libraries this package is built on+([effectful-websockets](https://hackage.haskell.org/package/effectful-websockets),+[streamly-websockets-tls](https://hackage.haskell.org/package/streamly-websockets-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-websockets-tls.cabal view
@@ -0,0 +1,86 @@+cabal-version:   3.12+name:            effectful-websockets-tls+version:         0.1.0.0+synopsis:        The WebSocket effect of effectful-websockets, over TLS too+description:+  Interpreters for the WebSocket effect of effectful-websockets that open+  secure WebSockets, through streamly-websockets-tls. A package apart, so+  that programs that only speak in clear need not build a TLS stack.++homepage:        https://github.com/GuillaumedeVolpiano/effectful-websockets-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-websockets-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.WebSocket.Client.TLS+  build-depends:+    , base                     >=4.19 && <4.22+    , bytestring               ^>=0.12+    , effectful-core           ^>=2.7.1+    , effectful-websockets       ^>=0.1+    , streamly-core            ^>=0.3.3+    , streamly-http            ^>=0.1+    , streamly-network-tls     ^>=0.1+    , streamly-websockets      ^>=0.1+    , streamly-websockets-tls  ^>=0.1+    , tls                      ^>=2.5++test-suite effectful-websockets-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-websockets+    , effectful-websockets-tls+    , network                   ^>=3.2+    , streamly-core+    , streamly-websockets+    , streamly-websockets-tls+    , tasty                     ^>=1.5+    , tasty-hunit               ^>=0.10
+ src/Effectful/WebSocket/Client/TLS.hs view
@@ -0,0 +1,116 @@+-- |+-- Module      : Effectful.WebSocket.Client.TLS+-- Description : Opening a secure WebSocket to a server+-- License     : BSD-3-Clause+--+-- Interpreters for the effect of "Effectful.WebSocket" that open the+-- connection over TLS, or as a URL says.+--+-- > {-# LANGUAGE OverloadedStrings #-}+-- > import Effectful (runEff)+-- > import Effectful.Error.Static (runErrorNoCallStack)+-- > import Effectful.WebSocket (Message, receiveMessage, sendText)+-- > import Effectful.WebSocket.Client (WebSocketError, clientConfig)+-- > import Effectful.WebSocket.Client.TLS (Certificates (SystemCertificates),+-- >                                        runWebSocketSecure)+-- >+-- > hello :: IO (Either WebSocketError (Maybe Message))+-- > hello = runEff . runErrorNoCallStack . runWebSocketSecure SystemCertificates (clientConfig "example.org" 443 "/chat") $ do+-- >   _ <- sendText "hello"+-- >   receiveMessage+--+-- They behave as 'Effectful.WebSocket.Client.runWebSocketClient' does:+-- the action runs in the calling thread, the server is pinged, and a+-- connection that the server closes, or that breaks, is not an error.+module Effectful.WebSocket.Client.TLS+  ( runWebSocketSecure+  , runWebSocketAt+  , urlClientConfig+  , Scheme (..)+  , Certificates (..)+  ) where++import Control.Exception (catch, throwIO, try)+import Data.ByteString (ByteString)+import Data.ByteString.Char8 (unpack)+import Data.IORef (newIORef, readIORef, writeIORef)+import Effectful (Eff, IOE, type (:>))+import Effectful.Error.Static (Error)+import Effectful.WebSocket (WebSocket)+import Effectful.WebSocket.Client (ClientConfig (..), WebSocketError,+                                   clientConfig, connectionConfig,+                                   runWebSocketClient, runWebSocketOver)+import Network.TLS (TLSException)+import Streamly.Data.Stream (unfoldrM)+import Streamly.Data.StreamK (fromStream, uncons)+import Streamly.External.Network.HTTP (Transport (..))+import Streamly.External.Network.TLS (Config (certificates, connectTimeout),+                                      ConnectTimedOut (ConnectTimedOut),+                                      withConnection)+import Streamly.External.Network.TLS qualified as NT (config, transport)+import Streamly.External.Network.WebSocket (Config (host, openTimeout, path, port),+                                            Connection, withConnectionOver)+import Streamly.External.Network.WebSocket qualified as WS (WebSocketError (HandshakeFailed, OpenTimedOut))+import Streamly.External.Network.WebSocket.TLS (Certificates (..), Scheme (..),+                                                urlConfig)++-- | Open a WebSocket over TLS and run an action over it, as+-- 'runWebSocketClient' does in clear. The server must present a+-- certificate valid for the host of the configuration and signed by one+-- of the authorities trusted.+--+-- Throws 'Effectful.WebSocket.Client.ConnectFailed' if the connection+-- cannot be opened, among others when the certificate is not accepted,+-- and 'Effectful.WebSocket.Client.NoPong' if the server stops answering+-- pings.+runWebSocketSecure+  :: (IOE :> es, Error WebSocketError :> es)+  => Certificates+  -> ClientConfig+  -> Eff (WebSocket : es) a+  -> Eff es a+runWebSocketSecure trusted config = runWebSocketOver open config.pingPong+  where+    settings = connectionConfig config+    secure = (NT.config config.host config.port) {certificates = trusted, connectTimeout = settings.openTimeout}+    open :: (Connection -> IO x) -> IO x+    open use = do+      -- What the action gave, kept in case the end of the TLS connection+      -- fails after it.+      result <- newIORef Nothing+      attempt <- try . try . withConnection secure $ \connection ->+        withConnectionOver (guarded (NT.transport connection)) settings use >>= writeIORef result . Just+      done <- readIORef result+      case (done, attempt) of+        (Just value, _) -> pure value+        (Nothing, Left ConnectTimedOut) -> throwIO WS.OpenTimedOut+        (Nothing, Right (Left (problem :: TLSException))) -> throwIO (WS.HandshakeFailed (show problem))+        (Nothing, Right (Right ())) -> throwIO (WS.HandshakeFailed "the connection gave nothing")+    -- Once the connection is open, a failure of TLS is the loss of the+    -- connection, as a failure of TCP is in clear.+    guarded transport =+      Transport+        { send = \bytes -> transport.send bytes `catch` lost+        , receive = unfoldrM (\from -> uncons from `catch` lost) (fromStream transport.receive)+        }+    lost :: TLSException -> IO b+    lost problem = throwIO (userError (show problem))++-- | Open a WebSocket in clear ('Http') or over TLS ('Https').+runWebSocketAt+  :: (IOE :> es, Error WebSocketError :> es)+  => Certificates+  -> Scheme+  -> ClientConfig+  -> Eff (WebSocket : es) a+  -> Eff es a+runWebSocketAt trusted = \case+  Http -> runWebSocketClient+  Https -> runWebSocketSecure trusted++-- | The scheme and the configuration that a @ws@ or @wss@ URL stands for,+-- to give to 'runWebSocketAt': 'Http' for @ws@, 'Https' for @wss@.+urlClientConfig :: ByteString -> Either String (Scheme, ClientConfig)+urlClientConfig text = do+  (scheme, settings) <- urlConfig text+  pure (scheme, clientConfig settings.host settings.port (unpack settings.path))
+ test/Main.hs view
@@ -0,0 +1,120 @@+-- | The interpreters against servers of streamly-websockets on the+-- loopback interface, over TLS and in clear.+module Main (main) where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (withAsync)+import Control.Exception (bracket)+import Control.Monad (forever, replicateM)+import Data.ByteString qualified as BS (replicate)+import Data.ByteString.Char8 (pack)+import Effectful (Eff, IOE, MonadIO (liftIO), runEff)+import Effectful.Error.Static (Error, runErrorNoCallStack)+import Effectful.WebSocket (Message (BinaryMessage, TextMessage), messages,+                            receiveMessage, sendBinary, sendText)+import Effectful.WebSocket.Client (ClientConfig (host, path, pingPong, port),+                                   PingPong (PingPong, interval, timeout),+                                   WebSocketError (..), clientConfig)+import Effectful.WebSocket.Client.TLS (Certificates (..), Scheme (Http, Https),+                                       runWebSocketAt, runWebSocketSecure,+                                       urlClientConfig)+import Network.Socket (socketPort)+import Network.Socket qualified as N (close)+import Streamly.Data.Fold (drain, drainMapM, toList)+import Streamly.Data.Stream (fold)+import Streamly.External.Network.WebSocket.Server (Connection,+                                                   defaultServerOptions, listen,+                                                   send, serveSocket)+import Streamly.External.Network.WebSocket.Server qualified as WSS (Message (TextMessage),+                                                                    close,+                                                                    messages)+import Streamly.External.Network.WebSocket.TLS (loadCredentials,+                                                serveSecureSocket)+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 certificate of the fixtures, trusted for itself.+local :: Certificates+local = CertificatesFrom certificateFile++run :: Eff '[Error WebSocketError, IOE] a -> IO (Either WebSocketError a)+run = runEff . runErrorNoCallStack++-- | Serve over TLS with a handler on a free loopback port, and give the+-- configuration that reaches the server by the name of its certificate.+withSecureServer :: (Connection -> IO ()) -> (ClientConfig -> IO a) -> IO a+withSecureServer handler use = do+  credentials <- loadCredentials certificateFile keyFile+  bracket (listen "127.0.0.1" 0) N.close $ \listener -> do+    port <- socketPort listener+    withAsync (serveSecureSocket credentials listener defaultServerOptions (const handler)) $ \_ ->+      use (clientConfig "localhost" (fromIntegral port) "/")++-- | The same, in clear.+withClearServer :: (Connection -> IO ()) -> (ClientConfig -> IO a) -> IO a+withClearServer handler use =+  bracket (listen "127.0.0.1" 0) N.close $ \listener -> do+    port <- socketPort listener+    withAsync (serveSocket listener defaultServerOptions (const handler)) $ \_ ->+      use (clientConfig "127.0.0.1" (fromIntegral port) "/")++echo :: Connection -> IO ()+echo connection = fold (drainMapM (send connection)) (WSS.messages connection)++tests :: TestTree+tests =+  localOption (mkTimeout 20_000_000) $+    testGroup+      "effectful-websockets-tls"+      [ testCase "echoes text and binary messages over TLS" $ do+          let large = BS.replicate 300_000 42+          outcome <- withSecureServer echo $ \config -> run . runWebSocketSecure local config $ do+            _ <- sendText "héllo"+            _ <- sendBinary large+            replicateM 2 receiveMessage+          outcome @?= Right [Just (TextMessage "héllo"), Just (BinaryMessage large)]+      , testCase "streams messages until the server closes, then sending fails" $ do+          let server connection = mapM_ (send connection . WSS.TextMessage) ["a", "b"] >> WSS.close connection >> fold drain (WSS.messages connection)+          outcome <- withSecureServer server $ \config -> run . runWebSocketSecure local config $ do+            received <- fold toList messages+            liftIO (threadDelay 100_000)+            late <- sendText "late"+            pure (received, late)+          outcome @?= Right ([TextMessage "a", TextMessage "b"], False)+      , testCase "a certificate the system does not know is a failure to connect" $ do+          outcome <- withSecureServer echo $ \config -> run (runWebSocketSecure SystemCertificates config (pure ()))+          case outcome of+            Left (ConnectFailed _) -> pure ()+            other -> assertFailure ("expected ConnectFailed, got " <> show other)+      , testCase "a server in clear is a failure to connect" $ do+          outcome <- withClearServer echo $ \config -> run (runWebSocketSecure local config {host = "localhost"} (pure ()))+          case outcome of+            Left (ConnectFailed _) -> pure ()+            other -> assertFailure ("expected ConnectFailed, got " <> show other)+      , testCase "reports a server that stops answering pings" $ do+          -- This server never reads, so it never answers a ping.+          outcome <- withSecureServer (\_ -> forever (threadDelay 1_000_000)) $ \config ->+            run (runWebSocketSecure local config {pingPong = Just PingPong {interval = 1, timeout = 2}} receiveMessage)+          outcome @?= Left NoPong+      , testCase "the scheme chooses between clear and TLS" $ do+          inClear <- withClearServer echo $ \config -> run (runWebSocketAt local Http config (sendText "clear" >> receiveMessage))+          overTls <- withSecureServer echo $ \config -> run (runWebSocketAt local Https config (sendText "secure" >> receiveMessage))+          (inClear, overTls) @?= (Right (Just (TextMessage "clear")), Right (Just (TextMessage "secure")))+      , testCase "a URL gives the scheme and the configuration" $ do+          let summary = fmap (\(scheme, config) -> (scheme, config.host, config.port, config.path)) . urlClientConfig+          summary "wss://example.org/chat?room=1" @?= Right (Https, "example.org", 443, "/chat?room=1")+          summary "ws://127.0.0.1:9330/api" @?= Right (Http, "127.0.0.1", 9330, "/api")+          summary "https://example.org/" @?= Left "not a ws or wss URL"+      , testCase "a URL reaches the server it names" $+          withSecureServer echo $ \config -> do+            let url = "wss://localhost:" <> pack (show config.port) <> "/"+            outcome <- either (fail . show) (\(scheme, found) -> run (runWebSocketAt local scheme found (sendText "by URL" >> receiveMessage))) (urlClientConfig url)+            outcome @?= Right (Just (TextMessage "by URL"))+      ]
+ 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-----