packages feed

streamly-websockets-tls (empty) → 0.1.0.0

raw patch · 9 files changed

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

Dependencies added: async, base, bytestring, network, stm, 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 streamly-websockets-tls++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* WebSockets by URL, the scheme choosing between plain TCP and TLS:+  `withUrl`, `urlConfig`, `withConnectionAt`.+* Servers over TLS: `serveSecure`, `serveSecureSocket`.
+ 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,61 @@+# streamly-websockets-tls++Secure WebSockets, and WebSockets by URL, with+[Streamly](https://streamly.composewell.com/). This is the convenient face+of+[streamly-websockets](https://hackage.haskell.org/package/streamly-websockets):+the scheme of a URL (`ws` or `wss`) chooses between plain TCP and TLS+(through+[streamly-network-tls](https://hackage.haskell.org/package/streamly-network-tls)),+and a server can serve over TLS.++A client:++```haskell+{-# LANGUAGE OverloadedStrings #-}++import Streamly.External.Network.WebSocket (Message (TextMessage), receive,+                                            send)+import Streamly.External.Network.WebSocket.TLS (withUrl)++main :: IO ()+main = withUrl "wss://example.org/chat" $ \connection -> do+  send connection (TextMessage "hello")+  receive connection >>= print+```++A server over TLS that sends back what it receives:++```haskell+{-# LANGUAGE OverloadedStrings #-}++import Streamly.Data.Fold (drainMapM)+import Streamly.Data.Stream (fold)+import Streamly.External.Network.WebSocket.Server (defaultServerOptions,+                                                   messages, send)+import Streamly.External.Network.WebSocket.TLS (loadCredentials, serveSecure)++main :: IO ()+main = do+  credentials <- loadCredentials "certificate.pem" "key.pem"+  serveSecure credentials "0.0.0.0" 8443 defaultServerOptions $ \_ connection ->+    fold (drainMapM (send connection)) (messages connection)+```++## What it gives++- `withUrl`: the WebSocket of a `ws` or `wss` URL, checked against the+  certificates of the system.+- `urlConfig` and `withConnectionAt`: the same in two steps, to change the+  configuration (extra headers, bounds) or the certificates trusted.+- `serveSecure` and `serveSecureSocket`: a server over TLS, with the+  certificate and the key that `loadCredentials` reads.++## Building++To build against copies of the libraries this package is built on+([streamly-websockets](https://hackage.haskell.org/package/streamly-websockets),+[streamly-network-tls](https://hackage.haskell.org/package/streamly-network-tls),+[streamly-http](https://hackage.haskell.org/package/streamly-http))+checked out next to this repository, pass+`--project-file=cabal.project.siblings`.
+ src/Streamly/External/Network/WebSocket/TLS.hs view
@@ -0,0 +1,109 @@+-- |+-- Module      : Streamly.External.Network.WebSocket.TLS+-- Description : WebSockets by URL, and over TLS+-- License     : BSD-3-Clause+--+-- Open a WebSocket from its URL, the scheme choosing between plain TCP+-- (@ws@) and TLS (@wss@), and serve WebSockets over TLS.+--+-- > {-# LANGUAGE OverloadedStrings #-}+-- > import Streamly.External.Network.WebSocket (Message (TextMessage), receive,+-- >                                             send)+-- > import Streamly.External.Network.WebSocket.TLS (withUrl)+-- >+-- > main :: IO ()+-- > main = withUrl "wss://example.org/chat" $ \connection -> do+-- >   send connection (TextMessage "hello")+-- >   receive connection >>= print+module Streamly.External.Network.WebSocket.TLS+  ( -- * Clients+    withUrl+  , urlConfig+  , withConnectionAt+  , Scheme (..)+  , Certificates (..)++    -- * Servers+  , serveSecure+  , serveSecureSocket+  , Credentials+  , loadCredentials+  ) where++import Control.Exception (bracket, throwIO, try)+import Data.ByteString (ByteString, breakSubstring)+import Data.ByteString.Char8 qualified as BS8 (map)+import Data.Char (toLower)+import Network.Socket (Socket, close)+import Streamly.External.Network.HTTP (HttpError (..))+import Streamly.External.Network.HTTP.URL (Scheme (..), Url (..), parseUrl)+import Streamly.External.Network.TLS (Certificates (..), Credentials,+                                      acceptConnection, loadCredentials,+                                      transport)+import Streamly.External.Network.TLS qualified as NT (Config (certificates, connectTimeout),+                                                      ConnectTimedOut (ConnectTimedOut),+                                                      config, withConnection)+import Streamly.External.Network.WebSocket (Config (..), Connection,+                                            WebSocketError (..), config,+                                            withConnection, withConnectionOver)+import Streamly.External.Network.WebSocket.Server (ServerOptions (..), Upgrade,+                                                   acceptOver, listen,+                                                   serveSocketWith)++-- | Open the WebSocket of a URL such as @wss:\/\/example.org\/chat@ and+-- use it, as 'withConnection' does: over TLS for @wss@, checked against+-- the certificates of the system, and in clear for @ws@.+--+-- Throws what 'withConnection' throws; @InvalidRequest@ (an 'HttpError')+-- for what is not a @ws@ or @wss@ URL; and @TLSException@ (of the @tls@+-- package) when the TLS connection fails, among others for a certificate+-- that is not accepted.+withUrl :: ByteString -> (Connection -> IO a) -> IO a+withUrl text use = do+  (scheme, settings) <- either (throwIO . InvalidRequest) pure (urlConfig text)+  withConnectionAt SystemCertificates scheme settings use++-- | The scheme and the configuration that a @ws@ or @wss@ URL stands for:+-- 'Http' for @ws@, 'Https' for @wss@; the ports are 80 and 443 unless the+-- URL names one. Change the configuration before giving it to+-- 'withConnectionAt' for extra headers or other bounds.+urlConfig :: ByteString -> Either String (Scheme, Config)+urlConfig text = case breakSubstring "://" text of+  (name, rest)+    | BS8.map toLower name == "ws" -> from ("http" <> rest)+    | BS8.map toLower name == "wss" -> from ("https" <> rest)+  _ -> Left "not a ws or wss URL"+  where+    from equivalent = case parseUrl equivalent of+      Left _ -> Left "not a ws or wss URL"+      Right found -> Right (found.scheme, config found.host found.port found.target)++-- | Open a WebSocket in clear ('Http') or over TLS ('Https') and use it,+-- as 'withConnection' does. Over TLS, the server must present a+-- certificate signed by one of the authorities trusted, and the time+-- allowed to open the connection covers the TLS handshake too.+withConnectionAt :: Certificates -> Scheme -> Config -> (Connection -> IO a) -> IO a+withConnectionAt trusted scheme settings use = case scheme of+  Http -> withConnection settings use+  Https -> do+    let secure = (NT.config settings.host settings.port) {NT.certificates = trusted, NT.connectTimeout = settings.openTimeout}+    opened <- try (NT.withConnection secure (\connection -> withConnectionOver (transport connection) settings use))+    -- One error for a connection that is not open in time, whatever the+    -- scheme.+    either (\NT.ConnectTimedOut -> throwIO OpenTimedOut) pure opened++-- | Listen on an address and a port, and serve every client over TLS with+-- a handler, each in a thread of its own, without end. See+-- 'serveSecureSocket'.+serveSecure :: Credentials -> String -> Int -> ServerOptions -> (Upgrade -> Connection -> IO ()) -> IO ()+serveSecure credentials host port options handler =+  bracket (listen host port) close (\listener -> serveSecureSocket credentials listener options handler)++-- | Serve over TLS every client that connects to a listening socket, as+-- @serveSocket@ does in clear. The server proves its name with its+-- credentials; the time allowed for the request of a client also bounds+-- its TLS handshake.+serveSecureSocket :: Credentials -> Socket -> ServerOptions -> (Upgrade -> Connection -> IO ()) -> IO ()+serveSecureSocket credentials listener options handler = serveSocketWith listener $ \peer ->+  acceptConnection credentials options.openTimeout peer $ \connection ->+    acceptOver (transport connection) options handler
+ streamly-websockets-tls.cabal view
@@ -0,0 +1,81 @@+cabal-version:   3.12+name:            streamly-websockets-tls+version:         0.1.0.0+synopsis:        Secure WebSockets, and WebSockets by URL, with Streamly+description:+  The convenient face of streamly-websockets: open a WebSocket from its+  URL, the scheme (ws or wss) choosing between plain TCP and TLS through+  streamly-network-tls, and serve WebSockets over TLS.++homepage:        https://github.com/GuillaumedeVolpiano/streamly-websockets-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-websockets-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.WebSocket.TLS+  build-depends:+    , base                  >=4.19 && <4.22+    , bytestring            ^>=0.12+    , network               ^>=3.2+    , streamly-http         ^>=0.1+    , streamly-network-tls  ^>=0.1+    , streamly-websockets   ^>=0.1++test-suite streamly-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+    , network+    , stm                      ^>=2.5+    , streamly-core            ^>=0.3.3+    , streamly-http+    , streamly-websockets+    , streamly-websockets-tls+    , tasty                    ^>=1.5+    , tasty-hunit              ^>=0.10+    , tls                      ^>=2.5
+ test/Main.hs view
@@ -0,0 +1,137 @@+-- | WebSockets by URL and over TLS, between the client and the servers of+-- these libraries on the loopback interface.+module Main (main) where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (withAsync)+import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)+import Control.Concurrent.STM (atomically)+import Control.Exception (bracket, try)+import Data.ByteString qualified as BS (replicate)+import Data.ByteString.Char8 (pack)+import Network.Socket (Family (AF_INET), SockAddr (SockAddrInet),+                       SocketType (Stream), accept, close, connect,+                       defaultProtocol, socketPort, tupleToHostAddress)+import Network.Socket qualified as N (socket)+import Network.Socket.ByteString (recv, sendAll)+import Network.TLS (TLSException (HandshakeFailed))+import Streamly.Data.Fold (drainMapM)+import Streamly.Data.Stream (fold, toList)+import Streamly.Data.Stream qualified as S (take)+import Streamly.External.Network.HTTP (HttpError (..))+import Streamly.External.Network.WebSocket (Config (host, openTimeout, path, port),+                                            Connection,+                                            Message (BinaryMessage, TextMessage),+                                            WebSocketError (OpenTimedOut),+                                            config, messages, ping, pongCount,+                                            receive, send)+import Streamly.External.Network.WebSocket.Server (Upgrade (..),+                                                   defaultServerOptions, listen,+                                                   serveSocket)+import Streamly.External.Network.WebSocket.TLS (Certificates (CertificatesFrom),+                                                Scheme (Http, Https),+                                                loadCredentials,+                                                serveSecureSocket, urlConfig,+                                                withConnectionAt, withUrl)+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++-- | Send back every message received.+echoBack :: Upgrade -> Connection -> IO ()+echoBack _ connection = fold (drainMapM (send connection)) (messages connection)++-- | Serve over TLS with a handler on a free port of the loopback+-- interface, and run something against the port.+withSecureServer :: (Upgrade -> Connection -> IO ()) -> (Int -> IO a) -> IO a+withSecureServer handler run = do+  credentials <- loadCredentials certificateFile keyFile+  bracket (listen "127.0.0.1" 0) close $ \listener -> do+    port <- socketPort listener+    withAsync (serveSecureSocket credentials listener defaultServerOptions handler) $ \_ -> run (fromIntegral port)++-- | The same, in clear.+withClearServer :: (Upgrade -> Connection -> IO ()) -> (Int -> IO a) -> IO a+withClearServer handler run =+  bracket (listen "127.0.0.1" 0) close $ \listener -> do+    port <- socketPort listener+    withAsync (serveSocket listener defaultServerOptions handler) $ \_ -> run (fromIntegral port)++tests :: TestTree+tests =+  localOption (mkTimeout 20_000_000) $+    testGroup+      "streamly-websockets-tls"+      [ testCase "what a ws or wss URL stands for" $ do+          let summary = fmap (\(scheme, settings) -> (scheme, settings.host, settings.port, settings.path)) . urlConfig+          summary "ws://example.org/chat?room=1" @?= Right (Http, "example.org", 80, "/chat?room=1")+          summary "WSS://Example.org" @?= Right (Https, "example.org", 443, "/")+          summary "wss://[::1]:9443/api#top" @?= Right (Https, "::1", 9443, "/api")+          map summary ["", "example.org", "http://example.org/", "https://example.org/", "ws:/example.org", "ws://", "ws://user@example.org/", "wss://example.org/a b"]+            @?= replicate 8 (Left "not a ws or wss URL")+      , testCase "messages go over TLS and come back, of every length form" $ do+          let sizes = [0, 125, 126, 65535, 65536, 300_000]+          outcome <- withSecureServer echoBack $ \port ->+            withConnectionAt local Https (config "localhost" port "/") $ \connection -> do+              ping connection "x"+              send connection (TextMessage "héllo")+              mapM_ (\size -> send connection (BinaryMessage (BS.replicate size 7))) sizes+              answers <- toList (S.take (1 + length sizes) (messages connection))+              pongs <- atomically (pongCount connection)+              pure (answers, pongs)+          outcome @?= (TextMessage "héllo" : map (\size -> BinaryMessage (BS.replicate size 7)) sizes, 1)+      , testCase "a ws URL goes in clear, with its path" $ do+          asked <- newEmptyMVar+          answer <- withClearServer (\upgrade connection -> putMVar asked upgrade.path >> echoBack upgrade connection) $ \port ->+            withUrl ("ws://127.0.0.1:" <> pack (show port) <> "/chat?room=1") $ \connection ->+              send connection (TextMessage "in clear") >> receive connection+          takeMVar asked >>= (@?= "/chat?room=1")+          answer @?= Just (TextMessage "in clear")+      , testCase "a wss URL goes over TLS, and a server the system does not know is refused" $+          withSecureServer echoBack $ \port ->+            try (withUrl ("wss://localhost:" <> pack (show port) <> "/") (\_ -> pure ())) >>= \case+              Left (HandshakeFailed _) -> pure ()+              Left other -> assertFailure ("expected HandshakeFailed, got " <> show other)+              Right () -> assertFailure "the certificate was accepted"+      , testCase "what is not a ws or wss URL is refused before any connection" $+          try (withUrl "https://example.org/" (\_ -> pure ())) >>= \case+            Left (InvalidRequest _) -> pure ()+            Left other -> assertFailure ("expected InvalidRequest, got " <> show other)+            Right () -> assertFailure "no error, expected InvalidRequest"+      , testCase "a wss connection to a server that speaks in clear is a TLS failure" $+          -- The server in clear answers 400 to what it reads as a request.+          withClearServer echoBack $ \port ->+            try (withConnectionAt local Https (config "localhost" port "/") (\_ -> pure ())) >>= \case+              Left (HandshakeFailed _) -> pure ()+              Left other -> assertFailure ("expected HandshakeFailed, got " <> show other)+              Right () -> assertFailure "no error, expected HandshakeFailed"+      , testCase "a wss connection to a server that says nothing gives up in time" $+          bracket (listen "127.0.0.1" 0) close $ \listener -> do+            port <- socketPort listener+            let hold = bracket (fst <$> accept listener) close (\_ -> threadDelay 10_000_000)+            withAsync hold $ \_ ->+              try (withConnectionAt local Https (config "localhost" (fromIntegral port) "/") {openTimeout = Just 200_000} (\_ -> pure ())) >>= (@?= Left OpenTimedOut)+      , testCase "the secure server goes on after a client that does not speak TLS" $ do+          served <- withSecureServer echoBack $ \port -> do+            bracket (N.socket AF_INET Stream defaultProtocol) close $ \socket -> do+              connect socket (SockAddrInet (fromIntegral port) (tupleToHostAddress (127, 0, 0, 1)))+              sendAll socket "GET / HTTP/1.1\r\nHost: x\r\n\r\n"+              _ <- recv socket 4096+              pure ()+            withConnectionAt local Https (config "localhost" port "/") (\connection -> send connection (TextMessage "still serving") >> receive connection)+          served @?= Just (TextMessage "still serving")+      , testCase "the handler of a secure server may close first" $ do+          received <- withSecureServer (\_ connection -> send connection (TextMessage "bye")) $ \port ->+            withConnectionAt local Https (config "localhost" port "/") (toList . messages)+          received @?= [TextMessage "bye"]+      ]
+ 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-----