packages feed

http-client-rustls (empty) → 0.0.0.0

raw patch · 6 files changed

+354/−0 lines, 6 filesdep +basedep +bytestringdep +directory

Dependencies added: base, bytestring, directory, filepath, http-client, http-client-rustls, http-types, network, port-utils, process, resourcet, rustls, tasty, tasty-hunit, temporary, text

Files

+ CHANGELOG.md view
@@ -0,0 +1,1 @@+# Revision history for http-client-rustls
+ LICENSE view
@@ -0,0 +1,121 @@+Creative Commons Legal Code++CC0 1.0 Universal++    CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE+    LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN+    ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS+    INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES+    REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS+    PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM+    THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED+    HEREUNDER.++Statement of Purpose++The laws of most jurisdictions throughout the world automatically confer+exclusive Copyright and Related Rights (defined below) upon the creator+and subsequent owner(s) (each and all, an "owner") of an original work of+authorship and/or a database (each, a "Work").++Certain owners wish to permanently relinquish those rights to a Work for+the purpose of contributing to a commons of creative, cultural and+scientific works ("Commons") that the public can reliably and without fear+of later claims of infringement build upon, modify, incorporate in other+works, reuse and redistribute as freely as possible in any form whatsoever+and for any purposes, including without limitation commercial purposes.+These owners may contribute to the Commons to promote the ideal of a free+culture and the further production of creative, cultural and scientific+works, or to gain reputation or greater distribution for their Work in+part through the use and efforts of others.++For these and/or other purposes and motivations, and without any+expectation of additional consideration or compensation, the person+associating CC0 with a Work (the "Affirmer"), to the extent that he or she+is an owner of Copyright and Related Rights in the Work, voluntarily+elects to apply CC0 to the Work and publicly distribute the Work under its+terms, with knowledge of his or her Copyright and Related Rights in the+Work and the meaning and intended legal effect of CC0 on those rights.++1. Copyright and Related Rights. A Work made available under CC0 may be+protected by copyright and related or neighboring rights ("Copyright and+Related Rights"). Copyright and Related Rights include, but are not+limited to, the following:++  i. the right to reproduce, adapt, distribute, perform, display,+     communicate, and translate a Work;+ ii. moral rights retained by the original author(s) and/or performer(s);+iii. publicity and privacy rights pertaining to a person's image or+     likeness depicted in a Work;+ iv. rights protecting against unfair competition in regards to a Work,+     subject to the limitations in paragraph 4(a), below;+  v. rights protecting the extraction, dissemination, use and reuse of data+     in a Work;+ vi. database rights (such as those arising under Directive 96/9/EC of the+     European Parliament and of the Council of 11 March 1996 on the legal+     protection of databases, and under any national implementation+     thereof, including any amended or successor version of such+     directive); and+vii. other similar, equivalent or corresponding rights throughout the+     world based on applicable law or treaty, and any national+     implementations thereof.++2. Waiver. To the greatest extent permitted by, but not in contravention+of, applicable law, Affirmer hereby overtly, fully, permanently,+irrevocably and unconditionally waives, abandons, and surrenders all of+Affirmer's Copyright and Related Rights and associated claims and causes+of action, whether now known or unknown (including existing as well as+future claims and causes of action), in the Work (i) in all territories+worldwide, (ii) for the maximum duration provided by applicable law or+treaty (including future time extensions), (iii) in any current or future+medium and for any number of copies, and (iv) for any purpose whatsoever,+including without limitation commercial, advertising or promotional+purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each+member of the public at large and to the detriment of Affirmer's heirs and+successors, fully intending that such Waiver shall not be subject to+revocation, rescission, cancellation, termination, or any other legal or+equitable action to disrupt the quiet enjoyment of the Work by the public+as contemplated by Affirmer's express Statement of Purpose.++3. Public License Fallback. Should any part of the Waiver for any reason+be judged legally invalid or ineffective under applicable law, then the+Waiver shall be preserved to the maximum extent permitted taking into+account Affirmer's express Statement of Purpose. In addition, to the+extent the Waiver is so judged Affirmer hereby grants to each affected+person a royalty-free, non transferable, non sublicensable, non exclusive,+irrevocable and unconditional license to exercise Affirmer's Copyright and+Related Rights in the Work (i) in all territories worldwide, (ii) for the+maximum duration provided by applicable law or treaty (including future+time extensions), (iii) in any current or future medium and for any number+of copies, and (iv) for any purpose whatsoever, including without+limitation commercial, advertising or promotional purposes (the+"License"). The License shall be deemed effective as of the date CC0 was+applied by Affirmer to the Work. Should any part of the License for any+reason be judged legally invalid or ineffective under applicable law, such+partial invalidity or ineffectiveness shall not invalidate the remainder+of the License, and in such case Affirmer hereby affirms that he or she+will not (i) exercise any of his or her remaining Copyright and Related+Rights in the Work or (ii) assert any associated claims and causes of+action with respect to the Work, in either case contrary to Affirmer's+express Statement of Purpose.++4. Limitations and Disclaimers.++ a. No trademark or patent rights held by Affirmer are waived, abandoned,+    surrendered, licensed or otherwise affected by this document.+ b. Affirmer offers the Work as-is and makes no representations or+    warranties of any kind concerning the Work, express, implied,+    statutory or otherwise, including without limitation warranties of+    title, merchantability, fitness for a particular purpose, non+    infringement, or the absence of latent or other defects, accuracy, or+    the present or absence of errors, whether or not discoverable, all to+    the greatest extent permissible under applicable law.+ c. Affirmer disclaims responsibility for clearing rights of other persons+    that may apply to the Work or any use thereof, including without+    limitation any person's Copyright and Related Rights in the Work.+    Further, Affirmer disclaims responsibility for obtaining any necessary+    consents, permissions or other rights required for any use of the+    Work.+ d. Affirmer understands and acknowledges that Creative Commons is not a+    party to this document and has no duty or obligation with respect to+    this CC0 or use of the Work.
+ README.md view
@@ -0,0 +1,7 @@+# http-client-rustls+[![CI](https://github.com/amesgen/hs-rustls/workflows/CI/badge.svg)](https://github.com/amesgen/hs-rustls/actions)+[![Hackage](https://img.shields.io/hackage/v/rustls)](https://hackage.haskell.org/package/http-client-rustls)++Make HTTPS requests using [http-client](https://hackage.haskell.org/package/http-client) and [Rustls](https://github.com/rustls/rustls).++See [the haddocks](https://hackage.haskell.org/package/http-client-rustls/docs/Network-HTTP-Client-Rustls.html) for documentation.
+ http-client-rustls.cabal view
@@ -0,0 +1,68 @@+cabal-version: 2.4+name: http-client-rustls+version: 0.0.0.0++synopsis: http-client TLS backend using Rustls+description:+  Make HTTPS connections using [http-client](https://hackage.haskell.org/package/http-client)+  and [Rustls](https://github.com/rustls/rustls).+category: Cryptography, Network++author: amesgen+maintainer: amesgen@amesgen.de+homepage: https://github.com/amesgen/hs-rustls/tree/main/http-client-rustls+bug-reports: https://github.com/amesgen/hs-rustls/issues+license: CC0-1.0+license-file: LICENSE++extra-source-files:+  README.md+  CHANGELOG.md++source-repository head+  location: https://github.com/amesgen/hs-rustls+  type: git++common commons+  default-language: Haskell2010+  ghc-options: -Wall -Wincomplete-record-updates -Wincomplete-uni-patterns -Wredundant-constraints -Wno-name-shadowing -Wno-unticked-promoted-constructors -fhide-source-paths+  if impl(ghc >= 8.10)+    ghc-options: -Wunused-packages+  default-extensions: BlockArguments LambdaCase OverloadedStrings RankNTypes ScopedTypeVariables TypeApplications ViewPatterns++library+  import: commons+  ghc-options: -Wmissing-export-lists+  hs-source-dirs: src+  exposed-modules:+    Network.HTTP.Client.Rustls+  build-depends:+      base >= 4.12 && < 5+    , rustls ^>= 0.0+    , http-client ^>= 0.7.11+    , text ^>= 1.2 || ^>= 2.0+    , bytestring ^>= 0.10 || ^>= 0.11+    , resourcet ^>= 1.2+    , network ^>= 3.1++test-suite tasty+  import: commons+  type: exitcode-stdio-1.0+  main-is: Main.hs+  hs-source-dirs: test+  ghc-options: -threaded -rtsopts -with-rtsopts=-N+  build-depends:+      base+    , http-client-rustls+    , tasty >= 1.3 && < 1.5+    , tasty-hunit ^>= 0.10+    , bytestring+    , rustls+    , http-types ^>= 0.12+    , http-client+    , process ^>= 1.6+    , filepath ^>= 1.4+    , directory ^>= 1.3+    , temporary ^>= 1.3+    , network+    , port-utils ^>= 0.2
+ src/Network/HTTP/Client/Rustls.hs view
@@ -0,0 +1,68 @@+-- | Make HTTPS connections using+-- [http-client](https://hackage.haskell.org/package/http-client) and+-- [Rustls](https://github.com/rustls/rustls).+--+-- >>> import qualified Rustls+-- >>> import qualified Network.HTTP.Client as HTTP+-- >>> :{+-- newRustlsManager :: IO HTTP.Manager+-- newRustlsManager = do+--   clientConfig <-+--     Rustls.buildClientConfig $ Rustls.defaultClientConfigBuilder roots+--   HTTP.newManager $ rustlsManagerSettings clientConfig+--   where+--     -- For now, rustls-ffi does not provide a built-in way to access+--     -- the OS certificate store.+--     roots = Rustls.ClientRootsFromFile "/etc/ssl/certs/ca-certificates.crt"+-- >>> :}+--+-- >>> :{+-- example = do+--   mgr <- newRustlsManager -- this should be shared across multiple requests+--   req <- HTTP.parseUrlThrow "https://example.org"+--   res <- HTTP.httpLbs req mgr+--   print $ HTTP.responseBody res+-- :}+module Network.HTTP.Client.Rustls+  ( rustlsManagerSettings,+  )+where++import qualified Control.Exception as E+import Data.Acquire (ReleaseType (..))+import Data.Acquire.Internal (Acquire (..), Allocated (..))+import qualified Data.ByteString.Builder.Extra as B+import qualified Data.Text as T+import qualified Network.HTTP.Client as HTTP+import qualified Network.HTTP.Client.Internal as HTTP+import qualified Network.Socket as NS+import qualified Rustls++-- | Get TLS-enabled HTTP 'HTTP.ManagerSettings' from a Rustls+-- 'Rustls.ClientConfig', consumable via 'HTTP.newManager'.+rustlsManagerSettings :: Rustls.ClientConfig -> HTTP.ManagerSettings+rustlsManagerSettings conf =+  HTTP.defaultManagerSettings+    { HTTP.managerTlsConnection = pure \hostAddress host port ->+        HTTP.withSocket mempty hostAddress host port \sock ->+          makeTlsConnection conf sock host,+      HTTP.managerTlsProxyConnection = pure \connStr checkConn serverName _ host port ->+        HTTP.withSocket mempty Nothing host port \sock -> do+          conn <- HTTP.socketConnection sock B.defaultChunkSize+          HTTP.connectionWrite conn connStr+          checkConn conn+          makeTlsConnection conf sock serverName,+      HTTP.managerWrapException = \req ->+        E.handle @Rustls.RustlsException+          (E.throwIO . HTTP.HttpExceptionRequest req . HTTP.InternalException . E.toException)+          . HTTP.managerWrapException HTTP.defaultManagerSettings req+    }+  where+    makeTlsConnection conf socket hostname = E.mask \restore -> do+      let strippedHost = T.pack $ HTTP.strippedHostName hostname+          Acquire allocate = Rustls.newClientConnection socket conf strippedHost+      Allocated conn freeConn <- allocate restore+      HTTP.makeConnection+        do Rustls.readBS conn (fromIntegral B.defaultChunkSize)+        do Rustls.writeBS conn+        do freeConn ReleaseNormal; NS.close socket
+ test/Main.hs view
@@ -0,0 +1,89 @@+module Main where++import qualified Control.Exception as E+import qualified Data.ByteString as B+import qualified Data.ByteString.Lazy as BL+import qualified Network.HTTP.Client as HTTP+import Network.HTTP.Client.Internal as HTTP (hostAddress)+import Network.HTTP.Client.Rustls+import qualified Network.HTTP.Types as HTTP+import Network.Socket (tupleToHostAddress)+import Network.Socket.Wait (wait)+import qualified Rustls+import qualified System.Directory as Dir+import System.FilePath ((</>))+import qualified System.IO.Temp as Temp+import qualified System.Process as Process+import Test.Tasty+import Test.Tasty.HUnit++main :: IO ()+main = defaultMain $ withRustlsManagerAndServer \(fmap fst -> mgr) ->+  let failsOn req =+        E.try (HTTP.httpNoBody (modifyReq req) =<< mgr) >>= \case+          Right _ ->+            assertFailure "Established invalid TLS connection!"+          Left (E.fromException -> Just (HTTP.HttpExceptionRequest _ (HTTP.InternalException ie)))+            | Just (e :: Rustls.RustlsException) <- E.fromException ie,+              Rustls.isCertError e ->+                mempty+          Left (E.SomeException e) ->+            assertFailure $ "Failed with unexpected exception: " <> show e+   in testGroup+        "HTTPS-via-Rustls connectivity tests"+        [ testCase "Make an HTTPS request" do+            req <- modifyReq <$> HTTP.parseUrlThrow "https://example.org"+            res <- HTTP.httpNoBody req =<< mgr+            HTTP.responseStatus res @?= HTTP.status200,+          testCase "Download byte stream" do+            req <- modifyReq <$> HTTP.parseUrlThrow "https://example.org/file"+            res <- HTTP.httpLbs req =<< mgr+            BL.length (HTTP.responseBody res) @?= fromIntegral fileLength,+          testCase "Fail on wrong host" $+            failsOn "https://examplee.org"+        ]+  where+    fileLength = 100000+    fileByte = 42++    modifyReq req =+      req+        { HTTP.port = 8080,+          HTTP.hostAddress = Just $ tupleToHostAddress (127, 0, 0, 1)+        }++    withRustlsManagerAndServer = withResource prepareServer cleanupServer+      where+        prepareServer = do+          tmpDir <-+            flip Temp.createTempDirectory "hs-rustls-server"+              =<< Temp.getCanonicalTemporaryDirectory++          let cp = Process.proc "minica" ["-domains", "example.org"]+          _ <- Process.readCreateProcess (cp {Process.cwd = Just tmpDir}) ""+          mgr <-+            HTTP.newManager . rustlsManagerSettings+              =<< Rustls.buildClientConfig+                ( Rustls.defaultClientConfigBuilder+                    (Rustls.ClientRootsFromFile $ tmpDir </> "minica.pem")+                )+          B.writeFile (tmpDir </> "file") $ B.replicate fileLength fileByte+          procInfo <-+            Process.createProcess $+              ( Process.proc+                  "miniserve"+                  [ "--tls-cert",+                    tmpDir </> "example.org/cert.pem",+                    "--tls-key",+                    tmpDir </> "example.org/key.pem",+                    tmpDir+                  ]+              )+                { Process.std_out = Process.CreatePipe,+                  Process.std_in = Process.CreatePipe+                }+          wait "127.0.0.1" 8080+          pure (mgr, (tmpDir, procInfo))+        cleanupServer (_, (tmpDir, procInfo)) = E.mask_ do+          Process.cleanupProcess procInfo+          Dir.removeDirectoryRecursive tmpDir