packages feed

hs-hath-1.3.0: test/MockRPC.hs

-- | A stand-in for the H\@H RPC server, which also plays the image server that
-- files are fetched from.
module MockRPC ( MockRPC(..), defaultMockRPC, withMockRPC, loginSettings ) where

import           Control.Concurrent       ( threadDelay )

import           Data.ByteString.Builder  ( byteString )
import qualified Data.ByteString.Char8    as BS
import qualified Data.List                as List
import           Data.Time.Clock.System   ( SystemTime(systemSeconds), getSystemTime )

import           Hath.Protocol            ( sha1Hex )

import qualified Network.HTTP.Types       as HTTP
import qualified Network.Wai              as Wai
import qualified Network.Wai.Handler.Warp as Warp

import           Relude

import           System.Environment       ( setEnv )
import           System.IO.Error          ( ioError, mkIOError, resourceVanishedErrorType )

data MockRPC
  = MockRPC
  { mockFileContent   :: ByteString
    -- ^ what the image server sends, whichever file is asked for
  , mockCertificate   :: ByteString
    -- ^ the reply to get_cert
  , mockClientKey     :: ByteString
    -- ^ the key OK replies are signed with
  , mockClockAhead    :: Int64
    -- ^ how far its clock is ahead of ours. A request signed more than a
    -- minute off it is answered KEY_EXPIRED, except server_stat, which
    -- tells the time.
  , mockOutages       :: Int
    -- ^ how many RPC requests it answers with a 500 before it works
  , mockBlacklist     :: [ ByteString ]
  , mockSeen          :: ( ByteString, ByteString ) -> IO ()
    -- ^ told the act and add of each RPC or gallery downloader request as it arrives
  , mockRPCServerIP   :: ByteString
    -- ^ its address as its settings give it (@rpc_server_ip@); by default the
    -- one the tests send server commands from
  , mockPauseHalfway  :: Int
    -- ^ microseconds the image server waits halfway through a file
  , mockHangUpHalfway :: Bool
    -- ^ whether it hangs up there instead, having announced the whole file
  , mockQueue         :: ByteString -> ByteString
    -- ^ the reply to a fetchqueue, given its add (the gallery it marks done)
  }

defaultMockRPC :: MockRPC
defaultMockRPC
  = MockRPC
  { mockFileContent   = "TEST_FILE_CONTENT"
  , mockCertificate   = "FAIL\nNo test certificate available"
  , mockClientKey     = "test-secret-key-12345"
  , mockClockAhead    = 0
  , mockOutages       = 0
  , mockBlacklist     = []
  , mockSeen          = const pass
  , mockRPCServerIP   = "127.0.0.1"
  , mockPauseHalfway  = 0
  , mockHangUpHalfway = False
  , mockQueue         = const "NO_PENDING_DOWNLOADS"
  }

loginSettings :: MockRPC -> [ ByteString ]
loginSettings mock
  = [ "host=127.0.0.1"
    , "port=8080"
    , "throttle_bytes=0"
    , "disklimit_bytes=107374182400"
    , "diskremaining_bytes=107374182400"
    , "rpc_server_ip=" <> mockRPCServerIP mock
    ]

withMockRPC :: MockRPC -> IO a -> IO a
withMockRPC mock action = do
  outagesLeft <- newIORef (mockOutages mock)
  Warp.testWithApplication (pure (application mock outagesLeft)) $ \port -> do
    setEnv "HATH_RPC_HOST" ("localhost:" <> show port)
    action

application :: MockRPC -> IORef Int -> Wai.Application
application mock outagesLeft req respond = case ( Wai.rawPathInfo req, parameter "act" ) of
  ( "/16/rpc", Just act ) -> do
    mockSeen mock ( act, add )
    down <- atomicModifyIORef' outagesLeft $ \n -> ( n - 1, n > 0 )
    clock <- (+ mockClockAhead mock) . systemSeconds <$> getSystemTime
    respond
      $ if down
        then Wai.responseLBS HTTP.status500 [] ""
        else Wai.responseLBS HTTP.status200 [] $ fromStrict $ rpcReply clock act
  ( "/16/dl", Just "fetchqueue" ) -> do
    mockSeen mock ( "fetchqueue", add )
    respond $ Wai.responseLBS HTTP.status200 [] $ fromStrict $ mockQueue mock add
  ( "/file", _ ) -> respond
    -- image servers always send the length
    $ Wai.responseStream HTTP.status200 [ ( "Content-Length", show (BS.length content) ) ]
    $ \write flush -> do
      write (byteString firstHalf) >> flush
      threadDelay (mockPauseHalfway mock)
      -- Warp drops a connection whose body throws, and does not report this kind of error
      if mockHangUpHalfway mock
        then ioError (mkIOError resourceVanishedErrorType "hanging up halfway" Nothing Nothing)
        else write (byteString secondHalf)
  _ -> respond $ Wai.responseLBS HTTP.status404 [ ( "Content-Type", "text/plain" ) ] "Not Found"
  where
    content = mockFileContent mock

    ( firstHalf, secondHalf ) = BS.splitAt (BS.length content `div` 2) content

    parameter name = join (List.lookup name (Wai.queryString req))

    -- as sent: Wai would end it at its first ';'
    add
      = maybe "" (HTTP.urlDecode True . BS.drop 4)
      $ find ("add=" `BS.isPrefixOf`)
      $ BS.split '&'
      $ BS.drop 1 (Wai.rawQueryString req)

    -- we are the image server too, at whatever address the client reached us
    ownFile = "http://" <> fromMaybe "localhost" (Wai.requestHeaderHost req) <> "/file"

    signedAt clock
      = maybe
        False
        (\time -> abs (time - clock) <= 60)
        (readMaybe . BS.unpack =<< parameter "acttime")

    rpcReply clock = \case
      "server_stat" -> signed [ "server_time=" <> show clock ]
      act
        | not (signedAt clock) -> "KEY_EXPIRED"
        | otherwise -> reply act

    reply = \case
      -- the PKCS#12 file itself, never signed
      "get_cert" -> mockCertificate mock
      "client_login" -> signed (loginSettings mock)
      "client_settings"
        -> signed [ "host=127.0.0.1", "port=8080", "rpc_server_ip=" <> mockRPCServerIP mock ]
      "srfetch" -> signed [ ownFile ]
      "dlfetch" -> signed [ ownFile ]
      "get_blacklist" -> signed (mockBlacklist mock)
      act
        | act `elem` answeredOK -> signed []
        | otherwise -> "FAIL\nUnknown action: " <> act

    answeredOK = [ "still_alive", "client_start", "client_stop", "overload", "dlfails" ]

    -- the 1.6.6 server signs every OK reply with the client key
    signed payload
      = BS.unlines
        (("OK-1-" <> sha1Hex ("1-" <> mockClientKey mock <> foldMap ("\n" <>) payload)) : payload)