{-# OPTIONS -Wno-incomplete-patterns -Wno-ambiguous-fields #-}

-- This file is part of the Wire Server implementation.
--
-- Copyright (C) 2025 Wire Swiss GmbH <opensource@wire.com>
--
-- This program is free software: you can redistribute it and/or modify it under
-- the terms of the GNU Affero General Public License as published by the Free
-- Software Foundation, either version 3 of the License, or (at your option) any
-- later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
-- details.
--
-- You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see <https://www.gnu.org/licenses/>.

module Test.Apps where

import API.Brig as Brig
import qualified API.BrigInternal as BrigI
import API.Common
import API.Galley
import API.Gundeck
import Data.Aeson.QQ.Simple
import qualified Data.Map as Map
import qualified Data.Set as Set
import MLS.Util
import Notifications
import SetupHelpers
import System.Random (randomRIO)
import Testlib.Prelude

testCreateGetApp :: (HasCallStack) => Domain -> App ()
testCreateGetApp :: HasCallStack => Domain -> App ()
testCreateGetApp Domain
sameOrOtherDomain = do
  domainA <- Domain -> App Value
forall a. (MakesValue a, HasCallStack) => a -> App Value
make Domain
OwnDomain
  domainB <- make sameOrOtherDomain

  (owner, tid, [regularMember]) <- createTeam domainA 2
  let new :: NewApp =
        def
          { name = "chappie",
            description = "some description of this app",
            category = "ai"
          }

  -- Regular team member can't create apps
  bindResponse (createApp regularMember tid new) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
403
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"label" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"app-no-permission"

  -- Get the last team notification ID before creating the app
  lastTeamNotif <- bindResponse (getTeamNotifications regularMember Nothing) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"notifications.-1.id" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString

  -- Owner can create an app
  (appId, cookie) <- withWebSockets [owner, regularMember] \[WebSocket
wsOwner, WebSocket
wsRegularMember] -> do
    App Response
-> (Response -> App (String, String)) -> App (String, String)
forall a.
HasCallStack =>
App Response -> (Response -> App a) -> App a
bindResponse (Value -> String -> NewApp -> App Response
forall creator.
MakesValue creator =>
creator -> String -> NewApp -> App Response
createApp Value
owner String
tid NewApp
new) ((Response -> App (String, String)) -> App (String, String))
-> (Response -> App (String, String)) -> App (String, String)
forall a b. (a -> b) -> a -> b
$ \Response
resp -> do
      Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
      appId <- Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user.id" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString
      cookie <- resp.json %. "cookie" & asString
      _ <- do
        let predicate a
payload = do
              typ <- a
payload a -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"payload.0.type" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString
              pure $ typ == "team.member-join"
        void $ awaitMatch predicate wsOwner
        void $ assertNoEvent 5 wsRegularMember
      pure (appId, cookie)

  -- Verify that the team.member-join event is in the team notifications queue
  bindResponse (getTeamNotifications regularMember (Just lastTeamNotif)) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    -- First notification is `lastTeamNotif`, we can ignore that one.
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"notifications.1.payload.0.type" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"team.member-join"
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"notifications.1.payload.0.team" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
tid
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"notifications.1.payload.0.data.user" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
appId

  -- App user should have type "app"
  let appIdObject = [Pair] -> Value
object [String
"domain" String -> Value -> Pair
forall a. ToJSON a => String -> a -> Pair
.= Value
domainA, String
"id" String -> String -> Pair
forall a. ToJSON a => String -> a -> Pair
.= String
appId]
  bindResponse (getUser owner appIdObject) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"type" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"app"

  -- getApp, getApps
  bindResponse (getApp owner tid appId) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
  bindResponse (getApps owner tid) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    App Value -> App ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (App Value -> App ()) -> App Value -> App ()
forall a b. (a -> b) -> a -> b
$ Response
resp.json Maybe Value -> (Maybe Value -> App [Value]) -> App [Value]
forall a b. a -> (a -> b) -> b
& Maybe Value -> App [Value]
forall a. (HasCallStack, MakesValue a) => a -> App [Value]
asList App [Value] -> ([Value] -> App Value) -> App Value
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= [Value] -> App Value
forall (t :: * -> *) a. (HasCallStack, Foldable t) => t a -> App a
assertOne
  bindResponse (createApp owner tid (new {name = "fmappie"})) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
  bindResponse (getApps owner tid) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    apps <- Response
resp.json Maybe Value -> (Maybe Value -> App [Value]) -> App [Value]
forall a b. a -> (a -> b) -> b
& Maybe Value -> App [Value]
forall a. (HasCallStack, MakesValue a) => a -> App [Value]
asList
    name1 <- apps %. "0.name"
    name2 <- apps %. "1.name"
    [name1, name2] `shouldMatchSet` ["chappie", "fmappie"]

  -- Creator should have type "regular"
  bindResponse (getUser owner owner) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"type" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"regular"

  void $ bindResponse (renewToken domainA cookie) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
appId
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"token_type" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"Bearer"
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"access_token" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString

  -- Get app for the app created above succeeds
  void $ getApp regularMember tid appId `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    (Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"name") App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"chappie"
    (Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"app.description") App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"some description of this app"
    (Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"app.category") App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"ai"

  -- A teamless user can't get the app
  outsideUser <- randomUser domainB (def {BrigI.team = False})
  bindResponse (getApp outsideUser tid appId) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
404

  (owner2, tid2, [regularMember2]) <- createTeam domainB 2
  bindResponse (getApp owner2 tid appId) $ \Response
resp -> Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
404
  bindResponse (getApp owner2 tid2 appId) $ \Response
resp -> Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
404
  bindResponse (getApp regularMember2 tid appId) $ \Response
resp -> Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
404

  -- Get app on remote apps gives 404 not found.
  void $ getApp owner2 tid appId `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
404
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"label" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"not-found"

  -- Category can be any text; sanitization must happen by clients.
  void $ bindResponse (createApp owner tid new {category = "notinenum"}) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    String -> Value -> App Value -> App Response
forall owner member.
(HasCallStack, MakesValue owner, MakesValue member) =>
String -> owner -> member -> App Response
deleteTeamMember String
tid Value
owner (Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user") App Response -> (Response -> App ()) -> App ()
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= HasCallStack => Response -> App ()
Response -> App ()
assertSuccess

testRefreshAppCookie :: (HasCallStack) => App ()
testRefreshAppCookie :: HasCallStack => App ()
testRefreshAppCookie = do
  (alice, tid, [bob]) <- Domain -> Int -> App (Value, String, [Value])
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> Int -> App (Value, String, [Value])
createTeam Domain
OwnDomain Int
2
  charlie <- randomUser OwnDomain def

  let new = NewApp
forall a. Default a => a
def {name = "flexo"} :: NewApp
      goodPassword = Value -> Maybe Value
forall a. a -> Maybe a
Just ([Pair] -> Value
object [String
"password" String -> String -> Pair
forall a. ToJSON a => String -> a -> Pair
.= String
defPassword])

  (appId, cookie) <- bindResponse (createApp alice tid new) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    appId <- Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user.id" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString
    cookie <- resp.json %. "cookie" & asString
    pure (appId, cookie)

  bindResponse (refreshAppCookie bob tid appId goodPassword) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
403
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"label" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"app-no-permission"

  bindResponse (refreshAppCookie charlie tid appId goodPassword) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
403
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"label" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"app-no-permission"

  forM_
    [ (Nothing, 415),
      (Just Null, 400),
      (Just (object []), 403),
      (Just (object ["password" .= "this is not a good password"]), 403)
    ]
    $ \(Maybe Value
badPassword, Int
stat) -> do
      -- the status codes and error labels differ here, but the
      -- important thing is that the request fails.
      Value -> String -> String -> Maybe Value -> App Response
forall u.
MakesValue u =>
u -> String -> String -> Maybe Value -> App Response
refreshAppCookie Value
alice String
tid String
appId Maybe Value
badPassword App Response -> (Response -> App ()) -> App ()
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= HasCallStack => Int -> Response -> App ()
Int -> Response -> App ()
assertStatus Int
stat

  cookie' <- bindResponse (refreshAppCookie alice tid appId goodPassword) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"cookie" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString

  renewToken OwnDomain cookie `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
403

  renewToken OwnDomain cookie' `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
appId
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"token_type" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"Bearer"
    App String -> App ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (App String -> App ()) -> App String -> App ()
forall a b. (a -> b) -> a -> b
$ Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"access_token" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString

testDeleteAppFromTeam :: (HasCallStack) => App ()
testDeleteAppFromTeam :: HasCallStack => App ()
testDeleteAppFromTeam = do
  domain <- Domain -> App Value
forall a. (MakesValue a, HasCallStack) => a -> App Value
make Domain
OwnDomain
  (owner, tid, [regularMember]) <- createTeam domain 2
  let new = NewApp
forall a. Default a => a
def {name = "chappie"} :: NewApp
  appId <- bindResponse (createApp owner tid new) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user.id" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString

  let appIdObject = [Pair] -> Value
object [String
"domain" String -> Value -> Pair
forall a. ToJSON a => String -> a -> Pair
.= Value
domain, String
"id" String -> String -> Pair
forall a. ToJSON a => String -> a -> Pair
.= String
appId]

  withWebSockets [owner, regularMember] \[WebSocket
wsOwner, WebSocket
wsRegularMember] -> do
    App Response -> (Response -> App ()) -> App ()
forall a.
HasCallStack =>
App Response -> (Response -> App a) -> App a
bindResponse (String -> Value -> Value -> App Response
forall owner member.
(HasCallStack, MakesValue owner, MakesValue member) =>
String -> owner -> member -> App Response
deleteTeamMember String
tid Value
owner Value
appIdObject) ((Response -> App ()) -> App ()) -> (Response -> App ()) -> App ()
forall a b. (a -> b) -> a -> b
$ \Response
resp -> do
      Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
202
      let predicate :: a -> App Bool
predicate a
payload = do
            typ <- a
payload a -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"payload.0.type" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString
            pure $ typ == "team.member-leave"
      App Value -> App ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (App Value -> App ()) -> App Value -> App ()
forall a b. (a -> b) -> a -> b
$ HasCallStack => (Value -> App Bool) -> WebSocket -> App Value
(Value -> App Bool) -> WebSocket -> App Value
awaitMatch Value -> App Bool
forall {a}. MakesValue a => a -> App Bool
predicate WebSocket
wsOwner
      App Value -> App ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (App Value -> App ()) -> App Value -> App ()
forall a b. (a -> b) -> a -> b
$ HasCallStack => (Value -> App Bool) -> WebSocket -> App Value
(Value -> App Bool) -> WebSocket -> App Value
awaitMatch Value -> App Bool
forall {a}. MakesValue a => a -> App Bool
predicate WebSocket
wsRegularMember

  eventually $ do
    -- Check StoredApp is gone
    bindResponse (getApp owner tid appId) $ \Response
resp -> do
      Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
404

    -- Check StoredUser is deleted (via public API)
    bindResponse (getUser owner appIdObject) $ \Response
resp -> do
      Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
      Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"deleted" App Value -> Bool -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` Bool
True

    -- Check StoredUser is gone (via internal API)
    bindResponse (BrigI.getUsersId domain [appId]) $ \Response
resp -> do
      Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
      Response
resp.json Maybe Value -> [Value] -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` ([] :: [Value])

testPutApp :: (HasCallStack) => App ()
testPutApp :: HasCallStack => App ()
testPutApp = do
  domain <- Domain -> App Value
forall a. (MakesValue a, HasCallStack) => a -> App Value
make Domain
OwnDomain
  (owner, tid, [regularMember]) <- createTeam domain 2
  let new = NewApp
forall a. Default a => a
def {name = "choppie"} :: NewApp
  (app, appId) <- bindResponse (createApp owner tid new) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    (,)
      (Value -> Value -> (Value, Value))
-> App Value -> App (Value -> (Value, Value))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user")
      App (Value -> (Value, Value)) -> App Value -> App (Value, Value)
forall a b. App (a -> b) -> App a -> App b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> (Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user.id")

  let Object appMetadata =
        [aesonQQ|
        {
          "accent_id": 126,
          "assets": [
            {
              "key": "3-1-47de4580-ae51-4650-acbb-d10c028cb0ac",
              "size": "preview",
              "type": "image"
            }
          ],
          "name": "Appy McApp",
          "category": "security",
          "description": "This is the best app ever."
        }|]

  withWebSockets [owner, regularMember, app] \[WebSocket
wsOwner, WebSocket
wsRegularMember, WebSocket
wsApp] -> do
    App Response -> (Response -> App ()) -> App ()
forall a.
HasCallStack =>
App Response -> (Response -> App a) -> App a
bindResponse (String -> Value -> Value -> Value -> App Response
forall user app.
(HasCallStack, MakesValue user, MakesValue app) =>
String -> user -> app -> Value -> App Response
putAppMetadata String
tid Value
owner Value
appId (Object -> Value
Object Object
appMetadata)) ((Response -> App ()) -> App ()) -> (Response -> App ()) -> App ()
forall a b. (a -> b) -> a -> b
$ \Response
resp -> do
      Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    notifOwner <- HasCallStack => (Value -> App Bool) -> WebSocket -> App Value
(Value -> App Bool) -> WebSocket -> App Value
awaitMatch Value -> App Bool
forall a. (HasCallStack, MakesValue a) => a -> App Bool
isUserUpdatedNotif WebSocket
wsOwner
    notifMember <- awaitMatch isUserUpdatedNotif wsRegularMember
    notifApp <- awaitMatch isUserUpdatedNotif wsApp
    notifOwner %. "payload.0.user.id" `shouldMatch` appId
    length (nub [notifOwner, notifMember, notifApp]) `shouldMatchInt` 1

  bindResponse (getApp owner tid appId) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json
      Maybe Value -> Shape -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Shape -> App ()
`shouldMatchShapeLenient` [(String, Shape)] -> Shape
SObject
        [ (String
"accent_id", Shape
SNumber),
          (String
"assets", Shape -> Shape
SArray ([(String, Shape)] -> Shape
SObject [(String
"key", Shape
SString), (String
"size", Shape
SString), (String
"type", Shape
SString)])),
          (String
"name", Shape
SString),
          (String
"app", [(String, Shape)] -> Shape
SObject [(String
"category", Shape
SString), (String
"description", Shape
SString)])
        ]

  let badAppId = String
"5e002eca-114f-11f1-b5a3-7306b8837f91"
  bindResponse (putAppMetadata tid owner badAppId (Object appMetadata)) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
404

-- | FUTUREWORK: 'Test.Apps.testFindApp',
-- 'Test.Apps.testRetrieveUsersIncludingApps',
-- 'Test.Search.checkUserSearch' have some overlap, or at least could
-- be re-ordered for clarity.
testRetrieveUsersIncludingApps :: (HasCallStack) => App ()
testRetrieveUsersIncludingApps :: HasCallStack => App ()
testRetrieveUsersIncludingApps = do
  let userShape :: Shape
userShape =
        [(String, Shape)] -> Shape
SObject
          [ (String
"accent_id", Shape
SNumber),
            (String
"assets", Shape -> Shape
SArray Shape
SAny),
            (String
"id", Shape
SString),
            (String
"name", Shape
SString),
            (String
"qualified_id", [(String, Shape)] -> Shape
SObject [(String
"domain", Shape
SString), (String
"id", Shape
SString)]),
            (String
"searchable", Shape
SBool),
            (String
"supported_protocols", Shape -> Shape
SArray Shape
SString),
            (String
"team", Shape
SString),
            (String
"type", Shape
SString)
          ]
      memberShape :: Shape
memberShape =
        [(String, Shape)] -> Shape
SObject
          [ (String
"created_at", Shape
SString),
            (String
"created_by", Shape
SString),
            (String
"legalhold_status", Shape
SString),
            (String
"permissions", [(String, Shape)] -> Shape
SObject [(String
"copy", Shape
SNumber), (String
"self", Shape
SNumber)]),
            (String
"user", Shape
SString)
          ]
      appShape :: Shape
appShape =
        [(String, Shape)] -> Shape
SObject
          [ (String
"category", Shape
SString),
            (String
"description", Shape
SString)
          ]
      appWithIdShape :: Shape
appWithIdShape =
        [(String, Shape)] -> Shape
SObject
          [ (String
"id", Shape
SString),
            (String
"app", Shape
appShape)
          ]
      searchResultShape :: Shape
searchResultShape =
        [(String, Shape)] -> Shape
SObject
          [ (String
"accent_id", Shape
SNumber),
            (String
"handle", Shape
SAny), -- sometimes "string", but always "null" for apps
            (String
"id", Shape
SString),
            (String
"name", Shape
SString),
            (String
"qualified_id", [(String, Shape)] -> Shape
SObject [(String
"domain", Shape
SString), (String
"id", Shape
SString)]),
            (String
"team", Shape
SString),
            (String
"type", Shape
SString)
          ]
      listResultShape :: Shape
listResultShape =
        [(String, Shape)] -> Shape
SObject
          [ (String
"accent_id", Shape
SNumber),
            (String
"assets", Shape -> Shape
SArray Shape
SAny),
            (String
"app", Shape
SAny),
            (String
"id", Shape
SString),
            (String
"legalhold_status", Shape
SString),
            (String
"name", Shape
SString),
            (String
"qualified_id", [(String, Shape)] -> Shape
SObject [(String
"domain", Shape
SString), (String
"id", Shape
SString)]),
            (String
"searchable", Shape
SBool),
            (String
"supported_protocols", Shape -> Shape
SArray Shape
SString),
            (String
"team", Shape
SString),
            (String
"type", Shape
SString)
          ]

  domain <- Domain -> App Value
forall a. (MakesValue a, HasCallStack) => a -> App Value
make Domain
OwnDomain
  (owner, tid, [regular]) <- createTeam domain 2

  -- [`POST /teams/:tid/apps`](https://staging-nginz-https.zinfra.io/v15/api/swagger-ui/#/default/create-app) (route id: "create-app")
  let new = NewApp
forall a. Default a => a
def {name = "chippie"} :: NewApp
  appCreated <- bindResponse (createApp owner tid new) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Maybe Value -> App (Maybe Value)
forall a. a -> App a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Response
resp.json
  appCreated
    `shouldMatchShapeLenient` SObject
      [ ("cookie", SString),
        ("user", userShape)
      ]
  appId <- appCreated %. "user.id" & asString

  -- [`GET /teams/:tid/members`](https://staging-nginz-https.zinfra.io/v15/api/swagger-ui/#/default/get-team-members) (route id: "get-team-members")
  getTeamMembers owner tid `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"hasMore" App Value -> Bool -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` Bool
False
    mems <- Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"members" App Value -> (Value -> App [Value]) -> App [Value]
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App [Value]
forall a. (HasCallStack, MakesValue a) => a -> App [Value]
asList
    memIds <- (asString . (%. "user")) `mapM` mems
    memIds
      `shouldMatchSet` sequence
        [ pure appId,
          asString $ regular %. "qualified_id.id",
          asString $ owner %. "qualified_id.id"
        ]

  -- [`GET /teams/:tid/members/:uid`](https://staging-nginz-https.zinfra.io/v15/api/swagger-ui/#/default/get-team-member) (route id: "get-team-member")
  getTeamMember owner tid appId `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
appId
    Response
resp.json Maybe Value -> Shape -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Shape -> App ()
`shouldMatchShapeLenient` Shape
memberShape

  -- [`GET /teams/:tid/apps`](https://staging-nginz-https.zinfra.io/v15/api/swagger-ui/#/default/get-apps) (route id: "get-apps")
  getApps owner tid `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    apps <- Response
resp.json Maybe Value -> (Maybe Value -> App Value) -> App Value
forall a b. a -> (a -> b) -> b
& App Value -> (Value -> App Value) -> Maybe Value -> App Value
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (String -> App Value
forall a. HasCallStack => String -> a
error String
"this shouldn't happen") Value -> App Value
forall a. a -> App a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
    apps `shouldMatchShapeLenient` SArray appWithIdShape

  -- [`GET /teams/:tid/apps/:uid`](https://staging-nginz-https.zinfra.io/v15/api/swagger-ui/#/default/get-app) (route id: "get-app")
  getApp owner tid appId `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> Shape -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Shape -> App ()
`shouldMatchShapeLenient` Shape
userShape

  -- [`POST /list-users`](https://staging-nginz-https.zinfra.io/v15/api/swagger-ui/#/default/list-users-by-ids-or-handles) (route id: "list-users-by-ids-or-handles")
  listUsers owner [appCreated %. "user"] `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"found.0" App Value -> Shape -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Shape -> App ()
`shouldMatchShapeLenient` Shape
listResultShape

  -- [`GET /search/contacts`](https://staging-nginz-https.zinfra.io/v15/api/swagger-ui/#/default/search-contacts) (route id: "search-contacts")
  putSelf owner (def {name = Just "name-A1"}) >>= assertSuccess
  putSelf regular (def {name = Just "name-A2"}) >>= assertSuccess
  putSelf (appCreated %. "user") (def {name = Just "name-A3"}) >>= assertSuccess
  eventually
    $ searchContacts owner "name" domain
    `bindResponse` \Response
resp -> do
      Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
      hits :: [Value] <- Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"documents" App Value -> (App Value -> App [Value]) -> App [Value]
forall a b. a -> (a -> b) -> b
& App Value -> App [Value]
forall a. (HasCallStack, MakesValue a) => a -> App [Value]
asList
      length hits `shouldMatchInt` 2 -- owner doesn't find itself
      (`shouldMatchShapeLenient` searchResultShape) `mapM_` hits

testCrossTeamAppConversation :: (HasCallStack) => Domain -> App ()
testCrossTeamAppConversation :: HasCallStack => Domain -> App ()
testCrossTeamAppConversation Domain
sameOrOtherDomain = do
  domainA <- Domain -> App Value
forall a. (MakesValue a, HasCallStack) => a -> App Value
make Domain
OwnDomain
  domainB <- make sameOrOtherDomain
  (ownerA, tidA, [m1]) <- createTeam domainA 2
  (ownerB, tidB, [m2]) <- createTeam domainB 2

  -- Create app A1 (member of team A)
  let newAppA1 = NewApp
forall a. Default a => a
def {name = "app-a1"} :: NewApp
  appA1 <- bindResponse (createApp ownerA tidA newAppA1) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user"

  -- Create app A2 (member of team B)
  let newAppA2 = NewApp
forall a. Default a => a
def {name = "app-a2"} :: NewApp
  appA2 <- bindResponse (createApp ownerB tidB newAppA2) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user"

  -- Create MLS clients for M1 and A1 (both on domainA)
  [m1c, appA1c] <- traverse (createMLSClient def) [m1, appA1]
  traverse_ (uploadNewKeyPackage def) [m1c, appA1c]

  -- M1 tries to connect to app A2 from team B => should fail
  -- Apps cannot create connections accross teams
  bindResponse (postConnection m1 appA2) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
400
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"label" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"invalid-user"

  -- M1 creates an MLS team conversation
  convId <- createNewGroupWith def m1c defMLS {team = Just tidA}

  -- M1 adds A1 to the conversation
  void $ createAddCommit m1c convId [appA1] >>= sendAndConsumeCommitBundle

  -- M1 connects to M2 from team B (cross-team/cross-domain)
  postConnection m1 m2 >>= assertSuccess
  putConnection m2 m1 "accepted" >>= assertSuccess

  -- Create MLS client for M2 (on domainB) and add to conversation
  m2c <- createMLSClient def m2
  void $ uploadNewKeyPackage def m2c
  void $ createAddCommit m1c convId [m2] >>= sendAndConsumeCommitBundle

  -- Create app A3 (on domainA, team A)
  let newAppA3 = NewApp
forall a. Default a => a
def {name = "app-a3"} :: NewApp
  appA3 <- bindResponse (createApp ownerA tidA newAppA3) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user"

  -- Create MLS client for A3 and add to conversation
  appA3c <- createMLSClient def appA3
  void $ uploadNewKeyPackage def appA3c
  void $ createAddCommit m1c convId [appA3] >>= sendAndConsumeCommitBundle

  void $ createApplicationMessage convId m1c "hello from M1" >>= sendAndConsumeMessage
  void $ createApplicationMessage convId appA1c "hello from A1" >>= sendAndConsumeMessage
  void $ createApplicationMessage convId appA3c "hello from A3" >>= sendAndConsumeMessage
  void $ createApplicationMessage convId m2c "hello from M2" >>= sendAndConsumeMessage

-- | FUTUREWORK: 'Test.Apps.testFindApp',
-- 'Test.Apps.testRetrieveUsersIncludingApps',
-- 'Test.Search.checkUserSearch' have some overlap, or at least could
-- be re-ordered for clarity.
testFindApp :: (HasCallStack) => Domain -> App ()
testFindApp :: HasCallStack => Domain -> App ()
testFindApp Domain
sameOrOtherDomain = do
  domainA <- Domain -> App Value
forall a. (MakesValue a, HasCallStack) => a -> App Value
make Domain
OwnDomain
  domainB <- make sameOrOtherDomain

  (ownerA1, tidA1, [regularMemberA1]) <- createTeam domainA 2
  let newAppA1 :: NewApp = def {name = "app A1", description = ""}
  (appA1Id) <- bindResponse (createApp ownerA1 tidA1 newAppA1) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user.id" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString
  BrigI.refreshIndex domainA

  (ownerA2, _, [regularMemberA2]) <- createTeam domainA 2
  (ownerB1, _, [regularMemberB1]) <- createTeam domainB 2

  let foundUserType :: (HasCallStack) => SearchContactsCfg -> [String] -> App ()
      foundUserType SearchContactsCfg
cfg [String]
uids =
        SearchContactsCfg -> App Response
searchContactsWith SearchContactsCfg
cfg App Response -> (Response -> App ()) -> App ()
forall a.
HasCallStack =>
App Response -> (Response -> App a) -> App a
`bindResponse` \Response
resp -> do
          Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
          foundDocs :: [Value] <- Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"documents" App Value -> (Value -> App [Value]) -> App [Value]
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App [Value]
forall a. (HasCallStack, MakesValue a) => a -> App [Value]
asList
          ((%. "id") `mapM` foundDocs) `shouldMatch` uids

  searchTerm <- asString newAppA1.name
  domain <- asString domainA

  -- App is findable from /search/contacts inside the own team.
  forM_ [ownerA1, regularMemberA1]
    $ \Value
user -> do
      HasCallStack => SearchContactsCfg -> [String] -> App ()
SearchContactsCfg -> [String] -> App ()
foundUserType SearchContactsCfg {types :: Maybe [String]
types = Maybe [String]
forall a. Maybe a
Nothing, String
Value
searchTerm :: String
domain :: String
user :: Value
domain :: String
searchTerm :: String
user :: Value
..} [String
appA1Id]
      HasCallStack => SearchContactsCfg -> [String] -> App ()
SearchContactsCfg -> [String] -> App ()
foundUserType SearchContactsCfg {types :: Maybe [String]
types = [String] -> Maybe [String]
forall a. a -> Maybe a
Just [], String
Value
searchTerm :: String
domain :: String
user :: Value
domain :: String
searchTerm :: String
user :: Value
..} [String
appA1Id]
      HasCallStack => SearchContactsCfg -> [String] -> App ()
SearchContactsCfg -> [String] -> App ()
foundUserType SearchContactsCfg {types :: Maybe [String]
types = [String] -> Maybe [String]
forall a. a -> Maybe a
Just [String
"app"], String
Value
searchTerm :: String
domain :: String
user :: Value
domain :: String
searchTerm :: String
user :: Value
..} [String
appA1Id]
      HasCallStack => SearchContactsCfg -> [String] -> App ()
SearchContactsCfg -> [String] -> App ()
foundUserType SearchContactsCfg {types :: Maybe [String]
types = [String] -> Maybe [String]
forall a. a -> Maybe a
Just [String
"app", String
"regular"], String
Value
searchTerm :: String
domain :: String
user :: Value
domain :: String
searchTerm :: String
user :: Value
..} [String
appA1Id]
      HasCallStack => SearchContactsCfg -> [String] -> App ()
SearchContactsCfg -> [String] -> App ()
foundUserType SearchContactsCfg {types :: Maybe [String]
types = [String] -> Maybe [String]
forall a. a -> Maybe a
Just [String
"regular"], String
Value
searchTerm :: String
domain :: String
user :: Value
domain :: String
searchTerm :: String
user :: Value
..} []

  -- App user is *not* findable from other team.
  forM_ [ownerA2, regularMemberA2, ownerB1, regularMemberB1]
    $ \Value
user -> do
      HasCallStack => SearchContactsCfg -> [String] -> App ()
SearchContactsCfg -> [String] -> App ()
foundUserType SearchContactsCfg {types :: Maybe [String]
types = Maybe [String]
forall a. Maybe a
Nothing, String
Value
searchTerm :: String
domain :: String
domain :: String
searchTerm :: String
user :: Value
user :: Value
..} []
      HasCallStack => SearchContactsCfg -> [String] -> App ()
SearchContactsCfg -> [String] -> App ()
foundUserType SearchContactsCfg {types :: Maybe [String]
types = [String] -> Maybe [String]
forall a. a -> Maybe a
Just [], String
Value
searchTerm :: String
domain :: String
domain :: String
searchTerm :: String
user :: Value
user :: Value
..} []
      HasCallStack => SearchContactsCfg -> [String] -> App ()
SearchContactsCfg -> [String] -> App ()
foundUserType SearchContactsCfg {types :: Maybe [String]
types = [String] -> Maybe [String]
forall a. a -> Maybe a
Just [String
"app"], String
Value
searchTerm :: String
domain :: String
domain :: String
searchTerm :: String
user :: Value
user :: Value
..} []
      HasCallStack => SearchContactsCfg -> [String] -> App ()
SearchContactsCfg -> [String] -> App ()
foundUserType SearchContactsCfg {types :: Maybe [String]
types = [String] -> Maybe [String]
forall a. a -> Maybe a
Just [String
"app", String
"regular"], String
Value
searchTerm :: String
domain :: String
domain :: String
searchTerm :: String
user :: Value
user :: Value
..} []
      HasCallStack => SearchContactsCfg -> [String] -> App ()
SearchContactsCfg -> [String] -> App ()
foundUserType SearchContactsCfg {types :: Maybe [String]
types = [String] -> Maybe [String]
forall a. a -> Maybe a
Just [String
"regular"], String
Value
searchTerm :: String
domain :: String
domain :: String
searchTerm :: String
user :: Value
user :: Value
..} []

testRemoveServicesAccessRole :: (HasCallStack) => App ()
testRemoveServicesAccessRole :: HasCallStack => App ()
testRemoveServicesAccessRole = do
  domain <- Domain -> App Value
forall a. (MakesValue a, HasCallStack) => a -> App Value
make Domain
OwnDomain

  -- Create team A with owner, member, and app
  (ownerA, tidA, [memberA]) <- createTeam domain 2
  let newApp = NewApp
forall a. Default a => a
def {name = "test-app"} :: NewApp
  app <- bindResponse (createApp ownerA tidA newApp) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user"

  -- Create MLS clients
  [memberAClient, appClient] <- traverse (createMLSClient def) [memberA, app]
  traverse_ (uploadNewKeyPackage def) [memberAClient, appClient]

  -- Create an MLS team conversation and add app
  conv <- postConversation memberA defMLS {team = Just tidA, protocol = "mls"} >>= getJSON 201
  convId <- objConvId conv
  createGroup def memberAClient convId
  void $ createAddCommit memberAClient convId [app] >>= sendAndConsumeCommitBundle

  -- Verify all members are in the conversation
  bindResponse (getConversation memberA conv) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    members <- Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"members.others" App Value -> (Value -> App [Value]) -> App [Value]
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App [Value]
forall a. (HasCallStack, MakesValue a) => a -> App [Value]
asList
    memberIds <- mapM (\Value
m -> Value
m Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"qualified_id.id" App Value -> (Value -> App String) -> App String
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString) members
    appId <- app %. "qualified_id.id" & asString
    memberIds `shouldContain` [appId]

  -- Remove "services" from access roles -> app should be removed
  -- First verify we can get the conversation with the creator
  bindResponse (getConversation memberA conv) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"protocol" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"mls"

  let noServices =
        [ String
"access" String -> [String] -> Pair
forall a. ToJSON a => String -> a -> Pair
.= [String
"invite", String
"link"],
          String
"access_role" String -> [String] -> Pair
forall a. ToJSON a => String -> a -> Pair
.= ([String
"team_member", String
"non_team_member"] :: [String])
        ]
  -- Use the conversation creator for the update
  bindResponse (updateAccess memberA conv noServices) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
  eventually $ do
    bindResponse (getConversation memberA conv) $ \Response
resp -> do
      Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
      members <- Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"members.others" App Value -> (Value -> App [Value]) -> App [Value]
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App [Value]
forall a. (HasCallStack, MakesValue a) => a -> App [Value]
asList
      memberIds <- mapM (\Value
m -> Value
m Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"qualified_id.id" App Value -> (Value -> App String) -> App String
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString) members
      appId <- app %. "qualified_id.id" & asString
      memberIds `shouldNotContain` [appId]

testAppReceivesMemberJoinNotification :: (HasCallStack) => App ()
testAppReceivesMemberJoinNotification :: HasCallStack => App ()
testAppReceivesMemberJoinNotification = do
  (owner, tid, []) <- Domain -> Int -> App (Value, String, [Value])
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> Int -> App (Value, String, [Value])
createTeam Domain
OwnDomain Int
1

  -- Create an app in the team
  app <- bindResponse (createApp owner tid def) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user"

  -- With websockets open for both owner and app, add a new regular member.
  -- Both should receive the team.member-join notification.
  withWebSockets [owner, app] $ \[WebSocket
wsOwner, WebSocket
wsApp] -> do
    newMember <- Value -> App Value
forall u. (HasCallStack, MakesValue u) => u -> App Value
addUserToTeam Value
owner

    memberJoinOwner <- awaitMatch isTeamMemberJoinNotif wsOwner
    memberJoinOwner %. "payload.0.team" `shouldMatch` tid
    memberJoinOwner %. "payload.0.data.user" `shouldMatch` objId newMember

    memberJoinApp <- awaitMatch isTeamMemberJoinNotif wsApp
    memberJoinApp %. "payload.0.team" `shouldMatch` tid
    memberJoinApp %. "payload.0.data.user" `shouldMatch` objId newMember

testTeamSizeWithApps :: (HasCallStack) => TaggedBool "test internal api" -> App ()
testTeamSizeWithApps :: HasCallStack => TaggedBool "test internal api" -> App ()
testTeamSizeWithApps (TaggedBool Bool
testInternalApi) = do
  domain <- Domain -> App Value
forall a. (MakesValue a, HasCallStack) => a -> App Value
make Domain
OwnDomain
  numRegulars <- liftIO $ randomRIO (1 :: Int, 3)
  numApps <- liftIO $ randomRIO (1 :: Int, 3)

  (owner, tid, extraMembers) <- createTeam domain (numRegulars + 1)

  apps <- replicateM numApps $ bindResponse (createApp owner tid def) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user"

  let checkSize :: (HasCallStack) => Int -> Int -> App ()
      checkSize Int
wantRegulars Int
wantApps =
        (if Bool
testInternalApi then Value -> String -> App Response
forall uid.
(HasCallStack, MakesValue uid) =>
uid -> String -> App Response
BrigI.getTeamSize else Value -> String -> App Response
forall uid.
(HasCallStack, MakesValue uid) =>
uid -> String -> App Response
Brig.getTeamSize) Value
owner String
tid App Response -> (Response -> App ()) -> App ()
forall a.
HasCallStack =>
App Response -> (Response -> App a) -> App a
`bindResponse` \Response
resp -> do
          Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
          Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"teamSize" App Value -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` (Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
wantRegulars Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
wantApps)
          Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"teamSizeRegulars" App Value -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` (Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
wantRegulars)
          Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"teamSizeApps" App Value -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
wantApps

  BrigI.refreshIndex domain
  eventually $ do
    checkSize numRegulars numApps

  deleteTeamMember tid owner (head apps) >>= assertSuccess
  deleteTeamMember tid owner (head extraMembers) >>= assertSuccess

  BrigI.refreshIndex domain
  eventually $ do
    checkSize (numRegulars - 1) (numApps - 1)

testReAddExternalAppToGroupConversation :: (HasCallStack) => App ()
testReAddExternalAppToGroupConversation :: HasCallStack => App ()
testReAddExternalAppToGroupConversation = do
  (owner1, tid1, []) <- Domain -> Int -> App (Value, String, [Value])
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> Int -> App (Value, String, [Value])
createTeam Domain
OwnDomain Int
1
  (owner2, tid2, [member2]) <- createTeam OwnDomain 2

  let newApp = NewApp
forall a. Default a => a
def {name = "external-app"} :: NewApp
  app <- bindResponse (createApp owner1 tid1 newApp) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user"
  appId <- app %. "id" & asString

  let appPermissions = [String
"create_team_conversation", String
"implicit_connection"]
  addTeamCollaborator owner2 tid2 app appPermissions >>= assertSuccess

  -- Create MLS clients
  [member2Client, appClient] <- traverse (createMLSClient def) [member2, app]
  traverse_ (uploadNewKeyPackage def) [member2Client, appClient]

  -- Create an MLS team conversation and add app
  conv <- postConversation member2 defMLS {team = Just tid2, protocol = "mls"} >>= getJSON 201
  convId <- objConvId conv
  createGroup def member2Client convId
  void $ createAddCommit member2Client convId [app] >>= sendAndConsumeCommitBundle

  bindResponse (getConversation member2 conv) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    mems <- Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"members.others" App Value -> (Value -> App [Value]) -> App [Value]
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App [Value]
forall a. (HasCallStack, MakesValue a) => a -> App [Value]
asList
    mIds <- mapM (\Value
m -> Value
m Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"qualified_id.id" App Value -> (Value -> App String) -> App String
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString) mems
    mIds `shouldContain` [appId]

  -- removeTeamCollaborator triggers a backend-side removal: the backend
  -- removes the app from the conversation and sends an external Remove
  -- proposal. The remaining client must consume it and commit.
  removeTeamCollaborator owner2 tid2 app >>= assertSuccess

  -- Fetch the external Remove proposal from the notification queue and
  -- consume it on the client side.
  eventually $ do
    notifs <- getNotifications member2 def {client = Just member2Client.client} >>= getJSON 200
    allNotifs <- notifs %. "notifications" & asList
    mlsNotifs <- filterM (\Value
n -> Value -> App Bool
forall a. (HasCallStack, MakesValue a) => a -> App Bool
isNewMLSMessageNotif Value
n) allNotifs
    mlsNotif <- assertOne mlsNotifs
    msgData <- mlsNotif %. "payload.0.data" & asByteString
    void $ mlsCliConsume convId def member2Client msgData

  -- Update test MLS state to reflect the removal
  modifyMLSState $ \MLSState
mls ->
    MLSState
mls
      { convs =
          Map.adjust
            ( \MLSConv
c ->
                MLSConv
c
                  { members = Set.filter (\ClientIdentity
m -> ClientIdentity
m.user String -> String -> Bool
forall a. Eq a => a -> a -> Bool
/= String
appId) c.members,
                    memberUsers = Set.filter (/= appClient.qualifiedUserId) c.memberUsers
                  }
            )
            convId
            mls.convs
      }

  void $ createPendingProposalCommit convId member2Client >>= sendCommitBundle

  bindResponse (getConversation member2 conv) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    mems <- Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"members.others" App Value -> (Value -> App [Value]) -> App [Value]
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App [Value]
forall a. (HasCallStack, MakesValue a) => a -> App [Value]
asList
    mIds <- mapM (\Value
m -> Value
m Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"qualified_id.id" App Value -> (Value -> App String) -> App String
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString) mems
    mIds `shouldNotContain` [appId]

  addTeamCollaborator owner2 tid2 app appPermissions >>= assertSuccess

  bindResponse (getConversation member2 conv) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    mems <- Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"members.others" App Value -> (Value -> App [Value]) -> App [Value]
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App [Value]
forall a. (HasCallStack, MakesValue a) => a -> App [Value]
asList
    mIds <- mapM (\Value
m -> Value
m Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"qualified_id.id" App Value -> (Value -> App String) -> App String
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString) mems
    mIds `shouldNotContain` [appId]

  do
    void $ uploadNewKeyPackage def appClient
    mp <- createAddCommit member2Client convId [app]
    void $ sendCommitBundle mp
    mlsConv <- getMLSConv convId
    traverse_ (fromWelcome convId mlsConv.ciphersuite appClient) mp.welcome

  bindResponse (getConversation member2 conv) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    mems <- Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"members.others" App Value -> (Value -> App [Value]) -> App [Value]
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App [Value]
forall a. (HasCallStack, MakesValue a) => a -> App [Value]
asList
    mIds <- mapM (\Value
m -> Value
m Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"qualified_id.id" App Value -> (Value -> App String) -> App String
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString) mems
    mIds `shouldContain` [appId]

-- | The ways in which an MLS 1:1 conversation can end.
data EndOfRelationship
  = -- | A full member is removed from the team, account is deleted.
    TeamMemberRemoved
  | -- | An app collaborating with the team gets removed.
    AppCollaboratorRemoved
  | -- | An app keeps its collaborator record, but loses every
    -- permission.  (Nothing about the conversation changes.)
    AppCollaboratorPermissionsDropped
  | -- | The app's own team deletes the app, so its account goes away.
    AppDeleted
  | -- | Like 'AppCollaboratorRemoved', but with a regular user as the
    -- collaborator.  Unlike an app, a regular user *could* be connected, so
    -- the conversation may only be dissolved after establishing that they are
    -- not (see 'ConnectedUserCollaboratorRemoved').
    UserCollaboratorRemoved
  | -- | A regular user who is both connected to the team member and a
    -- collaborator of their team loses the collaborator record.  The
    -- connection still justifies the conversation, so nothing about it may
    -- change at all.
    --
    -- NOTE: collaborators of type "user" are not a thing in our
    -- product. Its existence is an artefact of how external apps have
    -- been implement, and nobody in the product department knows or
    -- cares about this.  We still keep these two cases to document
    -- that backend does intentionally work that way.
    ConnectedUserCollaboratorRemoved
  deriving ((forall x. EndOfRelationship -> Rep EndOfRelationship x)
-> (forall x. Rep EndOfRelationship x -> EndOfRelationship)
-> Generic EndOfRelationship
forall x. Rep EndOfRelationship x -> EndOfRelationship
forall x. EndOfRelationship -> Rep EndOfRelationship x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. EndOfRelationship -> Rep EndOfRelationship x
from :: forall x. EndOfRelationship -> Rep EndOfRelationship x
$cto :: forall x. Rep EndOfRelationship x -> EndOfRelationship
to :: forall x. Rep EndOfRelationship x -> EndOfRelationship
Generic, Int -> EndOfRelationship -> ShowS
[EndOfRelationship] -> ShowS
EndOfRelationship -> String
(Int -> EndOfRelationship -> ShowS)
-> (EndOfRelationship -> String)
-> ([EndOfRelationship] -> ShowS)
-> Show EndOfRelationship
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> EndOfRelationship -> ShowS
showsPrec :: Int -> EndOfRelationship -> ShowS
$cshow :: EndOfRelationship -> String
show :: EndOfRelationship -> String
$cshowList :: [EndOfRelationship] -> ShowS
showList :: [EndOfRelationship] -> ShowS
Show, EndOfRelationship -> EndOfRelationship -> Bool
(EndOfRelationship -> EndOfRelationship -> Bool)
-> (EndOfRelationship -> EndOfRelationship -> Bool)
-> Eq EndOfRelationship
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: EndOfRelationship -> EndOfRelationship -> Bool
== :: EndOfRelationship -> EndOfRelationship -> Bool
$c/= :: EndOfRelationship -> EndOfRelationship -> Bool
/= :: EndOfRelationship -> EndOfRelationship -> Bool
Eq)

-- | An established MLS 1:1 conversation survives the end of the relationship
-- that justified it.
--
-- The conversation is never deleted: the remaining party keeps it
-- with all its metadata, and the only change is that the other party
-- is no longer a member.
--
-- Removing the other party from the conversation and removing them from the
-- MLS group go together: whenever the member is gone, the backend must also
-- have signed an external remove proposal for their leaf, and whenever the
-- member stays, there must be no such proposal.  (That a remaining client can
-- consume the proposal and commit the removal is covered by
-- 'testReAddExternalAppToGroupConversation', and is not repeated here.)
testMLSOne2OneAfterEndOfRelationship :: (HasCallStack) => EndOfRelationship -> App ()
testMLSOne2OneAfterEndOfRelationship :: HasCallStack => EndOfRelationship -> App ()
testMLSOne2OneAfterEndOfRelationship EndOfRelationship
scenario = do
  (owner1, tid1, []) <- Domain -> Int -> App (Value, String, [Value])
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> Int -> App (Value, String, [Value])
createTeam Domain
OwnDomain Int
1
  (owner2, tid2, [member2, teamMate2]) <- createTeam OwnDomain 3

  let collaboratorPermissions = [String
"create_team_conversation", String
"implicit_connection"]

      mkApp :: (HasCallStack) => App Value
      mkApp = do
        app <- App Response -> (Response -> App Value) -> App Value
forall a.
HasCallStack =>
App Response -> (Response -> App a) -> App a
bindResponse (Value -> String -> NewApp -> App Response
forall creator.
MakesValue creator =>
creator -> String -> NewApp -> App Response
createApp Value
owner1 String
tid1 (NewApp
forall a. Default a => a
def {name = "external-app-o2o"} :: NewApp)) ((Response -> App Value) -> App Value)
-> (Response -> App Value) -> App Value
forall a b. (a -> b) -> a -> b
$ \Response
resp -> do
          Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
          Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user"
        addTeamCollaborator owner2 tid2 app collaboratorPermissions >>= assertSuccess
        pure app

  -- The other party of the 1:1, the action that ends the relationship, and
  -- whether that action should remove the other party from the conversation
  -- (and, equivalently, from the MLS group).
  (other, endRelationship, expectOtherRemoved) <- case scenario of
    EndOfRelationship
TeamMemberRemoved ->
      (Value, App (), Bool) -> App (Value, App (), Bool)
forall a. a -> App a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
        ( Value
teamMate2,
          String -> Value -> Value -> App Response
forall owner member.
(HasCallStack, MakesValue owner, MakesValue member) =>
String -> owner -> member -> App Response
deleteTeamMember String
tid2 Value
owner2 Value
teamMate2 App Response -> (Response -> App ()) -> App ()
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= HasCallStack => Response -> App ()
Response -> App ()
assertSuccess,
          Bool
True
        )
    EndOfRelationship
AppCollaboratorRemoved -> do
      app <- App Value
HasCallStack => App Value
mkApp
      pure
        ( app,
          removeTeamCollaborator owner2 tid2 app >>= assertSuccess,
          True
        )
    EndOfRelationship
AppCollaboratorPermissionsDropped -> do
      app <- App Value
HasCallStack => App Value
mkApp
      pure
        ( app,
          updateTeamCollaborator owner2 tid2 app [] >>= assertSuccess,
          False
        )
    EndOfRelationship
AppDeleted -> do
      app <- App Value
HasCallStack => App Value
mkApp
      pure
        ( app,
          deleteTeamMember tid1 owner1 app >>= assertSuccess,
          True
        )
    EndOfRelationship
UserCollaboratorRemoved -> do
      user <- Domain -> CreateUser -> App Value
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> CreateUser -> App Value
randomUser Domain
OwnDomain CreateUser
forall a. Default a => a
def
      addTeamCollaborator owner2 tid2 user collaboratorPermissions >>= assertSuccess
      pure
        ( user,
          removeTeamCollaborator owner2 tid2 user >>= assertSuccess,
          True
        )
    EndOfRelationship
ConnectedUserCollaboratorRemoved -> do
      user <- Domain -> CreateUser -> App Value
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> CreateUser -> App Value
randomUser Domain
OwnDomain CreateUser
forall a. Default a => a
def
      connectTwoUsers member2 user
      addTeamCollaborator owner2 tid2 user collaboratorPermissions >>= assertSuccess
      pure
        ( user,
          removeTeamCollaborator owner2 tid2 user >>= assertSuccess,
          False
        )

  otherId <- other %. "qualified_id.id" & asString

  -- The team member establishes the MLS 1:1 conversation with the other party.
  one2OneConv <- getMLSOne2OneConversation member2 other >>= getJSON 200
  convQid <- one2OneConv %. "conversation.qualified_id"
  convId <- objConvId $ one2OneConv %. "conversation"
  [member2Client, otherClient] <- traverse (createMLSClient def) [member2, other]
  void $ uploadNewKeyPackage def otherClient
  resetOne2OneGroup def member2Client one2OneConv
  void $ createAddCommit member2Client convId [other] >>= sendAndConsumeCommitBundle

  convBefore <- getConversation member2 convQid >>= getJSON 200
  do
    mems <- convBefore %. "members.others" >>= asList
    mIds <- traverse (\Value
m -> Value
m Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"qualified_id.id" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString) mems
    mIds `shouldMatch` [otherId]

  -- How the conversation should look afterwards: the other party is gone (or
  -- not, in the control case), everything else is unchanged.
  convAfterExpected <-
    if expectOtherRemoved
      then convBefore & setField "members.others" ([] :: [Value])
      else pure convBefore

  endRelationship

  convAfter <- eventually $ do
    conv <- getConversation member2 convQid >>= getJSON 200
    conv `shouldMatch` convAfterExpected
    pure conv

  -- The remaining client is told about the removal in the MLS group as well.
  -- Not consumed here: it is enough that the backend sends the proposal, see
  -- the haddock of this test.
  eventually $ do
    -- The other party is the second member of the group, so its leaf is at index
    -- 1, and a removal initiated by the backend is signed by external sender 0.
    let isBackendRemoveProposal :: (HasCallStack) => Value -> App Bool
        isBackendRemoveProposal Value
n =
          Value -> App Bool
forall a. (HasCallStack, MakesValue a) => a -> App Bool
isNewMLSMessageNotif Value
n
            App Bool -> App Bool -> App Bool
&&~ ConvId -> Value -> App Bool
forall a.
(HasCallStack, MakesValue a, HasCallStack) =>
ConvId -> a -> App Bool
isNotifConvId ConvId
convId Value
n
            App Bool -> App Bool -> App Bool
&&~ do
              msg <- Value
n Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"payload.0.data" App Value -> (App Value -> App ByteString) -> App ByteString
forall a b. a -> (a -> b) -> b
& App Value -> App ByteString
forall a. (HasCallStack, MakesValue a) => a -> App ByteString
asByteString App ByteString -> (ByteString -> App Value) -> App Value
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= HasCallStack =>
Ciphersuite -> ClientIdentity -> ByteString -> App Value
Ciphersuite -> ClientIdentity -> ByteString -> App Value
showMessage Ciphersuite
forall a. Default a => a
def ClientIdentity
member2Client
              fieldEquals msg "message.content.body.Proposal.Remove.removed" (1 :: Int)
                &&~ fieldEquals msg "message.content.sender.External" (0 :: Int)
    notifs <- getNotifications member2 def {client = Just member2Client.client} >>= getJSON 200
    proposals <- notifs %. "notifications" & asList >>= filterM isBackendRemoveProposal
    length proposals `shouldMatchInt` (if expectOtherRemoved then 1 else 0)

  -- The remaining member can still use the conversation, and (made
  -- explicit here to catch regression) using it does not change it.
  do
    mp <- createApplicationMessage convId member2Client "hello"
    postMLSMessage mp.sender mp.message >>= assertStatus 201
  getConversation member2 convQid >>= getJSON 200 >>= (`shouldMatch` convAfter)

-- | Removing an app collaborator ends its MLS 1:1 conversation with a team
-- member (see 'testMLSOne2OneAfterEndOfRelationship'), but not for good: once
-- the app is a collaborator again, the team member gets back the very same
-- conversation, and can add the app to it again.
testMLSOne2OneReAddExternalApp :: (HasCallStack) => App ()
testMLSOne2OneReAddExternalApp :: HasCallStack => App ()
testMLSOne2OneReAddExternalApp = do
  (owner1, tid1, []) <- Domain -> Int -> App (Value, String, [Value])
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> Int -> App (Value, String, [Value])
createTeam Domain
OwnDomain Int
1
  (owner2, tid2, [member2]) <- createTeam OwnDomain 2

  app <- bindResponse (createApp owner1 tid1 (def {name = "external-app-o2o"} :: NewApp)) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"user"
  appId <- app %. "id" & asString

  let appPermissions = [String
"create_team_conversation", String
"implicit_connection"]
  addTeamCollaborator owner2 tid2 app appPermissions >>= assertSuccess

  one2OneConv <- getMLSOne2OneConversation member2 app >>= getJSON 200
  convQid <- one2OneConv %. "conversation.qualified_id"
  convId <- objConvId $ one2OneConv %. "conversation"
  [member2Client, appClient] <- traverse (createMLSClient def) [member2, app]
  void $ uploadNewKeyPackage def appClient
  resetOne2OneGroup def member2Client one2OneConv
  void $ createAddCommit member2Client convId [app] >>= sendAndConsumeCommitBundle

  let otherMemberIds :: (HasCallStack) => App [String]
      otherMemberIds = do
        conv <- Value -> Value -> App Response
forall user target.
(HasCallStack, MakesValue user, MakesValue target) =>
user -> target -> App Response
getConversation Value
member2 Value
convQid App Response -> (Response -> App Value) -> App Value
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= HasCallStack => Int -> Response -> App Value
Int -> Response -> App Value
getJSON Int
200
        mems <- conv %. "members.others" & asList
        traverse (\Value
m -> Value
m Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"qualified_id.id" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString) mems

  otherMemberIds `shouldMatch` [appId]

  removeTeamCollaborator owner2 tid2 app >>= assertSuccess

  -- The remaining client consumes the backend's remove proposal and commits
  -- it, so that the group is in a state where the app can be added again.
  eventually $ do
    notifs <- getNotifications member2 def {client = Just member2Client.client} >>= getJSON 200
    mlsNotifs <-
      notifs %. "notifications"
        & asList
          >>= filterM (\Value
n -> Value -> App Bool
forall a. (HasCallStack, MakesValue a) => a -> App Bool
isNewMLSMessageNotif Value
n App Bool -> App Bool -> App Bool
&&~ ConvId -> Value -> App Bool
forall a.
(HasCallStack, MakesValue a, HasCallStack) =>
ConvId -> a -> App Bool
isNotifConvId ConvId
convId Value
n)
    mlsNotif <- assertOne mlsNotifs
    msgData <- mlsNotif %. "payload.0.data" & asByteString
    void $ mlsCliConsume convId def member2Client msgData
  modifyMLSState $ \MLSState
mls ->
    MLSState
mls
      { convs =
          Map.adjust
            ( \MLSConv
c ->
                MLSConv
c
                  { members = Set.filter (\ClientIdentity
m -> ClientIdentity
m.user String -> String -> Bool
forall a. Eq a => a -> a -> Bool
/= String
appId) c.members,
                    memberUsers = Set.filter (/= appClient.qualifiedUserId) c.memberUsers
                  }
            )
            convId
            mls.convs
      }
  void $ createPendingProposalCommit convId member2Client >>= sendCommitBundle

  otherMemberIds `shouldMatch` ([] :: [String])
  getMLSOne2OneConversation member2 app >>= assertLabel 403 "not-connected"

  addTeamCollaborator owner2 tid2 app appPermissions >>= assertSuccess

  -- The conversation is the one from before, and the app does not come back
  -- by itself.
  getMLSOne2OneConversation member2 app `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"conversation.qualified_id" App Value -> Value -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` Value
convQid
  otherMemberIds `shouldMatch` ([] :: [String])

  do
    void $ uploadNewKeyPackage def appClient
    mp <- createAddCommit member2Client convId [app]
    void $ sendCommitBundle mp
    mlsConv <- getMLSConv convId
    traverse_ (fromWelcome convId mlsConv.ciphersuite appClient) mp.welcome

  otherMemberIds `shouldMatch` [appId]