Files
simplex-chat/tests/WebRTCTests.hs
Evgeny Poberezkin a2e5733be6 core: update/fix webrtc frame encryption function to return error (#1950)
* core: update/fix webrtc frame encryption function to return error

* ios: update C header

* more tests
2023-02-24 20:55:59 +00:00

39 lines
2.0 KiB
Haskell

module WebRTCTests where
import Control.Monad.Except
import Crypto.Random (getRandomBytes)
import qualified Data.ByteString.Base64.URL as U
import qualified Data.ByteString.Char8 as B
import Simplex.Chat.Mobile.WebRTC
import Test.Hspec
webRTCTests :: Spec
webRTCTests = describe "WebRTC crypto" $ do
it "encrypts and decrypts media" $ do
key <- U.encode <$> getRandomBytes 32
frame <- getRandomBytes 1000
Right frame' <- runExceptT $ chatEncryptMedia key $ frame <> B.replicate reservedSize '\NUL'
B.length frame' `shouldBe` B.length frame + reservedSize
Right frame'' <- runExceptT $ chatDecryptMedia key frame'
frame'' `shouldBe` frame <> B.replicate reservedSize '\NUL'
it "should fail on invalid frame size" $ do
key <- U.encode <$> getRandomBytes 32
frame <- getRandomBytes 10
runExceptT (chatEncryptMedia key frame) `shouldReturn` Left "frame has no [reserved space] IV and/or auth tag"
runExceptT (chatDecryptMedia key frame) `shouldReturn` Left "frame has no [reserved space] IV and/or auth tag"
it "should fail on invalid key" $ do
let key = B.replicate 32 '#'
frame <- (<> B.replicate reservedSize '\NUL') <$> getRandomBytes 100
runExceptT (chatEncryptMedia key frame) `shouldReturn` Left "invalid key: invalid character at offset: 0"
runExceptT (chatDecryptMedia key frame) `shouldReturn` Left "invalid key: invalid character at offset: 0"
it "should fail on invalid auth tag" $ do
key <- U.encode <$> getRandomBytes 32
frame <- getRandomBytes 1000
Right frame' <- runExceptT $ chatEncryptMedia key $ frame <> B.replicate reservedSize '\NUL'
Right frame'' <- runExceptT $ chatDecryptMedia key frame'
frame'' `shouldBe` frame <> B.replicate reservedSize '\NUL'
let (rest, iv) = B.splitAt (B.length frame' - ivSize) frame
(encFrame, _tag) = B.splitAt (B.length rest - authTagSize) rest
badFrame = encFrame <> B.replicate authTagSize '\NUL' <> iv
runExceptT (chatDecryptMedia key badFrame) `shouldReturn` Left "AESDecryptError"