Files
simplex-chat/tests/RemoteTests.hs
T
533bfd8ff5 core, store: merge master into names (#8298)
* core, ui: validate short link type, show contact info for long addresses and rejected contacts (#8184)

* tests: short link type, QR code capacity and contact statuses

* core: validate the type of short links

* android, desktop: show contact info for addresses above QR code capacity

* ui: show chats with rejected contact requests

* tests: short link types with group, channel and contact data

* core: validate short link type against link data

* tests: fix short link data test

* tests: group data in invitation link before its first use

* tests: connect via address in contact profile with group link

* core: connect via contact address only with address links

* core: parse short link data once, by link type

* core: types of short link data parser

* core: test short link types and contact rejection, record app fixtures

* android, desktop: test contact info, link alerts and rejected contacts

* ios: test invalid link alerts and rejected contacts in the chat list

* desktop: contact info tests find texts without app resources

* ui: core responses of invalid link plans and a rejected contact request

* desktop: contact info tests provide the app bar handler

* core: normalise file and message keys in app test fixtures

* core: normalise deletion times in app test fixtures

* desktop: test that a QR code above capacity is not shared on tap

* core: test relay link checks and known channel refresh from link data

* libs: nodejs 7.1.4 (#8263)

* nodejs: live test reads the updated item under the key of 7.1 and 7.2 cores

* libs: nodejs 7.1.4

* mcp: session states coloured by what they need, green for working (#8265)

* mcp: session states in the colours of what they need: green working, orange waiting in the chat, red idle

* mcp: the space after waiting for you in the tests

* mcp: a session with a background command shows working in the background

* mcp: a readable README, and the roadmap lines of 0.3.0 (#8264)

* mcp: readme by what the plugin does for its users, roadmap lines of 0.3.0

* mcp: almost every waiting state

* mcp: reply, edit and react in one line

* mcp: flat layout without the avatar note

* mcp: sessions use flat layout

* mcp: shorter lines on answers, the Main group and approvals

* mcp: approvals line without the taps

* mcp: live stream line

* mcp: status line

* mcp: shorter lines

* mcp: 0.3.1 with simplex-chat 7.1.4 (#8266)

* docs: testing approaches of the codebase (#8255)

* docs: app changes come with app tests on the core's recorded responses (#8252)

* ci: decide the library claim from the written releases (#8137)

* ci: test the library claim when reads return the previous releases

* ci: decide the library claim from the written releases

* tests: record name fixtures after the channel join settles (#8250)

* core, ci: update sqlcipher-simple to 0.4.19.0 and simplexmq (#8270)

* update sqlcipher-simple to 0.4.19.0

* sqlcipher-simple from simplex-chat/sqlcipher-simple

* update simplexmq

* ci: restore source repositories only for the same cabal.project

* ci: keep restored source checkouts only at their pinned commits

* android, desktop, ios: copy markdown files with line breaks, and the whole file with one button (#8269)

* android, desktop: test copying lines from the markdown text view

* android, desktop: keep line breaks in text copied from markdown files

* android, desktop: check the last copied text in the markdown view test

* android, desktop, ios: button to copy the whole markdown file

* android, desktop: test the markdown file copy button

* android, desktop, ios: ask before copying markdown files over 128 KB

* android, desktop, ios: title the markdown copy alerts File too large

* ios: test the markdown file copy button

* android, desktop, ios: preview the markdown file view and test the copy limit

* android, desktop, ios: snapshot references of the markdown file view

* docs: names conditions describe upgradeable registry contracts (#8277)

* docs: names conditions describe upgradeable registry contracts

* docs: names conditions without the immutability after stabilization

---------

Co-authored-by: brenzi-agent <346870783+brenzi-agent@users.noreply.github.com>

* ci: reproducible Linux builds of 7.1 releases (#8276)

* ci: plan reproducible Linux builds of 7.1 releases

* ci: reproduce Linux builds with the cabal store path of releases

* ci: reproduce releases with the current reproduce script

* ci: build in the image with the cabal directory of releases

* ci: reproduce releases on the Ubuntu 24.04 runner

* ci: correct the failure history and rollout in the plan

---------

Co-authored-by: sh-agents <350651734+sh-agents@users.noreply.github.com>

* website: remove the webinar promotion (#8281)

* website: remove the webinar invitation from the home page

* website: redirect the livestream page to Wefunder

* mcp server: recall the chat history in a new agent session (#8141)

* mcp server: recall the chat history in a new agent session

* docs: chat history in receive for a new agent session

* mcp server: type the history page for the compiler

* mcp server: recall the chat history after a compaction too

* docs: history plan changes with the message helpers of master

Claude-Session: https://claude.ai/code/session_01AV2VpomCCQNciqggT9gr75

* docs: drop anchor remapping from the docs table of the history plan

Claude-Session: https://claude.ai/code/session_01AV2VpomCCQNciqggT9gr75

---------

Co-authored-by: brenzi-agent <346870783+brenzi-agent@users.noreply.github.com>

* core: prevent stalled join of channel subscribers to a new relay (#8239)

* core: save relay connection before requesting relay link data

* core: share relay connection creation between join and retry

* tests: connect to a re-added relay when its connection is saved late

* tests: delay only the relay connection record, not the command

* ci, tests: run all tests in CI (#8238)

* bots, tests: run broadcast bot test in CI

* tests: test moderation that arrives before the message

* ci, tests: run all tests in CI

* tests: update re-enabled tests, restore query plans, PostgreSQL schema from CI

* tests: remove CI skip helpers no longer used

* tests: expect XFTP AUTH error of cancelled standalone file

* tests: update query plans from CI

* tests: update query plans from CI

* tests: expect group history and member contacts in async group test

* tests: accept subscription summary after first events on restart

* tests: make AUTH and client timeout direct tests deterministic

* tests: keep bob's badge clock before renewal until the move back

* tests: keep the quota of 2 messages only on the member's receive queue

* tests: keep query plans files with repeated entries of one query

* tests: update query plans from CI

* tests: stop the host before a member requests to join with a badge

* tests: remove repeated entries of one query from query plans files

* tests: accept the refusal of an unknown remote host after its session code

* ci: state when the query plans test fails

* tests: skip multicast discovery on macOS CI runners

* tests: accept a remote host started with one local address

* tests: restore the client timeout test except its zero timeout

* tests: fail when a remote host prints another line than its other addresses

* ci: name the tests that overwrite generated files

* tests: move the badge clock after the restoring device arms its wake

* tests: keep both members on the quota server in the member inactivity test

* tests: accept subscription summaries in any order in the async group test

* tests: update query plans from CI

* tests: quota of 2 only on bob's queues in member inactivity test

* tests: connect to a deleted link after its queue is deleted

* core: save relay connection before requesting relay link data

* core: share relay connection creation between join and retry

* tests: connect to a re-added relay when its connection is saved late

* tests: delay only the relay connection record, not the command

* tests: record API fixtures on SQLite only

* core: update query plans

* ci: run PostgreSQL tests with the steps of build-linux

* desktop: prevent crash on Linux with bitmap and WOFF2 fallback fonts (#8288)

* desktop: prevent crash on Linux with bitmap and WOFF2 fallback fonts

* desktop: record time offsets and snapshots rendered with Skia m138

* desktop: name the time offset test, skip only a missing fc-cache, update plan

---------

Co-authored-by: sh-agents <350651734+sh-agents@users.noreply.github.com>

* core, directory: stop cancelled actions instead of continuing them (#8279)

* ci: retry npm install once after a failure (#8280)

* core: query plans of the store group tests that master now verifies

---------

Co-authored-by: brenzi-agent <346870783+brenzi-agent@users.noreply.github.com>
Co-authored-by: sh-agents <justcheckingifitwillwork@gmail.com>
Co-authored-by: sh-agents <350651734+sh-agents@users.noreply.github.com>
Co-authored-by: brenzi-agent <brenzi-agent@brenzi.ch>
Co-authored-by: Evgeny Poberezkin <evgeny@poberezkin.com>
2026-11-21 23:35:25 +00:00

746 lines
31 KiB
Haskell

{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module RemoteTests where
import ChatClient
import ChatTests.DBUtils
import ChatTests.Utils
import Control.Logger.Simple
import Control.Monad
import Control.Monad.Except (runExceptT)
import qualified Data.Aeson as J
import qualified Data.ByteString as B
import Data.ByteString.Builder (toLazyByteString)
import qualified Data.ByteString.Lazy.Char8 as LB
import Data.List (find, isPrefixOf)
import qualified Data.Map.Strict as M
import Data.Word (Word32)
import Simplex.Chat.Controller (ChatCommand (..), ChatConfig (..), versionNumber)
import Simplex.Chat.Files (safeFileNameStr)
import Simplex.Chat.Library.Commands (parseChatCommand)
import qualified Simplex.Chat.Controller as Controller
import Simplex.Chat.Mobile.File
import Simplex.Chat.Remote (remoteFilesFolder, validRemoteFileName)
import Simplex.Chat.Remote.Protocol (encryptEncodeHTTP2Body, parseDecryptHTTP2Body, remoteStoreFile)
import Simplex.Chat.Remote.Types
import qualified Simplex.Messaging.Crypto as C
import Simplex.Messaging.Crypto.File (CryptoFileArgs (..))
import Simplex.Messaging.Encoding (smpEncode)
import Simplex.Messaging.Encoding.String (strEncode)
import qualified Simplex.Messaging.TMap as TM
import Simplex.Messaging.Transport (TSbChainKeys (..))
import Simplex.Messaging.Transport.HTTP2 (HTTP2BodyChunk (..), getHTTP2Body)
import Simplex.Messaging.Util
import Simplex.RemoteControl.Types (RCCtrlAddress (..))
import System.FilePath (takeFileName, (</>))
import Test.Hspec hiding (it)
import UnliftIO
import UnliftIO.Concurrent
import UnliftIO.Directory
remoteTests :: SpecWith TestParams
remoteTests = describe "Remote" $ do
describe "/start remote host parser" $ do
it "parses iface name with a space followed by port=" $ \_ ->
parseChatCommand "/start remote host new addr=192.168.1.5 iface=\"Ethernet 2\" port=12345"
`shouldSatisfy` \case
Right (StartRemoteHost Nothing (Just (RCCtrlAddress _ "Ethernet 2")) (Just 12345)) -> True
_ -> False
describe "stored file name" $ do
it "rejects names with directory components" $ \_ ->
filter validRemoteFileName ["../x", "../../etc/passwd", "/etc/cron.d/x", "a/b", "x/", "", ".", ".."]
`shouldBe` []
it "accepts bare file names" $ \_ ->
filter (not . validRemoteFileName) ["test.pdf", "test_1.pdf", ".hidden", "a b.tar.gz"]
`shouldBe` []
it "sanitizes any name to a real file name" $ \_ ->
filter (not . sanitized) fileNames `shouldBe` []
it "sanitizes to a name with no directory components" $ \_ ->
filter (not . bareName) fileNames `shouldBe` []
describe "skipped keys" $ do
it "keeps the most recent skipped keys" $ \_ -> do
(_, pk) <- atomically . C.generateKeyPair =<< C.newRandom
let (ck, _) = C.sbcInit "" ("secret" :: B.ByteString)
sndCounter <- newTVarIO 0
rcvCounter <- newTVarIO 0
sndKey <- newTVarIO ck
rcvKey <- newTVarIO ck
skippedKeys <- newTVarIO M.empty
let rc = RemoteCrypto {sessionCode = "", sndCounter, rcvCounter, chainKeys = TSbChainKeys {sndKey, rcvKey}, skippedKeys, signatures = RSSign pk pk, compression = False}
receive corrId = eitherToMaybe <$> atomically (getRemoteRcvKeys rc corrId)
sent <- replicateM 1280 $ atomically $ getRemoteSndKeys rc
let sentKeys = M.fromList [(corrId, (cmdKN, fileKN)) | (corrId, cmdKN, fileKN) <- sent]
forM_ [256, 512 .. 1280] $ \corrId -> receive corrId `shouldReturn` M.lookup corrId sentKeys
M.size <$> readTVarIO skippedKeys `shouldReturn` 1024
receive 251 `shouldReturn` Nothing
receive 252 `shouldReturn` M.lookup 252 sentKeys
describe "body size limit" $ do
it "rejects encrypted body above limit without reading it" $ \_ -> do
rc <- testRemoteCrypto
chunks <- newIORef [smpEncode (1 :: Word32, 1025 :: Word32), "body"]
r <- parseDecryptChunks 1024 rc chunks
r `shouldSatisfy` \case
Left RPEInvalidSize -> True
_ -> False
readIORef chunks `shouldReturn` ["body"]
it "rejects decompressed body above limit" $ \_ -> do
rc <- testRemoteCrypto
(corrId, cmdKN, _) <- atomically $ getRemoteSndKeys rc
Right encBody <- runExceptT $ encryptEncodeHTTP2Body corrId cmdKN rc $ LB.replicate 1025 'a'
chunks <- newIORef $ LB.toChunks $ toLazyByteString encBody
r <- parseDecryptChunks 1024 rc chunks
r `shouldSatisfy` \case
Left (RPEInvalidBody _) -> True
_ -> False
describe "No compression" $ aroundWith (. ((False, False),)) runRemoteTests
describe "Mobile offers compression" $ aroundWith (. ((True, False),)) runRemoteTests
describe "Desktop offers compression" $ aroundWith (. ((False, True),)) runRemoteTests
describe "With compression" $ aroundWith (. ((True, True),)) runRemoteTests
where
fileNames :: [FilePath]
fileNames = ["", ".", "..", "...", "../x", "../../etc/passwd", "/etc/cron.d/x", "a/b", "x/", "test.pdf", ".hidden", "a b.tar.gz"]
sanitized n = let n' = safeFileNameStr n in n' /= "" && n' /= "." && n' /= ".."
bareName n = let n' = safeFileNameStr n in n' == takeFileName n'
runRemoteTests :: SpecWith ((Bool, Bool), TestParams)
runRemoteTests = do
describe "protocol handshake" $ do
it "connects with new pairing (stops mobile)" $ remoteHandshakeTest False
it "connects with new pairing (stops desktop)" $ remoteHandshakeTest True
it "connects with stored pairing" remoteHandshakeStoredTest
xitMacCI "connects with multicast discovery" remoteHandshakeDiscoverTest
it "refuses invalid client cert" remoteHandshakeRejectTest
it "connects with stored server bindings" storedBindingsTest
it "sends messages" remoteMessageTest
describe "remote files" $ do
it "store/get/send/receive files" remoteStoreFileTest
it "should send files from CLI without /store" remoteCLIFileTest
it "switches remote hosts" switchRemoteHostTest
it "indicates remote hosts" indicateRemoteHostTest
it "works with multiple profiles" multipleProfilesTest
-- * Chat commands
remoteHandshakeTest :: HasCallStack => Bool -> ((Bool, Bool), TestParams) -> IO ()
remoteHandshakeTest viaDesktop = testRemote $ \compress mobile desktop -> do
desktop ##> "/list remote hosts"
desktop <## "No remote hosts"
mobile ##> "/list remote ctrls"
mobile <## "No remote controllers"
startRemote compress mobile desktop
desktop ##> "/list remote hosts"
desktop <## "Remote hosts:"
desktop <## "1. Mobile (connected)"
mobile ##> "/list remote ctrls"
mobile <## "Remote controllers:"
mobile <## "1. My desktop (connected)"
if viaDesktop then stopDesktop mobile desktop else stopMobile mobile desktop
desktop ##> "/delete remote host 1"
desktop <## "ok"
desktop ##> "/list remote hosts"
desktop <## "No remote hosts"
mobile ##> "/delete remote ctrl 1"
mobile <## "ok"
mobile ##> "/list remote ctrls"
mobile <## "No remote controllers"
remoteHandshakeStoredTest :: HasCallStack => ((Bool, Bool), TestParams) -> IO ()
remoteHandshakeStoredTest = testRemote $ \compress mobile desktop -> do
logNote "Starting new session"
startRemote compress mobile desktop
stopMobile mobile desktop `catchAny` (logError . tshow)
logNote "Starting stored session"
startRemoteStored compress mobile desktop
stopDesktop mobile desktop `catchAny` (logError . tshow)
desktop ##> "/list remote hosts"
desktop <## "Remote hosts:"
desktop <## "1. Mobile"
mobile ##> "/list remote ctrls"
mobile <## "Remote controllers:"
mobile <## "1. My desktop"
logNote "Starting stored session again"
startRemoteStored compress mobile desktop
stopMobile mobile desktop `catchAny` (logError . tshow)
remoteHandshakeDiscoverTest :: HasCallStack => ((Bool, Bool), TestParams) -> IO ()
remoteHandshakeDiscoverTest = testRemote $ \compress mobile desktop -> do
logNote "Preparing new session"
startRemote compress mobile desktop
stopMobile mobile desktop `catchAny` (logError . tshow)
logNote "Starting stored session with multicast"
startRemoteDiscover compress mobile desktop
stopMobile mobile desktop `catchAny` (logError . tshow)
remoteHandshakeRejectTest :: HasCallStack => ((Bool, Bool), TestParams) -> IO ()
remoteHandshakeRejectTest = testRemote3 $ \compress mobile desktop mobileBob -> do
logNote "Starting new session"
startRemote compress mobile desktop
stopMobile mobile desktop
mobileBob ##> "/set device name MobileBob"
mobileBob <## "ok"
desktop ##> "/start remote host 1"
desktop <##. "remote host 1 started on "
(_, inv) <- getRemoteInvitation desktop
mobileBob ##> ("/connect remote ctrl " <> inv)
mobileBob <## ("connecting new remote controller: My desktop, v" <> versionNumber)
getTermLine mobileBob >>= \case
"new remote controller connected" -> do
mobileBob <## "Compare session code with controller and use:"
void $ getTermLine mobileBob
mobileBob ##> "/stop remote ctrl"
mobileBob <## "ok"
l -> l `shouldBe` "remote controller stopped: this link was used with another controller, please create a new link on the host"
-- the server remains active after rejecting invalid client
mobile ##> ("/connect remote ctrl " <> inv)
mobile <## ("connecting remote controller 1: My desktop, v" <> versionNumber)
desktop <## "remote host 1 connecting"
desktop <## "Compare session code with host:"
sessId <- getTermLine desktop
mobile <## "remote controller 1 connected"
mobile <## "Compare session code with controller and use:"
mobile <## ("/verify remote ctrl " <> sessId)
mobile ##> ("/verify remote ctrl " <> sessId)
mobile <## ("remote controller 1 session started with My desktop" <> compress)
desktop <## ("remote host 1 connected" <> compress)
stopMobile mobile desktop
storedBindingsTest :: HasCallStack => ((Bool, Bool), TestParams) -> IO ()
storedBindingsTest = testRemote $ \compress mobile desktop -> do
desktop ##> "/set device name My desktop"
desktop <## "ok"
mobile ##> "/set device name Mobile"
mobile <## "ok"
desktop ##> "/start remote host new"
started <- dropStrPrefix "new remote host started on " <$> getTermLine desktop
(addrs, _) <- getRemoteInvitation desktop
Just localAddress <- pure $ find ("127." `isPrefixOf`) $ takeWhile (/= ':') started : addrs
desktop ##> "/stop remote host new"
desktop <## "ok"
desktop ##> ("/start remote host new addr=" <> localAddress <> " iface=\"lo\" port=" <> remoteTestPort desktop)
desktop <## ("new remote host started on " <> localAddress <> ":" <> remoteTestPort desktop)
(_, inv) <- getRemoteInvitation desktop
mobile ##> ("/connect remote ctrl " <> inv)
mobile <## ("connecting new remote controller: My desktop, v" <> versionNumber)
desktop <## "new remote host connecting"
mobile <## "new remote controller connected"
verifyRemoteCtrl mobile desktop
mobile <## ("remote controller 1 session started with My desktop" <> compress)
desktop <## "new remote host 1 added: Mobile"
desktop <## ("remote host 1 connected" <> compress)
desktop ##> "/list remote hosts"
desktop <## "Remote hosts:"
desktop <##. "1. Mobile (connected) ["
stopDesktop mobile desktop
desktop ##> "/list remote hosts"
desktop <## "Remote hosts:"
desktop <##. "1. Mobile ["
-- TODO: more parser tests
remoteMessageTest :: HasCallStack => ((Bool, Bool), TestParams) -> IO ()
remoteMessageTest = testRemote3 $ \compress mobile desktop bob -> do
startRemote compress mobile desktop
contactBob desktop bob
logNote "sending messages"
desktop #> "@bob hello there 🙂"
bob <# "alice> hello there 🙂"
bob #> "@alice hi"
desktop <# "bob> hi"
logNote "post-remote checks"
stopMobile mobile desktop
mobile ##> "/contacts"
mobile <## "bob (Bob)"
bob ##> "/contacts"
bob <## "alice (Alice)"
desktop ##> "/contacts"
-- empty contact list on desktop-local
threadDelay 1000000
logNote "done"
remoteStoreFileTest :: HasCallStack => ((Bool, Bool), TestParams) -> IO ()
remoteStoreFileTest =
testRemote3 $ \compress mobile desktop bob ->
withXFTPServer mobile $ do
let mobileFiles = tmpFile mobile "mobile_files"
mobile ##> ("/_files_folder " <> mobileFiles)
mobile <## "ok"
let desktopFiles = tmpFile desktop "desktop_files"
desktop ##> ("/_files_folder " <> desktopFiles)
desktop <## "ok"
let desktopHostFiles = tmpFile desktop "remote_hosts_data"
desktop ##> ("/remote_hosts_folder " <> desktopHostFiles)
desktop <## "ok"
let bobFiles = tmpFile bob "bob_files"
bob ##> ("/_files_folder " <> bobFiles)
bob <## "ok"
startRemote compress mobile desktop
contactBob desktop bob
rhs <- readTVarIO (Controller.remoteHostSessions $ chatController desktop)
(rhClient, desktopHostStore) <- case M.lookup (RHId 1) rhs of
Just (_, RHSessionConnected {rhClient, storePath}) ->
pure (rhClient, desktopHostFiles </> storePath </> remoteFilesFolder)
_ -> fail "Host session 1 should be started"
desktop ##> "/store remote file 1 tests/fixtures/test.pdf"
desktop <## "file test.pdf stored on remote host 1"
src <- B.readFile "tests/fixtures/test.pdf"
B.readFile (mobileFiles </> "test.pdf") `shouldReturn` src
B.readFile (desktopHostStore </> "test.pdf") `shouldReturn` src
desktop ##> "/store remote file 1 tests/fixtures/test.pdf"
desktop <## "file test_1.pdf stored on remote host 1"
B.readFile (mobileFiles </> "test_1.pdf") `shouldReturn` src
B.readFile (desktopHostStore </> "test_1.pdf") `shouldReturn` src
desktop ##> "/store remote file 1 encrypt=on tests/fixtures/test.pdf"
desktop <## "file test_2.pdf stored on remote host 1"
Just cfArgs@(CFArgs key nonce) <- J.decode . LB.pack <$> getTermLine desktop
chatReadFile (mobileFiles </> "test_2.pdf") (strEncode key) (strEncode nonce) `shouldReturn` Right (LB.fromStrict src)
chatReadFile (desktopHostStore </> "test_2.pdf") (strEncode key) (strEncode nonce) `shouldReturn` Right (LB.fromStrict src)
-- the host rejects a traversal name before draining the attachment; only calling the protocol
-- directly can put such a name on the wire, as /store remote file sanitizes it controller-side
runExceptT (remoteStoreFile rhClient "tests/fixtures/test.pdf" "../x") >>= \case
Left (RPEInvalidBody _) -> pure ()
r -> fail $ "expected RPEInvalidBody, got " <> show r
doesFileExist (tmpFile mobile "x") `shouldReturn` False
-- the undrained attachment did not break the session
desktop ##> "/store remote file 1 tests/fixtures/test.pdf"
desktop <## "file test_3.pdf stored on remote host 1"
B.readFile (mobileFiles </> "test_3.pdf") `shouldReturn` src
removeFile (desktopHostStore </> "test_1.pdf")
removeFile (desktopHostStore </> "test_2.pdf")
-- cannot get file before it is used
desktop ##> "/get remote file 1 {\"userId\": 1, \"fileId\": 1, \"sent\": true, \"fileSource\": {\"filePath\": \"test_1.pdf\"}}"
hostError desktop "SEFileNotFound"
-- send file not encrypted locally on mobile host
desktop ##> "/_send @2 json [{\"filePath\": \"test_1.pdf\", \"msgContent\": {\"type\": \"file\", \"text\": \"sending a file\"}}]"
desktop <# "@bob sending a file"
desktop <# "/f @bob test_1.pdf"
desktop <## "use /fc 1 to cancel sending"
bob <# "alice> sending a file"
bob <# "alice> sends file test_1.pdf (266.0 KiB / 272376 bytes)"
bob <## "use /fr 1 [<dir>/ | <path>] to receive it"
bob ##> "/fr 1"
concurrentlyN_
[ do
desktop <## "completed uploading file 1 (test_1.pdf) for bob",
do
bob
<### [ "saving file 1 from alice to test_1.pdf",
"started receiving file 1 (test_1.pdf) from alice"
]
bob <## "completed receiving file 1 (test_1.pdf) from alice"
]
B.readFile (bobFiles </> "test_1.pdf") `shouldReturn` src
-- returns error for inactive user
desktop ##> "/get remote file 1 {\"userId\": 2, \"fileId\": 1, \"sent\": true, \"fileSource\": {\"filePath\": \"test_1.pdf\"}}"
hostError desktop "CEDifferentActiveUser"
-- returns error with incorrect file ID
desktop ##> "/get remote file 1 {\"userId\": 1, \"fileId\": 2, \"sent\": true, \"fileSource\": {\"filePath\": \"test_1.pdf\"}}"
hostError desktop "SEFileNotFound"
-- gets file
doesFileExist (desktopHostStore </> "test_1.pdf") `shouldReturn` False
desktop ##> "/get remote file 1 {\"userId\": 1, \"fileId\": 1, \"sent\": true, \"fileSource\": {\"filePath\": \"test_1.pdf\"}}"
desktop <## "ok"
B.readFile (desktopHostStore </> "test_1.pdf") `shouldReturn` src
-- send file encrypted locally on mobile host
desktop ##> ("/_send @2 json [{\"fileSource\": {\"filePath\":\"test_2.pdf\", \"cryptoArgs\": " <> LB.unpack (J.encode cfArgs) <> "}, \"msgContent\": {\"type\": \"file\", \"text\": \"\"}}]")
desktop <# "/f @bob test_2.pdf"
desktop <## "use /fc 2 to cancel sending"
bob <# "alice> sends file test_2.pdf (266.0 KiB / 272376 bytes)"
bob <## "use /fr 2 [<dir>/ | <path>] to receive it"
bob ##> "/fr 2"
concurrentlyN_
[ do
desktop <## "completed uploading file 2 (test_2.pdf) for bob",
do
bob
<### [ "saving file 2 from alice to test_2.pdf",
"started receiving file 2 (test_2.pdf) from alice"
]
bob <## "completed receiving file 2 (test_2.pdf) from alice"
]
B.readFile (bobFiles </> "test_2.pdf") `shouldReturn` src
-- receive file via remote host
copyFile "./tests/fixtures/test.jpg" (bobFiles </> "test.jpg")
bob #> "/f @alice test.jpg"
bob <## "use /fc 3 to cancel sending"
desktop <# "bob> sends file test.jpg (136.5 KiB / 139737 bytes)"
desktop <## "use /fr 3 [<dir>/ | <path>] to receive it"
desktop ##> "/fr 3 encrypt=on"
concurrentlyN_
[ do
bob <## "completed uploading file 3 (test.jpg) for alice",
do
desktop
<### [ "saving file 3 from bob to test.jpg",
"started receiving file 3 (test.jpg) from bob"
]
desktop <## "completed receiving file 3 (test.jpg) from bob"
]
Just cfArgs'@(CFArgs key' nonce') <- J.decode . LB.pack <$> getTermLine desktop
desktop <## "File received to connected remote host 1"
desktop <## "To download to this device use:"
getCmd <- getTermLine desktop
getCmd `shouldBe` ("/get remote file 1 {\"userId\":1,\"fileId\":3,\"sent\":false,\"fileSource\":{\"filePath\":\"test.jpg\",\"cryptoArgs\":" <> LB.unpack (J.encode cfArgs') <> "}}")
src' <- B.readFile (bobFiles </> "test.jpg")
chatReadFile (mobileFiles </> "test.jpg") (strEncode key') (strEncode nonce') `shouldReturn` Right (LB.fromStrict src')
doesFileExist (desktopHostStore </> "test.jpg") `shouldReturn` False
-- returns error with incorrect key
desktop ##> "/get remote file 1 {\"userId\": 1, \"fileId\": 3, \"sent\": false, \"fileSource\": {\"filePath\": \"test.jpg\", \"cryptoArgs\": null}}"
hostError desktop "SEFileNotFound"
doesFileExist (desktopHostStore </> "test.jpg") `shouldReturn` False
desktop ##> getCmd
desktop <## "ok"
chatReadFile (desktopHostStore </> "test.jpg") (strEncode key') (strEncode nonce') `shouldReturn` Right (LB.fromStrict src')
stopMobile mobile desktop
where
hostError cc err = do
r <- getTermLine cc
r `shouldStartWith` "remote host 1 error"
r `shouldContain` err
remoteCLIFileTest :: HasCallStack => ((Bool, Bool), TestParams) -> IO ()
remoteCLIFileTest = testRemote3 $ \compress mobile desktop bob -> withXFTPServer mobile $ do
let mobileFiles = tmpFile mobile "mobile_files"
mobile ##> ("/_files_folder " <> mobileFiles)
mobile <## "ok"
let bobFiles = tmpFile bob "bob_files/"
createDirectoryIfMissing True bobFiles
let desktopHostFiles = tmpFile desktop "remote_hosts_data"
desktop ##> ("/remote_hosts_folder " <> desktopHostFiles)
desktop <## "ok"
startRemote compress mobile desktop
contactBob desktop bob
rhs <- readTVarIO (Controller.remoteHostSessions $ chatController desktop)
desktopHostStore <- case M.lookup (RHId 1) rhs of
Just (_, RHSessionConnected {storePath}) -> pure $ desktopHostFiles </> storePath </> remoteFilesFolder
_ -> fail "Host session 1 should be started"
mobileName <- userName mobile
bob #> ("/f @" <> mobileName <> " " <> "tests/fixtures/test.pdf")
bob <## "use /fc 1 to cancel sending"
desktop <# "bob> sends file test.pdf (266.0 KiB / 272376 bytes)"
desktop <## "use /fr 1 [<dir>/ | <path>] to receive it"
desktop ##> "/fr 1"
concurrentlyN_
[ do
bob <## "completed uploading file 1 (test.pdf) for alice",
do
desktop
<### [ "saving file 1 from bob to test.pdf",
"started receiving file 1 (test.pdf) from bob"
]
desktop <## "completed receiving file 1 (test.pdf) from bob"
]
desktop <## "File received to connected remote host 1"
desktop <## "To download to this device use:"
getCmd <- getTermLine desktop
src <- B.readFile "tests/fixtures/test.pdf"
B.readFile (mobileFiles </> "test.pdf") `shouldReturn` src
doesFileExist (desktopHostStore </> "test.pdf") `shouldReturn` False
desktop ##> getCmd
desktop <## "ok"
B.readFile (desktopHostStore </> "test.pdf") `shouldReturn` src
desktop `send` "/f @bob tests/fixtures/test.jpg"
desktop <# "/f @bob test.jpg"
desktop <## "use /fc 2 to cancel sending"
bob <# "alice> sends file test.jpg (136.5 KiB / 139737 bytes)"
bob <## "use /fr 2 [<dir>/ | <path>] to receive it"
bob ##> ("/fr 2 " <> bobFiles)
concurrentlyN_
[ do
desktop <## "completed uploading file 2 (test.jpg) for bob",
do
bob
<### [ ConsoleString ("saving file 2 from alice to " <> bobFiles <> "test.jpg"),
"started receiving file 2 (test.jpg) from alice"
]
bob <## "completed receiving file 2 (test.jpg) from alice"
]
src' <- B.readFile "tests/fixtures/test.jpg"
B.readFile (mobileFiles </> "test.jpg") `shouldReturn` src'
B.readFile (desktopHostStore </> "test.jpg") `shouldReturn` src'
B.readFile (bobFiles </> "test.jpg") `shouldReturn` src'
stopMobile mobile desktop
switchRemoteHostTest :: HasCallStack => ((Bool, Bool), TestParams) -> IO ()
switchRemoteHostTest = testRemote3 $ \compress mobile desktop bob -> do
startRemote compress mobile desktop
contactBob desktop bob
desktop ##> "/contacts"
desktop <## "bob (Bob)"
desktop ##> "/switch remote host local"
desktop <## "Using local profile"
desktop ##> "/contacts"
desktop ##> "/switch remote host 1"
desktop <## "Using remote host 1 (Mobile)"
desktop ##> "/contacts"
desktop <## "bob (Bob)"
desktop ##> "/switch remote host 123"
desktop <## "no remote host 123"
stopDesktop mobile desktop
desktop ##> "/contacts"
desktop ##> "/switch remote host 1"
desktop <## "remote host 1 error: RHEInactive"
desktop ##> "/contacts"
indicateRemoteHostTest :: HasCallStack => ((Bool, Bool), TestParams) -> IO ()
indicateRemoteHostTest = testRemote4 $ \compress mobile desktop bob cath -> do
connectUsers desktop cath
startRemote compress mobile desktop
contactBob desktop bob
-- remote contact -> remote host
bob #> "@alice hi"
desktop <#. "bob> hi"
-- local -> remote
cath #> "@alice_desktop hello"
(desktop, "[local] ") ^<# "cath> hello"
-- local -> local
desktop ##> "/switch remote host local"
desktop <## "Using local profile"
desktop <##> cath
-- local -> remote
bob #> "@alice what's up?"
(desktop, "[remote: 1] ") ^<# "bob> what's up?"
-- local -> local after disconnect
stopDesktop mobile desktop
desktop <##> cath
cath <##> desktop
multipleProfilesTest :: HasCallStack => ((Bool, Bool), TestParams) -> IO ()
multipleProfilesTest = testRemote4 $ \compress mobile desktop bob cath -> do
connectUsers desktop cath
desktop ##> "/create user desk_bottom"
desktop <## "user profile: desk_bottom"
desktop <## "use /p <name> [<bio>] to change it"
desktop ##> "/users"
desktop <## "alice_desktop (Alice Desktop)"
desktop <## "desk_bottom (active)"
startRemote compress mobile desktop
contactBob desktop bob
desktop ##> "/users"
desktop <## "alice (Alice) (active)"
desktop ##> "/create user alt_alice"
desktop <## "user profile: alt_alice"
desktop <## "use /p <name> [<bio>] to change it"
desktop ##> "/users"
desktop <## "alice (Alice)"
desktop <## "alt_alice (active)"
desktop ##> "/user"
desktop <## "user profile: alt_alice"
desktop <## "use /p <name> [<bio>] to change it"
bob #> "@alice hi"
(desktop, "[user: alice] ") ^<# "bob> hi"
cath #> "@alice_desktop hello"
(desktop, "[local, user: alice_desktop] ") ^<# "cath> hello"
desktop ##> "/switch remote host local"
desktop <## "Using local profile"
desktop ##> "/user"
desktop <## "user profile: desk_bottom"
desktop <## "use /p <name> [<bio>] to change it"
bob #> "@alice hey"
(desktop, "[remote: 1, user: alice] ") ^<# "bob> hey"
stopDesktop mobile desktop
-- * Utils
testRemote :: HasCallStack => (String -> TestCC -> TestCC -> IO()) -> ((Bool, Bool), TestParams) -> IO ()
testRemote test ((mobileCompression, desktopCompression), ps) =
withNewTestChatCfg ps testCfg {remoteCompression = mobileCompression} "mobile" aliceProfile $ \mobile ->
withNewTestChatCfg ps testCfg {remoteCompression = desktopCompression} "desktop" aliceDesktopProfile $ \desktop ->
let compress = " (" <> (if mobileCompression && desktopCompression then "with" else "no") <> " compression)"
in test compress mobile desktop
testRemote3 :: HasCallStack => (String -> TestCC -> TestCC -> TestCC -> IO()) -> ((Bool, Bool), TestParams) -> IO ()
testRemote3 test ps =
testRemote
(\compress mobile desktop -> withNewTestChat (snd ps) "bob" bobProfile $ test compress mobile desktop)
ps
testRemote4 :: HasCallStack => (String -> TestCC -> TestCC -> TestCC -> TestCC -> IO()) -> ((Bool, Bool), TestParams) -> IO ()
testRemote4 test ps =
testRemote3
(\compress mobile desktop bob -> withNewTestChat (snd ps) "cath" cathProfile $ test compress mobile desktop bob)
ps
startRemote :: String -> TestCC -> TestCC -> IO ()
startRemote compress mobile desktop = do
desktop ##> "/set device name My desktop"
desktop <## "ok"
mobile ##> "/set device name Mobile"
mobile <## "ok"
desktop ##> "/start remote host new"
desktop <##. "new remote host started on "
(_, inv) <- getRemoteInvitation desktop
mobile ##> ("/connect remote ctrl " <> inv)
mobile <## ("connecting new remote controller: My desktop, v" <> versionNumber)
desktop <## "new remote host connecting"
mobile <## "new remote controller connected"
verifyRemoteCtrl mobile desktop
mobile <## ("remote controller 1 session started with My desktop" <> compress)
desktop <## "new remote host 1 added: Mobile"
desktop <## ("remote host 1 connected" <> compress)
startRemoteStored :: String -> TestCC -> TestCC -> IO ()
startRemoteStored compress mobile desktop = do
desktop ##> "/start remote host 1"
desktop <##. "remote host 1 started on "
(_, inv) <- getRemoteInvitation desktop
mobile ##> ("/connect remote ctrl " <> inv)
mobile <## ("connecting remote controller 1: My desktop, v" <> versionNumber)
desktop <## "remote host 1 connecting"
mobile <## "remote controller 1 connected"
verifyRemoteCtrl mobile desktop
mobile <## ("remote controller 1 session started with My desktop" <> compress)
desktop <## ("remote host 1 connected" <> compress)
startRemoteDiscover :: String -> TestCC -> TestCC -> IO ()
startRemoteDiscover compress mobile desktop = do
desktop ##> "/start remote host 1 multicast=on"
desktop <##. "remote host 1 started on "
void $ getRemoteInvitation desktop -- will use multicast instead
mobile ##> "/find remote ctrl"
mobile <## "ok"
mobile <## ("remote controller 1 found: My desktop, v" <> versionNumber)
mobile <## "use /confirm remote ctrl 1 to connect"
mobile ##> "/confirm remote ctrl 1"
mobile <## ("connecting remote controller 1: My desktop, v" <> versionNumber)
desktop <## "remote host 1 connecting"
mobile <## "remote controller 1 connected"
verifyRemoteCtrl mobile desktop
mobile <## ("remote controller 1 session started with My desktop" <> compress)
desktop <## ("remote host 1 connected" <> compress)
getRemoteInvitation :: HasCallStack => TestCC -> IO ([String], String)
getRemoteInvitation desktop = do
addrs <- getTermLine desktop >>= \case
"Remote session invitation:" -> pure []
l -> evaluate (words $ dropStrPrefix "other addresses: " l) <* desktop <## "Remote session invitation:"
(addrs,) <$> getTermLine desktop
verifyRemoteCtrl :: TestCC -> TestCC -> IO ()
verifyRemoteCtrl mobile desktop = do
desktop <## "Compare session code with host:"
sessId <- getTermLine desktop
mobile <## "Compare session code with controller and use:"
mobile <## ("/verify remote ctrl " <> sessId)
mobile ##> ("/verify remote ctrl " <> sessId)
contactBob :: TestCC -> TestCC -> IO ()
contactBob desktop bob = do
logNote "exchanging contacts"
bob ##> "/c"
inv' <- getInvitation bob
desktop ##> ("/c " <> inv')
desktop <## "confirmation sent!"
concurrently_
(desktop <## "bob (Bob): contact is connected")
(bob <## "alice (Alice): contact is connected")
stopDesktop :: HasCallStack => TestCC -> TestCC -> IO ()
stopDesktop mobile desktop = do
logWarn "stopping via desktop"
desktop ##> "/stop remote host 1"
desktop <## "ok"
eventually 3 $ mobile <## "remote controller stopped"
stopMobile :: HasCallStack => TestCC -> TestCC -> IO ()
stopMobile mobile desktop = do
logWarn "stopping via mobile"
mobile ##> "/stop remote ctrl"
mobile <## "ok"
eventually 3 $ desktop <## "remote host 1 stopped"
-- | Run action with extended timeout
eventually :: Int -> IO a -> IO a
eventually retries action =
tryAny action >>= \case
-- TODO: only catch timeouts
Left err | retries == 0 -> throwIO err
Left _ -> eventually (retries - 1) action
Right r -> pure r
newtype TestBody = TestBody (IORef [B.ByteString])
instance HTTP2BodyChunk TestBody where
getBodyChunk (TestBody chunks) = atomicModifyIORef' chunks $ \case
c : cs -> (cs, c)
[] -> ([], "")
getBodySize _ = Nothing
testRemoteCrypto :: IO RemoteCrypto
testRemoteCrypto = do
drg <- C.newRandom
(_, idPrivKey) <- atomically $ C.generateKeyPair drg
(_, sessPrivKey) <- atomically $ C.generateKeyPair drg
let (chainKey, _) = C.sbcInit "" ("secret" :: B.ByteString)
chainKeys <- TSbChainKeys <$> newTVarIO chainKey <*> newTVarIO chainKey
sndCounter <- newTVarIO 0
rcvCounter <- newTVarIO 0
skippedKeys <- TM.emptyIO
pure RemoteCrypto {sessionCode = "", sndCounter, rcvCounter, chainKeys, skippedKeys, signatures = RSSign {idPrivKey, sessPrivKey}, compression = True}
parseDecryptChunks :: Int -> RemoteCrypto -> IORef [B.ByteString] -> IO (Either RemoteProtocolError ())
parseDecryptChunks maxSize rc chunks = do
body <- getHTTP2Body (TestBody chunks) 0
runExceptT . void $ parseDecryptHTTP2Body maxSize rc (TestBody chunks) body