diff --git a/services/brig/src/Brig/API/Client.hs b/services/brig/src/Brig/API/Client.hs index 46371c9329..5744bb9b95 100644 --- a/services/brig/src/Brig/API/Client.hs +++ b/services/brig/src/Brig/API/Client.hs @@ -145,9 +145,9 @@ addClientWithReAuthPolicy :: NewClient -> ExceptT ClientError (AppT r) Client addClientWithReAuthPolicy policy u con ip new = do - acc <- lift (wrapClient $ Data.lookupAccount u) >>= maybe (throwE (ClientUserNotFound u)) return + acc <- lift (wrapClient $ Data.lookupAccount u) >>= maybe (throwE (ClientUserNotFound u)) pure wrapHttpClientE $ verifyCode (newClientVerificationCode new) (userId . accountUser $ acc) - loc <- maybe (return Nothing) locationOf ip + loc <- maybe (pure Nothing) locationOf ip maxPermClients <- fromMaybe Opt.defUserMaxPermClients . Opt.setUserMaxPermClients <$> view settings let caps :: Maybe (Set ClientCapability) caps = updlhdev $ newClientCapabilities new @@ -172,7 +172,7 @@ addClientWithReAuthPolicy policy u con ip new = do for_ (userEmail usr) $ \email -> sendNewClientEmail (userDisplayName usr) email clt (userLocale usr) - return clt + pure clt where clientId' = clientIdFromPrekey (unpackLastPrekey $ newClientLastKey new) @@ -374,7 +374,7 @@ claimLocalMultiPrekeyBundles protectee userClients = do getClientKeys u c = do key <- fmap prekeyData <$> Data.claimPrekey u c when (isNothing key) $ noPrekeys u c - return key + pure key -- Utilities diff --git a/services/brig/src/Brig/API/Connection.hs b/services/brig/src/Brig/API/Connection.hs index 21c1efcc35..da4a3dd5fc 100644 --- a/services/brig/src/Brig/API/Connection.hs +++ b/services/brig/src/Brig/API/Connection.hs @@ -122,15 +122,15 @@ createConnectionToLocalUser self conn target = do <$> wrapClient (Data.lookupName (tUnqualified self)) let e2s = ConnectionUpdated s2o' (ucStatus <$> s2o) Nothing mapM_ (Intra.onConnectionEvent (tUnqualified self) (Just conn)) [e2o, e2s] - return s2o' + pure s2o' update :: UserConnection -> UserConnection -> ExceptT ConnectionError (AppT r) (ResponseForExistedCreated UserConnection) update s2o o2s = case (ucStatus s2o, ucStatus o2s) of (MissingLegalholdConsent, _) -> throwE $ InvalidTransition (tUnqualified self) (_, MissingLegalholdConsent) -> throwE $ InvalidTransition (tUnqualified self) - (Accepted, Accepted) -> return $ Existed s2o - (Accepted, Blocked) -> return $ Existed s2o - (Sent, Blocked) -> return $ Existed s2o + (Accepted, Accepted) -> pure $ Existed s2o + (Accepted, Blocked) -> pure $ Existed s2o + (Sent, Blocked) -> pure $ Existed s2o (Blocked, _) -> throwE $ InvalidTransition (tUnqualified self) (_, Blocked) -> change s2o SentWithHistory (_, Sent) -> accept s2o o2s @@ -159,7 +159,7 @@ createConnectionToLocalUser self conn target = do <$> Data.lookupName (tUnqualified self) let e2s = ConnectionUpdated s2o' (Just $ ucStatus s2o) Nothing lift $ mapM_ (Intra.onConnectionEvent (tUnqualified self) (Just conn)) [e2o, e2s] - return $ Existed s2o' + pure $ Existed s2o' resend :: UserConnection -> UserConnection -> ExceptT ConnectionError (AppT r) (ResponseForExistedCreated UserConnection) resend s2o o2s = do @@ -169,7 +169,7 @@ createConnectionToLocalUser self conn target = do logLocalConnection (tUnqualified self) (qUnqualified (ucTo s2o)) . msg (val "Resending connection request") s2o' <- insert (Just s2o) (Just o2s) - return $ Existed s2o' + pure $ Existed s2o' change :: UserConnection -> RelationWithHistory -> ExceptT ConnectionError (AppT r) (ResponseForExistedCreated UserConnection) change c s = Existed <$> lift (wrapClient $ Data.updateConnection c s) @@ -183,7 +183,7 @@ checkLegalholdPolicyConflict uid1 uid2 = do let catchProfileNotFound = -- Does not fit into 'ExceptT', so throw in '(AppT r)'. Anyway at the time of writing -- this, users are guaranteed to exist when called from 'createConnectionToLocalUser'. - maybe (throwM (errorToWai @'E.UserNotFound)) return + maybe (throwM (errorToWai @'E.UserNotFound)) pure status1 <- lift (wrapHttpClient $ getLegalHoldStatus uid1) >>= catchProfileNotFound status2 <- lift (wrapHttpClient $ getLegalHoldStatus uid2) >>= catchProfileNotFound @@ -270,14 +270,14 @@ updateConnectionToLocalUser self other newStatus conn = do -- Cancelled -> {Blocked} (Cancelled, _, Blocked) -> block s2o -- no change - (old, _, new) | old == new -> return Nothing + (old, _, new) | old == new -> pure Nothing -- invalid _ -> throwE $ InvalidTransition (tUnqualified self) let s2oUserConn = s2o' lift . for_ s2oUserConn $ \c -> let e2s = ConnectionUpdated c (Just $ ucStatus s2o) Nothing in Intra.onConnectionEvent (tUnqualified self) conn e2s - return s2oUserConn + pure s2oUserConn where accept :: UserConnection -> UserConnection -> ExceptT ConnectionError (AppT r) (Maybe UserConnection) accept s2o o2s = do @@ -496,4 +496,4 @@ lookupConnections :: UserId -> Maybe UserId -> Range 1 500 Int32 -> (AppT r) Use lookupConnections from start size = do lusr <- qualifyLocal from rs <- wrapClient $ Data.lookupLocalConnections lusr start size - return $! UserConnectionList (Data.resultList rs) (Data.resultHasMore rs) + pure $! UserConnectionList (Data.resultList rs) (Data.resultHasMore rs) diff --git a/services/brig/src/Brig/API/Handler.hs b/services/brig/src/Brig/API/Handler.hs index 4d5e42b5d1..f845156e22 100644 --- a/services/brig/src/Brig/API/Handler.hs +++ b/services/brig/src/Brig/API/Handler.hs @@ -83,7 +83,7 @@ runHandler e r h k = do a <- runAppT e' (runExceptT h) `catches` brigErrorHandlers (view applog e) (unRequestId (view requestId e)) - either (onError (view applog e') r k) return a + either (onError (view applog e') r k) pure a toServantHandler :: Env -> (Handler BrigCanonicalEffects) a -> Servant.Handler a toServantHandler env action = do diff --git a/services/brig/src/Brig/API/Internal.hs b/services/brig/src/Brig/API/Internal.hs index 8e0e1a1274..2b0c659aba 100644 --- a/services/brig/src/Brig/API/Internal.hs +++ b/services/brig/src/Brig/API/Internal.hs @@ -190,8 +190,8 @@ sitemap :: Members '[CodeStore, PasswordResetStore] r => Routes a (Handler r) () sitemap = do - get "/i/status" (continue $ const $ return empty) true - head "/i/status" (continue $ const $ return empty) true + get "/i/status" (continue $ const $ pure empty) true + head "/i/status" (continue $ const $ pure empty) true -- internal email activation (used in tests and in spar for validating emails obtained as -- SAML user identifiers). if the validate query parameter is false or missing, only set @@ -367,12 +367,12 @@ legalHoldClientRequestedH :: UserId ::: JsonRequest LegalHoldClientRequest ::: J legalHoldClientRequestedH (targetUser ::: req ::: _) = do clientRequest <- parseJsonBody req lift $ API.legalHoldClientRequested targetUser clientRequest - return $ setStatus status200 empty + pure $ setStatus status200 empty removeLegalHoldClientH :: UserId ::: JSON -> (Handler r) Response removeLegalHoldClientH (uid ::: _) = do lift $ API.removeLegalHoldClient uid - return $ setStatus status200 empty + pure $ setStatus status200 empty internalListClientsH :: JSON ::: JsonRequest UserSet -> (Handler r) Response internalListClientsH (_ ::: req) = do @@ -481,7 +481,7 @@ getActivationCodeH (_ ::: emailOrPhone) = do getActivationCode :: Either Email Phone -> (Handler r) GetActivationCodeResp getActivationCode emailOrPhone = do apair <- lift . wrapClient $ API.lookupActivationCode emailOrPhone - maybe (throwStd activationKeyNotFound) (return . GetActivationCodeResp) apair + maybe (throwStd activationKeyNotFound) (pure . GetActivationCodeResp) apair newtype GetActivationCodeResp = GetActivationCodeResp (ActivationKey, ActivationCode) @@ -511,19 +511,19 @@ changeAccountStatusH :: UserId ::: JsonRequest AccountStatusUpdate -> (Handler r changeAccountStatusH (usr ::: req) = do status <- suStatus <$> parseJsonBody req wrapHttpClientE (API.changeSingleAccountStatus usr status) !>> accountStatusError - return empty + pure empty getAccountStatusH :: JSON ::: UserId -> (Handler r) Response getAccountStatusH (_ ::: usr) = do status <- lift $ wrapClient $ API.lookupStatus usr - return $ case status of + pure $ case status of Just s -> json $ AccountStatusResp s Nothing -> setStatus status404 empty getConnectionsStatusUnqualified :: ConnectionsStatusRequest -> Maybe Relation -> (Handler r) [ConnectionStatus] getConnectionsStatusUnqualified ConnectionsStatusRequest {csrFrom, csrTo} flt = lift $ do r <- wrapClient $ maybe (API.lookupConnectionStatus' csrFrom) (API.lookupConnectionStatus csrFrom) csrTo - return $ maybe r (filterByRelation r) flt + pure $ maybe r (filterByRelation r) flt where filterByRelation l rel = filter ((== rel) . csStatus) l @@ -547,35 +547,35 @@ getConnectionsStatus (ConnectionsStatusRequestV2 froms mtos mrel) = do revokeIdentityH :: Either Email Phone -> (Handler r) Response revokeIdentityH emailOrPhone = do lift $ API.revokeIdentity emailOrPhone - return $ setStatus status200 empty + pure $ setStatus status200 empty updateConnectionInternalH :: JSON ::: JsonRequest UpdateConnectionsInternal -> (Handler r) Response updateConnectionInternalH (_ ::: req) = do updateConn <- parseJsonBody req API.updateConnectionInternal updateConn !>> connError - return $ setStatus status200 empty + pure $ setStatus status200 empty checkBlacklistH :: Either Email Phone -> (Handler r) Response checkBlacklistH emailOrPhone = do bl <- lift $ API.isBlacklisted emailOrPhone - return $ setStatus (bool status404 status200 bl) empty + pure $ setStatus (bool status404 status200 bl) empty deleteFromBlacklistH :: Either Email Phone -> (Handler r) Response deleteFromBlacklistH emailOrPhone = do void . lift $ API.blacklistDelete emailOrPhone - return empty + pure empty addBlacklistH :: Either Email Phone -> (Handler r) Response addBlacklistH emailOrPhone = do void . lift $ API.blacklistInsert emailOrPhone - return empty + pure empty -- | Get any matching prefixes. Also try for shorter prefix matches, -- i.e. checking for +123456 also checks for +12345, +1234, ... getPhonePrefixesH :: PhonePrefix -> (Handler r) Response getPhonePrefixesH prefix = do results <- lift $ API.phonePrefixGet prefix - return $ case results of + pure $ case results of [] -> setStatus status404 empty _ -> json results @@ -583,13 +583,13 @@ getPhonePrefixesH prefix = do deleteFromPhonePrefixH :: PhonePrefix -> (Handler r) Response deleteFromPhonePrefixH prefix = do void . lift $ API.phonePrefixDelete prefix - return empty + pure empty addPhonePrefixH :: JSON ::: JsonRequest ExcludedPrefix -> (Handler r) Response addPhonePrefixH (_ ::: req) = do prefix :: ExcludedPrefix <- parseJsonBody req void . lift $ API.phonePrefixInsert prefix - return empty + pure empty updateSSOIdH :: UserId ::: JSON ::: JsonRequest UserSSOId -> (Handler r) Response updateSSOIdH (uid ::: _ ::: req) = do @@ -598,8 +598,8 @@ updateSSOIdH (uid ::: _ ::: req) = do if success then do lift $ wrapHttpClient $ Intra.onUserEvent uid Nothing (UserUpdated ((emptyUserUpdatedData uid) {eupSSOId = Just ssoid})) - return empty - else return . setStatus status404 $ plain "User does not exist or has no team." + pure empty + else pure . setStatus status404 $ plain "User does not exist or has no team." deleteSSOIdH :: UserId ::: JSON -> (Handler r) Response deleteSSOIdH (uid ::: _) = do @@ -607,14 +607,14 @@ deleteSSOIdH (uid ::: _) = do if success then do lift $ wrapHttpClient $ Intra.onUserEvent uid Nothing (UserUpdated ((emptyUserUpdatedData uid) {eupSSOIdRemoved = True})) - return empty - else return . setStatus status404 $ plain "User does not exist or has no team." + pure empty + else pure . setStatus status404 $ plain "User does not exist or has no team." updateManagedByH :: UserId ::: JSON ::: JsonRequest ManagedByUpdate -> (Handler r) Response updateManagedByH (uid ::: _ ::: req) = do ManagedByUpdate managedBy <- parseJsonBody req lift $ wrapClient $ Data.updateManagedBy uid managedBy - return empty + pure empty updateRichInfoH :: UserId ::: JSON ::: JsonRequest RichInfoUpdate -> (Handler r) Response updateRichInfoH (uid ::: _ ::: req) = do @@ -677,9 +677,9 @@ checkHandleInternalH = getContactListH :: JSON ::: UserId -> (Handler r) Response getContactListH (_ ::: uid) = do contacts <- lift . wrapClient $ API.lookupContactList uid - return $ json $ UserIds contacts + pure $ json $ UserIds contacts -- Utilities ifNothing :: Utilities.Error -> Maybe a -> (Handler r) a -ifNothing e = maybe (throwStd e) return +ifNothing e = maybe (throwStd e) pure diff --git a/services/brig/src/Brig/API/MLS/KeyPackages/Validation.hs b/services/brig/src/Brig/API/MLS/KeyPackages/Validation.hs index 7cdce75572..c76bb89190 100644 --- a/services/brig/src/Brig/API/MLS/KeyPackages/Validation.hs +++ b/services/brig/src/Brig/API/MLS/KeyPackages/Validation.hs @@ -111,7 +111,7 @@ checkRequiredExtensions re = <*> maybe (Left "Missing capability extension") (pure . Identity) (reCapabilities re) findExtensions :: [Extension] -> Either Text (RequiredExtensions Identity) -findExtensions = (checkRequiredExtensions =<<) . getAp . foldMap findExtension +findExtensions = checkRequiredExtensions <=< (getAp . foldMap findExtension) findExtension :: Extension -> Ap (Either Text) (RequiredExtensions Maybe) findExtension ext = (Ap (decodeExtension ext) >>=) . foldMap $ \case diff --git a/services/brig/src/Brig/API/Public.hs b/services/brig/src/Brig/API/Public.hs index 88efa357e9..ed52f76273 100644 --- a/services/brig/src/Brig/API/Public.hs +++ b/services/brig/src/Brig/API/Public.hs @@ -507,7 +507,7 @@ listPropertyKeys u = lift $ wrapClient (API.lookupPropertyKeys u) listPropertyKeysAndValues :: UserId -> Handler r Public.PropertyKeysAndValues listPropertyKeysAndValues u = do keysAndVals <- fmap Map.fromList . lift $ wrapClient (API.lookupPropertyKeysAndValues u) - fmap Public.PropertyKeysAndValues $ traverse parseStoredPropertyValue keysAndVals + Public.PropertyKeysAndValues <$> traverse parseStoredPropertyValue keysAndVals getPrekeyUnqualifiedH :: UserId -> UserId -> ClientId -> (Handler r) Public.ClientPrekey getPrekeyUnqualifiedH zusr user client = do @@ -689,7 +689,7 @@ createUser (Public.NewUserPublic new) = lift . runExceptT $ do -- NOTE: Welcome e-mails for the team creator are not dealt by brig anymore sendWelcomeEmail e (CreateUserTeam t n) newUser l = case newUser of Public.NewTeamCreator _ -> - return () + pure () Public.NewTeamMember _ -> Team.sendMemberWelcomeMail e t n l Public.NewTeamMemberSSO _ -> @@ -798,7 +798,7 @@ checkHandlesH (_ ::: _ ::: req) = do Public.CheckHandles hs num <- parseJsonBody req let handles = mapMaybe parseHandle (fromRange hs) free <- lift . wrapClient $ API.checkHandles handles (fromRange num) - return $ json (free :: [Handle]) + pure $ json (free :: [Handle]) -- | This endpoint returns UserHandleInfo instead of UserProfile for backwards -- compatibility, whereas the corresponding qualified endpoint (implemented by @@ -841,7 +841,7 @@ completePasswordResetH :: completePasswordResetH (_ ::: req) = do Public.CompletePasswordReset {..} <- parseJsonBody req API.completePasswordReset cpwrIdent cpwrCode cpwrPassword !>> pwResetError - return empty + pure empty sendActivationCodeH :: JsonRequest Public.SendActivationCode -> (Handler r) Response sendActivationCodeH req = @@ -891,7 +891,7 @@ updateConnection self conn other update = do let newStatus = Public.cuStatus update lself <- qualifyLocal self mc <- API.updateConnection lself other newStatus (Just conn) !>> connError - return $ maybe Public.Unchanged Public.Updated mc + pure $ maybe Public.Unchanged Public.Updated mc listLocalConnections :: UserId -> Maybe UserId -> Maybe (Range 1 500 Int32) -> (Handler r) Public.UserConnectionList listLocalConnections uid start msize = do @@ -962,7 +962,7 @@ verifyDeleteUserH :: JsonRequest Public.VerifyDeleteUser ::: JSON -> (Handler r) verifyDeleteUserH (r ::: _) = do body <- parseJsonBody r API.verifyDeleteUser body !>> deleteUserError - return (setStatus status200 empty) + pure (setStatus status200 empty) updateUserEmail :: UserId -> UserId -> Public.EmailUpdate -> (Handler r) () updateUserEmail zuserId emailOwnerId (Public.EmailUpdate email) = do @@ -1015,10 +1015,10 @@ activate :: Public.Activate -> (Handler r) ActivationRespWithStatus activate (Public.Activate tgt code dryrun) | dryrun = do wrapClientE (API.preverify tgt code) !>> actError - return ActivationRespDryRun + pure ActivationRespDryRun | otherwise = do result <- API.activate tgt code Nothing !>> actError - return $ case result of + pure $ case result of ActivationSuccess ident x -> respond ident x ActivationPass -> ActivationRespPass where @@ -1088,9 +1088,9 @@ deprecatedCompletePasswordResetH (_ ::: k ::: req) = do (Public.pwrCode pwr) (Public.pwrPassword pwr) !>> pwResetError - return empty + pure empty -- Utilities ifNothing :: Utilities.Error -> Maybe a -> (Handler r) a -ifNothing e = maybe (throwStd e) return +ifNothing e = maybe (throwStd e) pure diff --git a/services/brig/src/Brig/API/User.hs b/services/brig/src/Brig/API/User.hs index d68d696d92..592f4d62d0 100644 --- a/services/brig/src/Brig/API/User.hs +++ b/services/brig/src/Brig/API/User.hs @@ -299,7 +299,7 @@ createUser new = do lift $ initAccountFeatureConfig uid - return $! CreateUserResult account edata pdata createUserTeam + pure $! CreateUserResult account edata pdata createUserTeam where -- NOTE: all functions in the where block don't use any arguments of createUser @@ -309,14 +309,14 @@ createUser new = do email <- for (newUserEmail newUser) $ \e -> either (const $ throwE RegisterErrorInvalidEmail) - return + pure (validateEmail e) -- Validate phone phone <- for (newUserPhone newUser) $ \p -> maybe (throwE RegisterErrorInvalidPhone) - return + pure =<< lift (wrapClient $ validatePhone p) for_ (catMaybes [userEmailKey <$> email, userPhoneKey <$> phone]) $ \k -> @@ -334,7 +334,7 @@ createUser new = do (Just invite, Just em) | e == userEmailKey em -> do _ <- ensureMemberCanJoin (Team.iiTeam ii) - return $ Just (invite, ii, Team.iiTeam ii) + pure $ Just (invite, ii, Team.iiTeam ii) _ -> throwE RegisterErrorInvalidInvitationCode Nothing -> throwE RegisterErrorInvalidInvitationCode @@ -406,13 +406,13 @@ createUser new = do field "user" (toByteString uid) . field "activation.key" (toByteString $ activationKey edata) . msg (val "Created email activation key/code pair") - return $ Just edata + pure $ Just edata Just c -> do ak <- liftIO $ Data.mkActivationKey ek void $ activateWithCurrency (ActivateKey ak) c (Just uid) (bnuCurrency =<< newTeam) !>> activationErrorToRegisterError - return Nothing + pure Nothing -- Handle phone activation (deprecated, see #RefRegistrationNoPreverification in /docs/reference/user/registration.md) handlePhoneActivation :: Maybe Phone -> UserId -> ExceptT RegisterError (AppT r) (Maybe Activation) @@ -425,11 +425,11 @@ createUser new = do field "user" (toByteString uid) . field "activation.key" (toByteString $ activationKey pdata) . msg (val "Created phone activation key/code pair") - return $ Just pdata + pure $ Just pdata Just c -> do ak <- liftIO $ Data.mkActivationKey pk void $ activate (ActivateKey ak) c (Just uid) !>> activationErrorToRegisterError - return Nothing + pure Nothing initAccountFeatureConfig :: UserId -> (AppT r) () initAccountFeatureConfig uid = do @@ -462,7 +462,7 @@ createUserInviteViaScim uid (NewUserScimInvitation tid loc name rawEmail) = do True lift . wrapClient $ Data.insertAccount account Nothing Nothing activated - return account + pure account -- | docs/reference/user/registration.md {#RefRestrictRegistration}. checkRestrictedUserCreation :: NewUser -> ExceptT RegisterError (AppT r) () @@ -551,17 +551,17 @@ checkHandle uhandle = do if | isJust owner -> -- Handle is taken (=> getHandleInfo will return 200) - return CheckHandleFound + pure CheckHandleFound | isBlacklistedHandle xhandle -> -- Handle is free but cannot be taken -- -- FUTUREWORK: i wonder if this is correct? isn't this the error for malformed -- handles? shouldn't we throw not-found here? or should there be a fourth case -- 'CheckHandleBlacklisted'? - return CheckHandleInvalid + pure CheckHandleInvalid | otherwise -> -- Handle is free and can be taken - return CheckHandleNotFound + pure CheckHandleNotFound -------------------------------------------------------------------------------- -- Check Handles @@ -569,8 +569,8 @@ checkHandle uhandle = do checkHandles :: MonadClient m => [Handle] -> Word -> m [Handle] checkHandles check num = reverse <$> collectFree [] check num where - collectFree free _ 0 = return free - collectFree free [] _ = return free + collectFree free _ 0 = pure free + collectFree free [] _ = pure free collectFree free (h : hs) n = if isBlacklistedHandle h then collectFree free hs n @@ -610,7 +610,7 @@ changeEmail u email allowScim = do em <- either (throwE . InvalidNewEmail email) - return + pure (validateEmail email) let ek = userEmailKey em blacklisted <- lift . wrapClient $ Blacklist.exists ek @@ -620,10 +620,10 @@ changeEmail u email allowScim = do unless available $ throwE $ EmailExists email - usr <- maybe (throwM $ UserProfileNotFound u) return =<< lift (wrapClient $ Data.lookupUser WithPendingInvitations u) + usr <- maybe (throwM $ UserProfileNotFound u) pure =<< lift (wrapClient $ Data.lookupUser WithPendingInvitations u) case emailIdentity =<< userIdentity usr of -- The user already has an email address and the new one is exactly the same - Just current | current == em -> return ChangeEmailIdempotent + Just current | current == em -> pure ChangeEmailIdempotent _ -> do unless ( userManagedBy usr /= ManagedByScim @@ -632,7 +632,7 @@ changeEmail u email allowScim = do $ throwE EmailManagedByScim timeout <- setActivationTimeout <$> view settings act <- lift . wrapClient $ Data.newActivation ek timeout (Just u) - return $ ChangeEmailNeedsActivation (usr, act, em) + pure $ ChangeEmailNeedsActivation (usr, act, em) ------------------------------------------------------------------------------- -- Change Phone @@ -642,7 +642,7 @@ changePhone u phone = do canonical <- maybe (throwE InvalidNewPhone) - return + pure =<< lift (wrapClient $ validatePhone phone) let pk = userPhoneKey canonical available <- lift . wrapClient $ Data.keyAvailable pk (Just u) @@ -657,7 +657,7 @@ changePhone u phone = do when prefixExcluded $ throwE BlacklistedNewPhone act <- lift . wrapClient $ Data.newActivation pk timeout (Just u) - return (act, canonical) + pure (act, canonical) ------------------------------------------------------------------------------- -- Remove Email @@ -699,7 +699,7 @@ revokeIdentity key = do let uk = either userEmailKey userPhoneKey key mu <- wrapClient $ Data.lookupKey uk case mu of - Nothing -> return () + Nothing -> pure () Just u -> fetchUserIdentity u >>= \case Just (FullIdentity _ _) -> revokeKey u uk @@ -709,7 +709,7 @@ revokeIdentity key = do Just (PhoneIdentity p) | Right p == key -> do revokeKey u uk wrapClient $ Data.deactivateUser u - _ -> return () + _ -> pure () where revokeKey :: UserId -> UserKey -> AppT r () revokeKey u uk = do @@ -779,8 +779,8 @@ changeSingleAccountStatus uid status = do mkUserEvent :: (MonadUnliftIO m, Traversable t, MonadClient m) => t UserId -> AccountStatus -> ExceptT AccountStatusError m (UserId -> UserEvent) mkUserEvent usrs status = case status of - Active -> return UserResumed - Suspended -> lift $ mapConcurrently revokeAllCookies usrs >> return UserSuspended + Active -> pure UserResumed + Suspended -> lift $ mapConcurrently revokeAllCookies usrs >> pure UserSuspended Deleted -> throwE InvalidAccountStatus Ephemeral -> throwE InvalidAccountStatus PendingInvitation -> throwE InvalidAccountStatus @@ -813,13 +813,13 @@ activateWithCurrency tgt code usr cur = do . msg (val "Activating") event <- wrapClientE $ Data.activateKey key code usr case event of - Nothing -> return ActivationPass + Nothing -> pure ActivationPass Just e -> do (uid, ident, first) <- lift $ onActivated e when first $ lift $ activateTeam uid - return $ ActivationSuccess ident first + pure $ ActivationSuccess ident first where activateTeam uid = do tid <- wrapHttp $ Intra.getTeamId uid @@ -842,14 +842,14 @@ onActivated (AccountActivated account) = do Log.debug $ field "user" (toByteString uid) . field "action" (Log.val "User.onActivated") Log.info $ field "user" (toByteString uid) . msg (val "User activated") wrapHttpClient $ Intra.onUserEvent uid Nothing $ UserActivated (accountUser account) - return (uid, userIdentity (accountUser account), True) + pure (uid, userIdentity (accountUser account), True) onActivated (EmailActivated uid email) = do wrapHttpClient $ Intra.onUserEvent uid Nothing (emailUpdated uid email) wrapHttpClient $ Data.deleteEmailUnvalidated uid - return (uid, Just (EmailIdentity email), False) + pure (uid, Just (EmailIdentity email), False) onActivated (PhoneActivated uid phone) = do wrapHttpClient $ Intra.onUserEvent uid Nothing (phoneUpdated uid phone) - return (uid, Just (PhoneIdentity phone), False) + pure (uid, Just (PhoneIdentity phone), False) -- docs/reference/user/activation.md {#RefActivationRequest} sendActivationCode :: Either Email Phone -> Maybe Locale -> Bool -> ExceptT SendActivationCodeError (AppT r) () @@ -858,7 +858,7 @@ sendActivationCode emailOrPhone loc call = case emailOrPhone of ek <- either (const . throwE . InvalidRecipient $ userEmailKey email) - (return . userEmailKey) + (pure . userEmailKey) (validateEmail email) exists <- lift $ isJust <$> wrapClient (Data.lookupKey ek) when exists $ @@ -877,7 +877,7 @@ sendActivationCode emailOrPhone loc call = case emailOrPhone of canonical <- maybe (throwE $ InvalidRecipient (userPhoneKey phone)) - return + pure =<< lift (wrapClient $ validatePhone phone) let pk = userPhoneKey canonical exists <- lift $ isJust <$> wrapClient (Data.lookupKey pk) @@ -906,7 +906,7 @@ sendActivationCode emailOrPhone loc call = case emailOrPhone of Just c' -> liftIO $ (,c') <$> Data.mkActivationKey k Nothing -> lift $ do dat <- Data.newActivation k timeout u - return (activationKey dat, activationCode dat) + pure (activationKey dat, activationCode dat) sendVerificationEmail ek uc = do p <- wrapClientE $ mkPair ek uc Nothing void . forEmailKey ek $ \em -> @@ -915,7 +915,7 @@ sendActivationCode emailOrPhone loc call = case emailOrPhone of sendActivationEmail ek uc uid = do -- FUTUREWORK(fisx): we allow for 'PendingInvitations' here, but I'm not sure this -- top-level function isn't another piece of a deprecated onboarding flow? - u <- maybe (notFound uid) return =<< lift (wrapClient $ Data.lookupUser WithPendingInvitations uid) + u <- maybe (notFound uid) pure =<< lift (wrapClient $ Data.lookupUser WithPendingInvitations uid) p <- wrapClientE $ mkPair ek (Just uc) (Just uid) let ident = userIdentity u name = userDisplayName u @@ -935,19 +935,19 @@ sendActivationCode emailOrPhone loc call = case emailOrPhone of sendActivationMail em name p loc' ident mkActivationKey :: (MonadClient m, MonadReader Env m) => ActivationTarget -> ExceptT ActivationError m ActivationKey -mkActivationKey (ActivateKey k) = return k +mkActivationKey (ActivateKey k) = pure k mkActivationKey (ActivateEmail e) = do ek <- either (throwE . InvalidActivationEmail e) - (return . userEmailKey) + (pure . userEmailKey) (validateEmail e) liftIO $ Data.mkActivationKey ek mkActivationKey (ActivatePhone p) = do pk <- maybe (throwE $ InvalidActivationPhone p) - (return . userPhoneKey) + (pure . userPhoneKey) =<< lift (validatePhone p) liftIO $ Data.mkActivationKey pk @@ -977,7 +977,7 @@ beginPasswordReset :: ExceptT PasswordResetError (AppT r) (UserId, PasswordResetPair) beginPasswordReset target = do let key = either userEmailKey userPhoneKey target - user <- lift (wrapClient $ Data.lookupKey key) >>= maybe (throwE InvalidPasswordResetKey) return + user <- lift (wrapClient $ Data.lookupKey key) >>= maybe (throwE InvalidPasswordResetKey) pure lift . Log.debug $ field "user" (toByteString user) . field "action" (Log.val "User.beginPasswordReset") status <- lift . wrapClient $ Data.lookupStatus user unless (status == Just Active) $ @@ -1020,7 +1020,7 @@ mkPasswordResetKey :: PasswordResetIdentity -> ExceptT PasswordResetError (AppT r) PasswordResetKey mkPasswordResetKey ident = case ident of - PasswordResetIdentityKey k -> return k + PasswordResetIdentityKey k -> pure k PasswordResetEmailIdentity e -> wrapClientE (user (userEmailKey e)) >>= lift . liftSem . E.mkPasswordResetKey @@ -1028,7 +1028,7 @@ mkPasswordResetKey ident = case ident of wrapClientE (user (userPhoneKey p)) >>= lift . liftSem . E.mkPasswordResetKey where - user uk = lift (Data.lookupKey uk) >>= maybe (throwE InvalidPasswordResetKey) return + user uk = lift (Data.lookupKey uk) >>= maybe (throwE InvalidPasswordResetKey) pure ------------------------------------------------------------------------------- -- User Deletion @@ -1047,7 +1047,7 @@ deleteUser uid pwd = do case account of Nothing -> throwE DeleteUserInvalid Just a -> case accountStatus a of - Deleted -> return Nothing + Deleted -> pure Nothing Suspended -> ensureNotOwner a >> go a Active -> ensureNotOwner a >> go a Ephemeral -> go a @@ -1072,7 +1072,7 @@ deleteUser uid pwd = do Just emailOrPhone -> sendCode a emailOrPhone Nothing -> case pwd of Just _ -> throwE DeleteUserMissingPassword - Nothing -> lift $ wrapHttpClient $ deleteAccount a >> return Nothing + Nothing -> lift $ wrapHttpClient $ deleteAccount a >> pure Nothing byPassword a pw = do lift . Log.info $ field "user" (toByteString uid) @@ -1083,7 +1083,7 @@ deleteUser uid pwd = do Just p -> do unless (verifyPassword pw p) $ throwE DeleteUserInvalidPassword - lift $ wrapHttpClient $ deleteAccount a >> return Nothing + lift $ wrapHttpClient $ deleteAccount a >> pure Nothing sendCode a target = do gen <- Code.mkGen (either Code.ForEmail Code.ForPhone target) pending <- lift . wrapClient $ Code.lookup (Code.genKey gen) Code.AccountDeletion @@ -1110,7 +1110,7 @@ deleteUser uid pwd = do (\p -> lift $ wrapClient $ sendDeletionSms p k v l) target `onException` wrapClientE (Code.delete k Code.AccountDeletion) - return $! Just $! Code.codeTTL c + pure $! Just $! Code.codeTTL c -- | Conclude validation and scheduling of user's deletion request that was initiated in -- 'deleteUser'. Called via @post /delete@. @@ -1119,7 +1119,7 @@ verifyDeleteUser d = do let key = verifyDeleteUserKey d let code = verifyDeleteUserCode d c <- lift . wrapClient $ Code.verify key Code.AccountDeletion code - a <- maybe (throwE DeleteUserInvalidCode) return (Code.codeAccount =<< c) + a <- maybe (throwE DeleteUserInvalidCode) pure (Code.codeAccount =<< c) account <- lift . wrapClient $ Data.lookupAccount (Id a) for_ account $ lift . wrapHttpClient . deleteAccount lift . wrapClient $ Code.delete key Code.AccountDeletion @@ -1165,7 +1165,7 @@ deleteAccount account@(accountUser -> user) = do where mkTombstone = do defLoc <- setDefaultUserLocale <$> view settings - return $ + pure $ account { accountStatus = Deleted, accountUser = @@ -1191,7 +1191,7 @@ lookupActivationCode emailOrPhone = do let uk = either userEmailKey userPhoneKey emailOrPhone k <- liftIO $ Data.mkActivationKey uk c <- fmap snd <$> Data.lookupActivationCode uk - return $ (k,) <$> c + pure $ (k,) <$> c lookupPasswordResetCode :: Members '[CodeStore, PasswordResetStore] r => @@ -1201,11 +1201,11 @@ lookupPasswordResetCode emailOrPhone = do let uk = either userEmailKey userPhoneKey emailOrPhone usr <- wrapClient $ Data.lookupKey uk liftSem $ case usr of - Nothing -> return Nothing + Nothing -> pure Nothing Just u -> do k <- E.mkPasswordResetKey u c <- E.lookupPasswordResetCode u - return $ (k,) <$> c + pure $ (k,) <$> c deleteUserNoVerify :: ( MonadReader Env m, @@ -1237,13 +1237,13 @@ userGC :: User -> m User userGC u = case userExpire u of - Nothing -> return u + Nothing -> pure u (Just (fromUTCTimeMillis -> e)) -> do now <- liftIO =<< view currentTime -- ephemeral users past their expiry date are deleted when (diffUTCTime e now < 0) $ deleteUserNoVerify (userId u) - return u + pure u lookupProfile :: ( MonadClient m, @@ -1344,7 +1344,7 @@ lookupLocalProfiles requestingUser others = do Nothing -> pure EmailVisibleToSelf' EmailVisibleToSelf -> pure EmailVisibleToSelf' usersAndStatus <- for users $ \u -> (u,) <$> getLegalHoldStatus' u - return $ map (toProfile emailVisibility'' css) usersAndStatus + pure $ map (toProfile emailVisibility'' css) usersAndStatus where toMap :: [ConnectionStatus] -> Map UserId Relation toMap = Map.fromList . map (csFrom &&& csStatus) diff --git a/services/brig/src/Brig/API/Util.hs b/services/brig/src/Brig/API/Util.hs index 92c3c4bffb..f7e068a29b 100644 --- a/services/brig/src/Brig/API/Util.hs +++ b/services/brig/src/Brig/API/Util.hs @@ -62,7 +62,7 @@ import Wire.API.User.Search (FederatedUserSearchPolicy (NoSearch)) lookupProfilesMaybeFilterSameTeamOnly :: UserId -> [UserProfile] -> (Handler r) [UserProfile] lookupProfilesMaybeFilterSameTeamOnly self us = do selfTeam <- lift $ wrapClient $ Data.lookupUserTeam self - return $ case selfTeam of + pure $ case selfTeam of Just team -> filter (\x -> profileTeam x == Just team) us Nothing -> us @@ -71,7 +71,7 @@ fetchUserIdentity uid = lookupSelfProfile uid >>= maybe (throwM $ UserProfileNotFound uid) - (return . userIdentity . selfUser) + (pure . userIdentity . selfUser) -- | Obtain a profile for a user as he can see himself. lookupSelfProfile :: UserId -> (AppT r) (Maybe SelfProfile) @@ -80,7 +80,7 @@ lookupSelfProfile = fmap (fmap mk) . wrapClient . Data.lookupAccount mk a = SelfProfile (accountUser a) validateHandle :: Text -> (Handler r) Handle -validateHandle = maybe (throwStd (errorToWai @'InvalidHandle)) return . parseHandle +validateHandle = maybe (throwStd (errorToWai @'InvalidHandle)) pure . parseHandle logEmail :: Email -> (Msg -> Msg) logEmail email = diff --git a/services/brig/src/Brig/AWS.hs b/services/brig/src/Brig/AWS.hs index 294de9b578..85c081a514 100644 --- a/services/brig/src/Brig/AWS.hs +++ b/services/brig/src/Brig/AWS.hs @@ -114,9 +114,9 @@ mkEnv lgr opts emailOpts mgr = do sesEndpoint dynamoEndpoint (mkEndpoint SQS.defaultService (Opt.sqsEndpoint opts)) - sq <- maybe (return Nothing) (fmap Just . getQueueUrl e . Opt.sesQueue) emailOpts - jq <- maybe (return Nothing) (fmap Just . getQueueUrl e) (Opt.userJournalQueue opts) - return (Env g sq jq pk e) + sq <- maybe (pure Nothing) (fmap Just . getQueueUrl e . Opt.sesQueue) emailOpts + jq <- maybe (pure Nothing) (fmap Just . getQueueUrl e) (Opt.userJournalQueue opts) + pure (Env g sq jq pk e) where mkEndpoint svc e = AWS.setEndpoint (e ^. awsSecure) (e ^. awsHost) (e ^. awsPort) svc mkAwsEnv g ses dyn sqs = do @@ -180,7 +180,7 @@ listen throttleMillis url callback = forever . handleAny unexpectedError $ do & set SQS.receiveMessage_waitTimeSeconds (Just 20) . set SQS.receiveMessage_maxNumberOfMessages (Just 10) onMessage m = - case decodeStrict =<< Text.encodeUtf8 <$> m ^. SQS.message_body of + case decodeStrict . Text.encodeUtf8 =<< (m ^. SQS.message_body) of Nothing -> err $ msg ("Failed to parse SQS event: " ++ show m) Just n -> do debug $ msg ("Received SQS event: " ++ show n) @@ -214,7 +214,7 @@ sendMail m = do & SES.sendRawEmail_destinations ?~ fmap addressEmail (mailTo m) & SES.sendRawEmail_source ?~ addressEmail (mailFrom m) resp <- retrying retry5x (const canRetry) $ const (sendCatch raw) - void $ either check return resp + void $ either check pure resp where check x = case x of -- To map rejected domain names by SES to 400 responses, in order @@ -242,7 +242,7 @@ send :: AWSRequest r => r -> Amazon (AWSResponse r) send r = throwA =<< sendCatch r throwA :: Either AWS.Error a -> Amazon a -throwA = either (throwM . GeneralError) return +throwA = either (throwM . GeneralError) pure execCatch :: (AWSRequest a, MonadUnliftIO m, MonadCatch m, MonadThrow m, MonadIO m) => @@ -259,7 +259,7 @@ exec :: AWS.Env -> a -> m (AWSResponse a) -exec e cmd = liftIO (execCatch e cmd) >>= either (throwM . GeneralError) return +exec e cmd = liftIO (execCatch e cmd) >>= either (throwM . GeneralError) pure canRetry :: MonadIO m => Either AWS.Error a -> m Bool canRetry (Right _) = pure False diff --git a/services/brig/src/Brig/AWS/Types.hs b/services/brig/src/Brig/AWS/Types.hs index e30b38d61d..8847d66513 100644 --- a/services/brig/src/Brig/AWS/Types.hs +++ b/services/brig/src/Brig/AWS/Types.hs @@ -41,9 +41,9 @@ data SESBounceType deriving (Eq, Show) instance FromJSON SESBounceType where - parseJSON "Undetermined" = return BounceUndetermined - parseJSON "Permanent" = return BouncePermanent - parseJSON "Transient" = return BounceTransient + parseJSON "Undetermined" = pure BounceUndetermined + parseJSON "Permanent" = pure BouncePermanent + parseJSON "Transient" = pure BounceTransient parseJSON x = fail $ "Unknown type: " <> show x instance FromJSON SESNotification where @@ -55,10 +55,10 @@ instance FromJSON SESNotification where bt <- b .: "bounceType" br <- b .: "bouncedRecipients" em <- mapM (\r -> r .: "emailAddress") br - return $! MailBounce bt em + pure $! MailBounce bt em "Complaint" -> do c <- o .: "complaint" cr <- c .: "complainedRecipients" em <- mapM (\r -> r .: "emailAddress") cr - return $! MailComplaint em + pure $! MailComplaint em x -> fail ("Brig.AWS: Unexpected notification type" ++ show x) diff --git a/services/brig/src/Brig/App.hs b/services/brig/src/Brig/App.hs index c7279183b4..80ba594971 100644 --- a/services/brig/src/Brig/App.hs +++ b/services/brig/src/Brig/App.hs @@ -242,7 +242,7 @@ newEnv o = do Just True -> Just <$> newMVar () _ -> pure Nothing kpLock <- newMVar () - return + pure $! Env { _cargohold = mkEndpoint $ Opt.cargohold o, _galley = mkEndpoint $ Opt.galley o, @@ -279,17 +279,17 @@ newEnv o = do _keyPackageLocalLock = kpLock } where - emailConn _ (Opt.EmailAWS aws) = return (Just aws, Nothing) + emailConn _ (Opt.EmailAWS aws) = pure (Just aws, Nothing) emailConn lgr (Opt.EmailSMTP s) = do let host = Opt.smtpEndpoint s ^. epHost port = Just $ fromInteger $ toInteger $ Opt.smtpEndpoint s ^. epPort smtpCredentials <- case Opt.smtpCredentials s of Just (Opt.EmailSMTPCredentials u p) -> do pass <- initCredentials p - return $ Just (SMTP.Username u, SMTP.Password pass) - _ -> return Nothing + pure $ Just (SMTP.Username u, SMTP.Password pass) + _ -> pure Nothing smtp <- SMTP.initSMTP lgr host port smtpCredentials (Opt.smtpConnType s) - return (Nothing, Just smtp) + pure (Nothing, Just smtp) mkEndpoint service = RPC.host (encodeUtf8 (service ^. epHost)) . RPC.port (service ^. epPort) $ RPC.empty mkIndexEnv :: Opts -> Logger -> Manager -> Metrics -> Endpoint -> IndexEnv @@ -302,12 +302,12 @@ mkIndexEnv o lgr mgr mtr galleyEndpoint = in IndexEnv mtr lgr' bhe Nothing mainIndex additionalIndex additionalBhe galleyEndpoint mgr geoSetup :: Logger -> FS.WatchManager -> Maybe FilePath -> IO (Maybe (IORef GeoIp.GeoDB)) -geoSetup _ _ Nothing = return Nothing +geoSetup _ _ Nothing = pure Nothing geoSetup lgr w (Just db) = do path <- canonicalizePath db geodb <- newIORef =<< GeoIp.openGeoDB path startWatching w path (replaceGeoDb lgr geodb) - return $ Just geodb + pure $ Just geodb startWatching :: FS.WatchManager -> FilePath -> FS.Action -> IO () startWatching w p = void . FS.watchDir w (Path.dropFileName p) predicate @@ -384,7 +384,7 @@ initExtGetManager = do managerResponseTimeout = responseTimeoutMicro 10000000 } Just sha <- getDigestByName "SHA256" - return (mgr, mkVerify sha) + pure (mgr, mkVerify sha) where mkVerify sha fprs = let pinset = map toByteString' fprs @@ -411,12 +411,12 @@ initCassandra o g = do . Cas.setPolicy (Cas.dcFilterPolicyIfConfigured g (Opt.cassandra o ^. casFilterNodesByDatacentre)) $ Cas.defSettings runClient p $ versionCheck schemaVersion - return p + pure p initCredentials :: (FromJSON a) => FilePathSecrets -> IO a initCredentials secretFile = do dat <- loadSecret secretFile - return $ either (\e -> error $ "Could not load secrets from " ++ show secretFile ++ ": " ++ e) id dat + pure $ either (\e -> error $ "Could not load secrets from " ++ show secretFile ++ ": " ++ e) id dat userTemplates :: MonadReader Env m => Maybe Locale -> m (Locale, UserTemplates) userTemplates l = forLocale l <$> view usrTemplates @@ -612,10 +612,10 @@ locationOf ip = view geoDb >>= \case Just g -> do database <- liftIO $ readIORef g - return $! do + pure $! do loc <- GeoIp.geoLocation =<< hush (GeoIp.findGeoData database "en" ip) - return $ location (Latitude $ GeoIp.locationLatitude loc) (Longitude $ GeoIp.locationLongitude loc) - Nothing -> return Nothing + pure $ location (Latitude $ GeoIp.locationLatitude loc) (Longitude $ GeoIp.locationLongitude loc) + Nothing -> pure Nothing -------------------------------------------------------------------------------- -- Federation diff --git a/services/brig/src/Brig/Budget.hs b/services/brig/src/Brig/Budget.hs index b7ac60fc88..cf952a3ed7 100644 --- a/services/brig/src/Brig/Budget.hs +++ b/services/brig/src/Brig/Budget.hs @@ -63,18 +63,18 @@ withBudget k b ma = do Budget ttl val <- fromMaybe b <$> lookupBudget k let remaining = val - 1 if remaining < 0 - then return (BudgetExhausted ttl) + then pure (BudgetExhausted ttl) else do a <- ma insertBudget k (Budget ttl remaining) - return (BudgetedValue a remaining) + pure (BudgetedValue a remaining) -- | Like 'withBudget', but does not decrease budget, only takes a look. checkBudget :: MonadClient m => BudgetKey -> Budget -> m (Budgeted ()) checkBudget k b = do Budget ttl val <- fromMaybe b <$> lookupBudget k let remaining = val - 1 - return $ + pure $ if remaining < 0 then BudgetExhausted ttl else BudgetedValue () remaining diff --git a/services/brig/src/Brig/Calling.hs b/services/brig/src/Brig/Calling.hs index 0b140baf91..48f892c64e 100644 --- a/services/brig/src/Brig/Calling.hs +++ b/services/brig/src/Brig/Calling.hs @@ -374,7 +374,7 @@ startWatching w p = void . FS.watchDir w (Path.dropFileName p) predicate predicate FS.Unknown {} = False readTurnList :: FilePath -> IO (Maybe (NonEmpty TurnURI)) -readTurnList = Text.readFile >=> return . fn . mapMaybe (fromByteString . Text.encodeUtf8) . Text.lines +readTurnList = Text.readFile >=> pure . fn . mapMaybe (fromByteString . Text.encodeUtf8) . Text.lines where fn [] = Nothing fn (x : xs) = Just (x :| xs) diff --git a/services/brig/src/Brig/Code.hs b/services/brig/src/Brig/Code.hs index 05fbb72f12..ec7383151e 100644 --- a/services/brig/src/Brig/Code.hs +++ b/services/brig/src/Brig/Code.hs @@ -136,13 +136,13 @@ instance Cql Scope where toCql CreateScimToken = CqlInt 6 toCql DeleteTeam = CqlInt 7 - fromCql (CqlInt 1) = return AccountDeletion - fromCql (CqlInt 2) = return IdentityVerification - fromCql (CqlInt 3) = return PasswordReset - fromCql (CqlInt 4) = return AccountLogin - fromCql (CqlInt 5) = return AccountApproval - fromCql (CqlInt 6) = return CreateScimToken - fromCql (CqlInt 7) = return DeleteTeam + fromCql (CqlInt 1) = pure AccountDeletion + fromCql (CqlInt 2) = pure IdentityVerification + fromCql (CqlInt 3) = pure PasswordReset + fromCql (CqlInt 4) = pure AccountLogin + fromCql (CqlInt 5) = pure AccountApproval + fromCql (CqlInt 6) = pure CreateScimToken + fromCql (CqlInt 7) = pure DeleteTeam fromCql _ = Left "fromCql: Scope: int expected" newtype Retries = Retries {numRetries :: Word8} @@ -151,7 +151,7 @@ newtype Retries = Retries {numRetries :: Word8} instance Cql Retries where ctype = Tagged IntColumn toCql = CqlInt . fromIntegral . numRetries - fromCql (CqlInt n) = return (Retries (fromIntegral n)) + fromCql (CqlInt n) = pure (Retries (fromIntegral n)) fromCql _ = Left "fromCql: Retries: int expected" -------------------------------------------------------------------------------- @@ -178,7 +178,7 @@ mkKey cfor = liftIO $ do mkGen :: MonadIO m => CodeFor -> m Gen mkGen cfor = liftIO $ do Just sha256 <- getDigestByName "SHA256" - return (initGen sha256 cfor) + pure (initGen sha256 cfor) where initGen d (ForEmail e) = mkEmailLinkGen e d initGen d _ = mk6DigitGen' cfor d @@ -187,7 +187,7 @@ mkGen cfor = liftIO $ do mk6DigitGen :: MonadIO m => CodeFor -> m Gen mk6DigitGen cfor = liftIO $ do Just sha256 <- getDigestByName "SHA256" - return $ mk6DigitGen' cfor sha256 + pure $ mk6DigitGen' cfor sha256 mk6DigitGen' :: CodeFor -> Digest -> Gen mk6DigitGen' cfor d = @@ -224,7 +224,7 @@ generate :: generate gen scope retries ttl account = do let key = genKey gen val <- liftIO $ genValue gen - return $ mkCode key val + pure $ mkCode key val where mkCode key val = Code @@ -297,14 +297,14 @@ lookup k s = fmap (toCode k s) <$> retry x1 (query1 cql (params LocalQuorum (k, -- | Lookup and verify the code for the given key and scope -- against the given value. verify :: MonadClient m => Key -> Scope -> Value -> m (Maybe Code) -verify k s v = lookup k s >>= maybe (return Nothing) continue +verify k s v = lookup k s >>= maybe (pure Nothing) continue where continue c - | codeValue c == v = return (Just c) + | codeValue c == v = pure (Just c) | codeRetries c > 0 = do insert (c {codeRetries = codeRetries c - 1}) - return Nothing - | otherwise = return Nothing + pure Nothing + | otherwise = pure Nothing -- | Delete a code associated with the given key and scope. delete :: MonadClient m => Key -> Scope -> m () diff --git a/services/brig/src/Brig/Data/Activation.hs b/services/brig/src/Brig/Data/Activation.hs index 7fff629efc..7f20e71948 100644 --- a/services/brig/src/Brig/Data/Activation.hs +++ b/services/brig/src/Brig/Data/Activation.hs @@ -96,9 +96,9 @@ activateKey :: ExceptT ActivationError m (Maybe ActivationEvent) activateKey k c u = verifyCode k c >>= pickUser >>= activate where - pickUser (uk, u') = maybe (throwE invalidUser) (return . (uk,)) (u <|> u') + pickUser (uk, u') = maybe (throwE invalidUser) (pure . (uk,)) (u <|> u') activate (key, uid) = do - a <- lift (lookupAccount uid) >>= maybe (throwE invalidUser) return + a <- lift (lookupAccount uid) >>= maybe (throwE invalidUser) pure unless (accountStatus a == Active) $ -- this is never 'PendingActivation' in the flow this function is used in. throwE invalidCode case userIdentity (accountUser a) of @@ -107,7 +107,7 @@ activateKey k c u = verifyCode k c >>= pickUser >>= activate let ident = foldKey EmailIdentity PhoneIdentity key lift $ activateUser uid ident let a' = a {accountUser = (accountUser a) {userIdentity = Just ident}} - return . Just $ AccountActivated a' + pure . Just $ AccountActivated a' Just _ -> do let usr = accountUser a (profileNeedsUpdate, oldKey) = @@ -118,19 +118,19 @@ activateKey k c u = verifyCode k c >>= pickUser >>= activate usr in handleExistingIdentity uid profileNeedsUpdate oldKey key handleExistingIdentity uid profileNeedsUpdate oldKey key - | oldKey == Just key && not profileNeedsUpdate = return Nothing + | oldKey == Just key && not profileNeedsUpdate = pure Nothing -- activating existing key and exactly same profile -- (can happen when a user clicks on activation links more than once) | oldKey == Just key && profileNeedsUpdate = do lift $ foldKey (updateEmailAndDeleteEmailUnvalidated uid) (updatePhone uid) key - return . Just $ foldKey (EmailActivated uid) (PhoneActivated uid) key + pure . Just $ foldKey (EmailActivated uid) (PhoneActivated uid) key -- if the key is the same, we only want to update our profile | otherwise = do lift (runM (codeStoreToCassandra @m @'[Embed m] (E.mkPasswordResetKey uid >>= E.codeDelete))) claim key uid lift $ foldKey (updateEmailAndDeleteEmailUnvalidated uid) (updatePhone uid) key for_ oldKey $ lift . deleteKey - return . Just $ foldKey (EmailActivated uid) (PhoneActivated uid) key + pure . Just $ foldKey (EmailActivated uid) (PhoneActivated uid) key where updateEmailAndDeleteEmailUnvalidated :: MonadClient m => UserId -> Email -> m () updateEmailAndDeleteEmailUnvalidated u' email = @@ -162,7 +162,7 @@ newActivation uk timeout u = do insert t k c = do key <- liftIO $ mkActivationKey uk retry x5 . write keyInsert $ params LocalQuorum (key, t, k, c, u, maxAttempts, round timeout) - return $ Activation key c + pure $ Activation key c genCode = ActivationCode . Ascii.unsafeFromText . pack . printf "%06d" <$> randIntegerZeroToNMinusOne 1000000 @@ -190,10 +190,10 @@ verifyCode key code = do Nothing -> throwE invalidCode where mkScope "email" k u = case parseEmail k of - Just e -> return (userEmailKey e, u) + Just e -> pure (userEmailKey e, u) Nothing -> throwE invalidCode mkScope "phone" k u = case parsePhone k of - Just p -> return (userPhoneKey p, u) + Just p -> pure (userPhoneKey p, u) Nothing -> throwE invalidCode mkScope _ _ _ = throwE invalidCode countdown = lift . retry x5 . write keyInsert . params LocalQuorum @@ -202,9 +202,9 @@ verifyCode key code = do mkActivationKey :: UserKey -> IO ActivationKey mkActivationKey k = do d <- liftIO $ getDigestByName "SHA256" - d' <- maybe (fail "SHA256 not found") return d + d' <- maybe (fail "SHA256 not found") pure d let bs = digestBS d' (T.encodeUtf8 $ keyText k) - return . ActivationKey $ Ascii.encodeBase64Url bs + pure . ActivationKey $ Ascii.encodeBase64Url bs deleteActivationPair :: MonadClient m => ActivationKey -> m () deleteActivationPair = write keyDelete . params LocalQuorum . Identity diff --git a/services/brig/src/Brig/Data/Blacklist.hs b/services/brig/src/Brig/Data/Blacklist.hs index 4ebe61fd7e..9b0c3a45c0 100644 --- a/services/brig/src/Brig/Data/Blacklist.hs +++ b/services/brig/src/Brig/Data/Blacklist.hs @@ -42,7 +42,7 @@ insert uk = retry x5 $ write keyInsert (params LocalQuorum (Identity $ keyText u exists :: MonadClient m => UserKey -> m Bool exists uk = - (return . isJust) . fmap runIdentity + (pure . isJust) . fmap runIdentity =<< retry x1 (query1 keySelect (params LocalQuorum (Identity $ keyText uk))) delete :: MonadClient m => UserKey -> m () @@ -80,12 +80,12 @@ getAllPrefixes prefix = do existsAnyPrefix :: MonadClient m => Phone -> m Bool existsAnyPrefix phone = do let prefixes = fromPhonePrefix <$> allPrefixes (fromPhone phone) - (not . null) <$> selectPrefixes prefixes + not . null <$> selectPrefixes prefixes selectPrefixes :: MonadClient m => [Text] -> m [ExcludedPrefix] selectPrefixes prefixes = do results <- retry x1 (query sel (params LocalQuorum (Identity $ prefixes))) - return $ (\(p, c) -> ExcludedPrefix p c) <$> results + pure $ uncurry ExcludedPrefix <$> results where sel :: PrepQuery R (Identity [Text]) (PhonePrefix, Text) sel = "SELECT prefix, comment FROM excluded_phones WHERE prefix IN ?" diff --git a/services/brig/src/Brig/Data/Client.hs b/services/brig/src/Brig/Data/Client.hs index 03ea230140..51b42529a3 100644 --- a/services/brig/src/Brig/Data/Client.hs +++ b/services/brig/src/Brig/Data/Client.hs @@ -147,7 +147,7 @@ addClientWithReAuthPolicy reAuthPolicy u newId c maxPermClients loc cps = do new <- insert let !total = fromIntegral (length clients + if upsert then 0 else 1) let old = maybe (filter (not . exists) typed) (const []) limit - return (new, old, total) + pure (new, old, total) where limit :: Maybe Int limit = case newClientType c of @@ -170,7 +170,7 @@ addClientWithReAuthPolicy reAuthPolicy u newId c maxPermClients loc cps = do prm = (u, newId, now, newClientType c, newClientLabel c, newClientClass c, newClientCookie c, lat, lon, mdl, C.Set . Set.toList <$> cps) retry x5 $ write insertClient (params LocalQuorum prm) addMLSPublicKeys u newId (Map.assocs (newClientMLSPublicKeys c)) - return + pure $! Client { clientId = newId, clientType = newClientType c, @@ -265,8 +265,8 @@ updatePrekeys u c pks = do check a b = do i <- CryptoBox.isPrekey b case i of - Success n -> return (CryptoBox.prekeyId n == keyId (prekeyId a)) - _ -> return False + Success n -> pure (CryptoBox.prekeyId n == keyId (prekeyId a)) + _ -> pure False claimPrekey :: ( Log.MonadLogger m, @@ -298,8 +298,8 @@ claimPrekey u c = field "user" (toByteString u) . field "client" (toByteString c) . msg (val "last resort prekey used") - return $ Just (ClientPrekey c (Prekey i k)) - removeAndReturnPreKey Nothing = return Nothing + pure $ Just (ClientPrekey c (Prekey i k)) + removeAndReturnPreKey Nothing = pure Nothing pickRandomPrekey :: MonadIO f => [(PrekeyId, Text)] -> f (Maybe (PrekeyId, Text)) pickRandomPrekey [] = pure Nothing @@ -309,7 +309,7 @@ claimPrekey u c = pickRandomPrekey pks = do let pks' = filter (\k -> fst k /= lastPrekeyId) pks ind <- liftIO $ randomRIO (0, length pks' - 1) - return $ atMay pks' ind + pure $ atMay pks' ind lookupMLSPublicKey :: MonadClient m => @@ -488,13 +488,13 @@ withOptLock :: withOptLock u c ma = go (10 :: Int) where go !n = do - v <- (version =<<) <$> execDyn return get + v <- (version =<<) <$> execDyn pure get a <- ma - r <- execDyn return (put v) + r <- execDyn pure (put v) case r of Nothing | n > 0 -> reportAttemptFailure >> go (n - 1) - Nothing -> reportFailureAndLogError >> return a - Just _ -> return a + Nothing -> reportFailureAndLogError >> pure a + Just _ -> pure a version :: AWS.GetItemResponse -> Maybe Word32 version v = conv =<< HashMap.lookup ddbVersion (view AWS.getItemResponse_item v) where @@ -549,13 +549,13 @@ withOptLock u c ma = go (10 :: Int) IO (Maybe y) execDyn' e m conv cmd = recovering policy handlers (const run) where - run = execCatch e cmd >>= either handleErr (return . conv) + run = execCatch e cmd >>= either handleErr (pure . conv) handlers = httpHandlers ++ [const $ EL.handler_ AWS._ConditionalCheckFailedException (pure True)] policy = limitRetries 3 <> exponentialBackoff 100000 handleErr (AWS.ServiceError se) | se ^. AWS.serviceCode == AWS.ErrorCode "ProvisionedThroughputExceeded" = do Metrics.counterIncr (Metrics.path "client.opt_lock.provisioned_throughput_exceeded") m - return Nothing - handleErr _ = return Nothing + pure Nothing + handleErr _ = pure Nothing withLocalLock :: (MonadMask m, MonadIO m) => MVar () -> m a -> m a withLocalLock l ma = do diff --git a/services/brig/src/Brig/Data/Connection.hs b/services/brig/src/Brig/Data/Connection.hs index 428df573f8..906a94d811 100644 --- a/services/brig/src/Brig/Data/Connection.hs +++ b/services/brig/src/Brig/Data/Connection.hs @@ -290,7 +290,7 @@ countConnections u r = do rels <- retry x1 . query selectStatus $ params One (Identity (tUnqualified u)) relsRemote <- retry x1 . query selectStatusRemote $ params One (Identity (tUnqualified u)) - return $ foldl' count 0 rels + foldl' count 0 relsRemote + pure $ foldl' count 0 rels + foldl' count 0 relsRemote where selectStatus :: QueryString R (Identity UserId) (Identity RelationWithHistory) selectStatus = "SELECT status FROM connection WHERE left = ?" diff --git a/services/brig/src/Brig/Data/Instances.hs b/services/brig/src/Brig/Data/Instances.hs index 7b61939285..feeb356b8e 100644 --- a/services/brig/src/Brig/Data/Instances.hs +++ b/services/brig/src/Brig/Data/Instances.hs @@ -74,7 +74,7 @@ instance Cql Email where ctype = Tagged TextColumn fromCql (CqlText t) = case parseEmail t of - Just e -> return e + Just e -> pure e Nothing -> Left "fromCql: Invalid email" fromCql _ = Left "fromCql: email: CqlText expected" @@ -84,7 +84,7 @@ instance Cql UserSSOId where ctype = Tagged TextColumn fromCql (CqlText t) = case eitherDecode $ cs t of - Right i -> return i + Right i -> pure i Left msg -> Left $ "fromCql: Invalid UserSSOId: " ++ msg fromCql _ = Left "fromCql: UserSSOId: CqlText expected" @@ -129,8 +129,8 @@ instance Cql Pict where fromCql (CqlList l) = do vs <- map (\(Blob lbs) -> lbs) <$> mapM fromCql l as <- mapM (note "Failed to read asset" . JSON.decode) vs - return $ Pict as - fromCql _ = return noPict + pure $ Pict as + fromCql _ = pure noPict toCql = toCql . map (Blob . JSON.encode) . fromPict @@ -145,8 +145,8 @@ instance Cql AssetKey where instance Cql AssetSize where ctype = Tagged IntColumn - fromCql (CqlInt 0) = return AssetPreview - fromCql (CqlInt 1) = return AssetComplete + fromCql (CqlInt 0) = pure AssetPreview + fromCql (CqlInt 1) = pure AssetComplete fromCql n = Left $ "Unexpected asset size: " ++ show n toCql AssetPreview = CqlInt 0 @@ -171,7 +171,7 @@ instance Cql Asset where k <- required "key" s <- optional "size" case (t :: Int32) of - 0 -> return $! ImageAsset k s + 0 -> pure $! ImageAsset k s _ -> Left $ "unexpected user asset type: " ++ show t where required :: Cql r => Text -> Either String r @@ -201,11 +201,11 @@ instance Cql AccountStatus where toCql PendingInvitation = CqlInt 4 fromCql (CqlInt i) = case i of - 0 -> return Active - 1 -> return Suspended - 2 -> return Deleted - 3 -> return Ephemeral - 4 -> return PendingInvitation + 0 -> pure Active + 1 -> pure Suspended + 2 -> pure Deleted + 3 -> pure Ephemeral + 4 -> pure PendingInvitation n -> Left $ "unexpected account status: " ++ show n fromCql _ = Left "account status: int expected" @@ -215,9 +215,9 @@ instance Cql ClientType where toCql PermanentClientType = CqlInt 1 toCql LegalHoldClientType = CqlInt 2 - fromCql (CqlInt 0) = return TemporaryClientType - fromCql (CqlInt 1) = return PermanentClientType - fromCql (CqlInt 2) = return LegalHoldClientType + fromCql (CqlInt 0) = pure TemporaryClientType + fromCql (CqlInt 1) = pure PermanentClientType + fromCql (CqlInt 2) = pure LegalHoldClientType fromCql _ = Left "ClientType: Int [0, 2] expected" instance Cql ClientClass where @@ -227,10 +227,10 @@ instance Cql ClientClass where toCql DesktopClient = CqlInt 2 toCql LegalHoldClient = CqlInt 3 - fromCql (CqlInt 0) = return PhoneClient - fromCql (CqlInt 1) = return TabletClient - fromCql (CqlInt 2) = return DesktopClient - fromCql (CqlInt 3) = return LegalHoldClient + fromCql (CqlInt 0) = pure PhoneClient + fromCql (CqlInt 1) = pure TabletClient + fromCql (CqlInt 2) = pure DesktopClient + fromCql (CqlInt 3) = pure LegalHoldClient fromCql _ = Left "ClientClass: Int [0, 3] expected" instance Cql RawPropertyValue where @@ -244,7 +244,7 @@ instance Cql Country where toCql = toCql . con2Text fromCql (CqlAscii c) = case parseCountry c of - Just c' -> return c' + Just c' -> pure c' Nothing -> Left "Country: ISO 3166-1-alpha2 expected." fromCql _ = Left "Country: ASCII expected" @@ -253,15 +253,15 @@ instance Cql Language where toCql = toCql . lan2Text fromCql (CqlAscii l) = case parseLanguage l of - Just l' -> return l' + Just l' -> pure l' Nothing -> Left "Language: ISO 639-1 expected." fromCql _ = Left "Language: ASCII expected" instance Cql ManagedBy where ctype = Tagged IntColumn - fromCql (CqlInt 0) = return ManagedByWire - fromCql (CqlInt 1) = return ManagedByScim + fromCql (CqlInt 0) = pure ManagedByWire + fromCql (CqlInt 1) = pure ManagedByScim fromCql n = Left $ "Unexpected ManagedBy: " ++ show n toCql ManagedByWire = CqlInt 0 diff --git a/services/brig/src/Brig/Data/LoginCode.hs b/services/brig/src/Brig/Data/LoginCode.hs index 4ac76a2c42..8a93ebcf48 100644 --- a/services/brig/src/Brig/Data/LoginCode.hs +++ b/services/brig/src/Brig/Data/LoginCode.hs @@ -53,7 +53,7 @@ createLoginCode u = do now <- liftIO =<< view currentTime code <- liftIO genCode insertLoginCode u code maxAttempts (ttl `addUTCTime` now) - return $! PendingLoginCode code (Timeout ttl) + pure $! PendingLoginCode code (Timeout ttl) where genCode = LoginCode . T.pack . printf "%06d" <$> randIntegerZeroToNMinusOne 1000000 @@ -62,18 +62,18 @@ verifyLoginCode u c = do code <- retry x1 (query1 codeSelect (params LocalQuorum (Identity u))) now <- liftIO =<< view currentTime case code of - Just (c', _, t) | c == c' && t >= now -> deleteLoginCode u >> return True - Just (c', n, t) | n > 1 && t > now -> insertLoginCode u c' (n - 1) t >> return False - Just (_, _, _) -> deleteLoginCode u >> return False - Nothing -> return False + Just (c', _, t) | c == c' && t >= now -> deleteLoginCode u >> pure True + Just (c', n, t) | n > 1 && t > now -> insertLoginCode u c' (n - 1) t >> pure False + Just (_, _, _) -> deleteLoginCode u >> pure False + Nothing -> pure False lookupLoginCode :: (MonadReader Env m, MonadClient m) => UserId -> m (Maybe PendingLoginCode) lookupLoginCode u = do now <- liftIO =<< view currentTime validate now =<< retry x1 (query1 codeSelect (params LocalQuorum (Identity u))) where - validate now (Just (c, _, t)) | now < t = return (Just (pending c now t)) - validate _ _ = return Nothing + validate now (Just (c, _, t)) | now < t = pure (Just (pending c now t)) + validate _ _ = pure Nothing pending c now t = PendingLoginCode c (timeout now t) timeout now t = Timeout (t `diffUTCTime` now) diff --git a/services/brig/src/Brig/Data/MLS/KeyPackage.hs b/services/brig/src/Brig/Data/MLS/KeyPackage.hs index 1239eb82b1..a2d6b78459 100644 --- a/services/brig/src/Brig/Data/MLS/KeyPackage.hs +++ b/services/brig/src/Brig/Data/MLS/KeyPackage.hs @@ -123,8 +123,8 @@ keyPackageRefSetConvId ref convId = do { serialConsistency = Just LocalSerialConsistency } case updated of - [] -> return False - [_] -> return True + [] -> pure False + [_] -> pure True _ -> throwM $ ErrorCall "Primary key violation detected mls_key_package_refs.ref" where q :: PrepQuery W (Domain, ConvId, KeyPackageRef) x diff --git a/services/brig/src/Brig/Data/User.hs b/services/brig/src/Brig/Data/User.hs index d60bca1680..1cc046c4e1 100644 --- a/services/brig/src/Brig/Data/User.hs +++ b/services/brig/src/Brig/Data/User.hs @@ -132,7 +132,7 @@ newAccount u inv tid mbHandle = do (Just (toUUID -> uuid), _) -> pure uuid (_, Just uuid) -> pure uuid (Nothing, Nothing) -> liftIO nextRandom - passwd <- maybe (return Nothing) (fmap Just . liftIO . mkSafePassword) pass + passwd <- maybe (pure Nothing) (fmap Just . liftIO . mkSafePassword) pass expiry <- case status of Ephemeral -> do -- Ephemeral users' expiry time is in expires_in (default sessionTokenTimeout) seconds @@ -140,9 +140,9 @@ newAccount u inv tid mbHandle = do let ZAuth.SessionTokenTimeout defTTL = e ^. ZAuth.settings . ZAuth.sessionTokenTimeout ttl = maybe defTTL fromRange (newUserExpiresIn u) now <- liftIO =<< view currentTime - return . Just . toUTCTimeMillis $ addUTCTime (fromIntegral ttl) now - _ -> return Nothing - return (UserAccount (user uid domain (locale defLoc) expiry) status, passwd) + pure . Just . toUTCTimeMillis $ addUTCTime (fromIntegral ttl) now + _ -> pure Nothing + pure (UserAccount (user uid domain (locale defLoc) expiry) status, passwd) where ident = newUserIdentity u pass = newUserPassword u @@ -162,7 +162,7 @@ newAccountInviteViaScim :: (MonadClient m, MonadReader Env m) => UserId -> TeamI newAccountInviteViaScim uid tid locale name email = do defLoc <- setDefaultUserLocale <$> view settings domain <- viewFederationDomain - return (UserAccount (user domain (fromMaybe defLoc locale)) PendingInvitation) + pure (UserAccount (user domain (fromMaybe defLoc locale)) PendingInvitation) where user domain loc = User @@ -703,7 +703,7 @@ toUserAccount managed_by ) = let ident = toIdentity activated email phone ssoid - deleted = maybe False (== Deleted) status + deleted = Just Deleted == status expiration = if status == Just Ephemeral then expires else Nothing loc = toLocale defaultLocale (lan, con) svc = newServiceRef <$> sid <*> pid @@ -777,7 +777,7 @@ toUsers domain defaultLocale havePendingInvitations = fmap mk . filter fp managed_by ) = let ident = toIdentity activated email phone ssoid - deleted = maybe False (== Deleted) status + deleted = Just Deleted == status expiration = if status == Just Ephemeral then expires else Nothing loc = toLocale defaultLocale (lan, con) svc = newServiceRef <$> sid <*> pid diff --git a/services/brig/src/Brig/Data/UserKey.hs b/services/brig/src/Brig/Data/UserKey.hs index d9afe3af53..027fbac7d1 100644 --- a/services/brig/src/Brig/Data/UserKey.hs +++ b/services/brig/src/Brig/Data/UserKey.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE GeneralizedNewtypeDeriving #-} - -- This file is part of the Wire Server implementation. -- -- Copyright (C) 2022 Wire Swiss GmbH @@ -70,8 +68,8 @@ instance Cql UKHashType where ctype = Tagged IntColumn fromCql (CqlInt i) = case i of - 0 -> return UKHashPhone - 1 -> return UKHashEmail + 0 -> pure UKHashPhone + 1 -> pure UKHashEmail n -> Left $ "unexpected hashtype: " ++ show n fromCql _ = Left "userkeyhashtype: int expected" @@ -85,7 +83,7 @@ instance Cql UserKeyHash where fromCql (CqlBlob lbs) = case MH.decode (toStrict lbs) of Left e -> Left ("userkeyhash: " ++ e) - Right h -> return $ UserKeyHash h + Right h -> pure $ UserKeyHash h fromCql _ = Left "userkeyhash: expected blob" toCql (UserKeyHash d) = CqlBlob $ MH.encode (MH.algorithm d) (MH.digest d) @@ -129,7 +127,7 @@ claimKey :: claimKey k u = do free <- keyAvailable k (Just u) when free (insertKey u k) - return free + pure free -- | Check whether a 'UserKey' is available. -- A key is available if it is not already actived for another user or @@ -144,8 +142,8 @@ keyAvailable :: keyAvailable k u = do o <- lookupKey k case (o, u) of - (Nothing, _) -> return True - (Just x, Just y) | x == y -> return True + (Nothing, _) -> pure True + (Just x, Just y) | x == y -> pure True (Just x, _) -> not <$> User.isActivated x lookupKey :: MonadClient m => UserKey -> m (Maybe UserId) @@ -170,7 +168,7 @@ hashKey :: MonadReader Env m => UserKey -> m UserKeyHash hashKey uk = do d <- view digestSHA256 let d' = digestBS d $ T.encodeUtf8 (keyText uk) - return . UserKeyHash $ + pure . UserKeyHash $ MH.MultihashDigest MH.SHA256 (B.length d') d' lookupPhoneHashes :: MonadClient m => [ByteString] -> m [(ByteString, UserId)] diff --git a/services/brig/src/Brig/Data/UserPendingActivation.hs b/services/brig/src/Brig/Data/UserPendingActivation.hs index 2388479446..23a5668428 100644 --- a/services/brig/src/Brig/Data/UserPendingActivation.hs +++ b/services/brig/src/Brig/Data/UserPendingActivation.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE GeneralizedNewtypeDeriving #-} - -- This file is part of the Wire Server implementation. -- -- Copyright (C) 2022 Wire Swiss GmbH diff --git a/services/brig/src/Brig/IO/Intra.hs b/services/brig/src/Brig/IO/Intra.hs index afbdec1a85..1a17770abb 100644 --- a/services/brig/src/Brig/IO/Intra.hs +++ b/services/brig/src/Brig/IO/Intra.hs @@ -173,7 +173,7 @@ onConnectionEvent orig conn evt = do orig Push.RouteAny conn - (return $ list1 from []) + (pure $ list1 from []) onPropertyEvent :: -- | Originator of the event. @@ -189,7 +189,7 @@ onPropertyEvent orig conn e = orig Push.RouteDirect (Just conn) - (return $ list1 orig []) + (pure $ list1 orig []) onClientEvent :: -- | Originator of the event. @@ -221,13 +221,13 @@ updateSearchIndex :: m () updateSearchIndex orig e = case e of -- no-ops - UserCreated {} -> return () + UserCreated {} -> pure () UserIdentityUpdated UserIdentityUpdatedData {..} -> do when (isJust eiuEmail) $ Search.reindex orig - UserIdentityRemoved {} -> return () - UserLegalHoldDisabled {} -> return () - UserLegalHoldEnabled {} -> return () - LegalHoldClientRequested {} -> return () + UserIdentityRemoved {} -> pure () + UserLegalHoldDisabled {} -> pure () + UserLegalHoldEnabled {} -> pure () + LegalHoldClientRequested {} -> pure () UserSuspended {} -> Search.reindex orig UserResumed {} -> Search.reindex orig UserActivated {} -> Search.reindex orig @@ -258,7 +258,7 @@ journalEvent orig e = case e of UserDeleted {} -> Journal.userDelete orig _ -> - return () + pure () ------------------------------------------------------------------------------- -- Low-Level Event Notification @@ -282,9 +282,9 @@ dispatchNotifications :: UserEvent -> m () dispatchNotifications orig conn e = case e of - UserCreated {} -> return () - UserSuspended {} -> return () - UserResumed {} -> return () + UserCreated {} -> pure () + UserSuspended {} -> pure () + UserResumed {} -> pure () LegalHoldClientRequested {} -> notifyContacts event orig Push.RouteAny conn UserLegalHoldDisabled {} -> notifyContacts event orig Push.RouteAny conn UserLegalHoldEnabled {} -> notifyContacts event orig Push.RouteAny conn @@ -334,7 +334,7 @@ notifyUserDeletionRemotes :: notifyUserDeletionRemotes deleted = do runConduit $ Data.lookupRemoteConnectedUsersC deleted (fromInteger (natVal (Proxy @UserDeletedNotificationMaxConnections))) - .| C.mapM_ (fanoutNotifications) + .| C.mapM_ fanoutNotifications where fanoutNotifications :: [Remote UserId] -> m () fanoutNotifications = mapM_ notifyBackend . bucketRemote @@ -482,7 +482,7 @@ fork u ma = do let logErr e = ExLog.err g $ request r ~~ user u ~~ msg (show e) withRunInIO $ \lower -> void . liftIO . forkIO $ - either logErr (const $ return ()) + either logErr (const $ pure ()) =<< runExceptT (syncIO $ lower ma) where request = field "request" . unRequestId @@ -542,8 +542,8 @@ notifyContacts events orig route conn = do screenMemberList :: Maybe Team.TeamMemberList -> m [UserId] screenMemberList (Just mems) | mems ^. Team.teamMemberListType == Team.ListComplete = - return $ fmap (view Team.userId) (mems ^. Team.teamMembers) - screenMemberList _ = return [] + pure $ fmap (view Team.userId) (mems ^. Team.teamMembers) + screenMemberList _ = pure [] -- Event Serialisation: @@ -754,7 +754,7 @@ createLocalConnectConv from to cname conn = do . lbytes (encode $ Connect (qUntagged to) Nothing cname Nothing) . expect2xx r <- galleyRequest POST req - maybe (error "invalid conv id") return $ + maybe (error "invalid conv id") pure $ fromByteString $ getHeader' "Location" r @@ -911,7 +911,7 @@ getConv usr cnv = do rs <- galleyRequest GET req case Bilge.statusCode rs of 200 -> Just <$> decodeBody "galley" rs - _ -> return Nothing + _ -> pure Nothing where req = paths ["conversations", toByteString' cnv] @@ -960,7 +960,7 @@ getTeamConv usr tid cnv = do rs <- galleyRequest GET req case Bilge.statusCode rs of 200 -> Just <$> decodeBody "galley" rs - _ -> return Nothing + _ -> pure Nothing where req = paths ["teams", toByteString' tid, "conversations", toByteString' cnv] @@ -1110,10 +1110,10 @@ checkUserCanJoinTeam tid = do remote "galley" . msg (val "Check if can add member to team") rs <- galleyRequest GET req - return $ case Bilge.statusCode rs of + pure $ case Bilge.statusCode rs of 200 -> Nothing _ -> case decodeBody "galley" rs of - Just (e :: Wai.Error) -> return e + Just (e :: Wai.Error) -> pure e Nothing -> error ("Invalid response from galley: " <> show rs) where req = @@ -1138,7 +1138,7 @@ addTeamMember u tid (minvmeta, role) = do remote "galley" . msg (val "Adding member to team") rs <- galleyRequest POST req - return $ case Bilge.statusCode rs of + pure $ case Bilge.statusCode rs of 200 -> True _ -> False where @@ -1170,10 +1170,10 @@ createTeam u t@(Team.BindingNewTeam bt) teamid = do . msg (val "Creating Team") r <- galleyRequest PUT $ req teamid tid <- - maybe (error "invalid team id") return $ + maybe (error "invalid team id") pure $ fromByteString $ getHeader' "Location" r - return (CreateUserTeam tid $ fromRange (bt ^. Team.newTeamName)) + pure (CreateUserTeam tid $ fromRange (bt ^. Team.newTeamName)) where req tid = paths ["i", "teams", toByteString' tid] @@ -1201,7 +1201,7 @@ getTeamMember u tid = do rs <- galleyRequest GET req case Bilge.statusCode rs of 200 -> Just <$> decodeBody "galley" rs - _ -> return Nothing + _ -> pure Nothing where req = paths ["i", "teams", toByteString' tid, "members", toByteString' u] @@ -1265,7 +1265,7 @@ getTeamContacts u = do rs <- galleyRequest GET req case Bilge.statusCode rs of 200 -> Just <$> decodeBody "galley" rs - _ -> return Nothing + _ -> pure Nothing where req = paths ["i", "users", toByteString' u, "team", "members"] @@ -1287,7 +1287,7 @@ getTeamId u = do rs <- galleyRequest GET req case Bilge.statusCode rs of 200 -> Just <$> decodeBody "galley" rs - _ -> return Nothing + _ -> pure Nothing where req = paths ["i", "users", toByteString' u, "team"] diff --git a/services/brig/src/Brig/IO/Journal.hs b/services/brig/src/Brig/IO/Journal.hs index c612c4fc7a..2ebe6b102a 100644 --- a/services/brig/src/Brig/IO/Journal.hs +++ b/services/brig/src/Brig/IO/Journal.hs @@ -51,7 +51,7 @@ userActivate :: (MonadReader Env m, MonadIO m) => User -> m () userActivate u@User {..} = journalEvent UserEvent'USER_ACTIVATE userId (userEmail u) (Just userLocale) userTeam (Just userDisplayName) userUpdate :: (MonadReader Env m, MonadIO m) => UserId -> Maybe Email -> Maybe Locale -> Maybe Name -> m () -userUpdate uid em loc nm = journalEvent UserEvent'USER_UPDATE uid em loc Nothing nm +userUpdate uid em loc = journalEvent UserEvent'USER_UPDATE uid em loc Nothing userEmailRemove :: (MonadReader Env m, MonadIO m) => UserId -> Email -> m () userEmailRemove uid em = journalEvent UserEvent'USER_EMAIL_REMOVE uid (Just em) Nothing Nothing Nothing @@ -67,7 +67,7 @@ journalEvent typ uid em loc tid nm = let userEvent :: UserEvent = defMessage & U.eventType .~ typ - & U.userId .~ (toBytes uid) + & U.userId .~ toBytes uid & U.utcTime .~ ts & U.maybe'email .~ (toByteString' <$> em) & U.maybe'locale .~ (pack . show <$> loc) diff --git a/services/brig/src/Brig/Index/Options.hs b/services/brig/src/Brig/Index/Options.hs index 5935684a41..c614172794 100644 --- a/services/brig/src/Brig/Index/Options.hs +++ b/services/brig/src/Brig/Index/Options.hs @@ -200,27 +200,25 @@ elasticSettingsParser = ) templateParser :: Parser (Maybe ES.TemplateName) = ES.TemplateName - <$$> ( optional - ( option - str - ( long "delete-template" - <> metavar "TEMPLATE_NAME" - <> help "Delete this ES template before creating a new index" - ) - ) - ) + <$$> optional + ( option + str + ( long "delete-template" + <> metavar "TEMPLATE_NAME" + <> help "Delete this ES template before creating a new index" + ) + ) cassandraSettingsParser :: Parser CassandraSettings cassandraSettingsParser = CassandraSettings - <$> ( strOption - ( long "cassandra-host" - <> metavar "HOST" - <> help "Cassandra Host." - <> value (_cHost localCassandraSettings) - <> showDefault - ) - ) + <$> strOption + ( long "cassandra-host" + <> metavar "HOST" + <> help "Cassandra Host." + <> value (_cHost localCassandraSettings) + <> showDefault + ) <*> option auto ( long "cassandra-port" @@ -257,36 +255,33 @@ reindexToAnotherIndexSettingsParser = <> help "Elasticsearch index name to reindex to" ) ) - <*> ( option - auto - ( long "timeout" - <> metavar "SECONDS" - <> help "Number of seconds to wait for reindexing to complete. The reindexing will not be cancelled when this timeout expires." - <> value 600 - <> showDefault - ) - ) + <*> option + auto + ( long "timeout" + <> metavar "SECONDS" + <> help "Number of seconds to wait for reindexing to complete. The reindexing will not be cancelled when this timeout expires." + <> value 600 + <> showDefault + ) galleyEndpointParser :: Parser Endpoint galleyEndpointParser = Endpoint - <$> ( strOption - ( long "galley-host" - <> help "Hostname or IP address of galley" - <> metavar "HOSTNAME" - <> value "localhost" - <> showDefault - ) - ) - <*> ( option - auto - ( long "galley-port" - <> help "Port number of galley" - <> metavar "PORT" - <> value 8085 - <> showDefault - ) - ) + <$> strOption + ( long "galley-host" + <> help "Hostname or IP address of galley" + <> metavar "HOSTNAME" + <> value "localhost" + <> showDefault + ) + <*> option + auto + ( long "galley-port" + <> help "Port number of galley" + <> metavar "PORT" + <> value 8085 + <> showDefault + ) commandParser :: Parser Command commandParser = @@ -295,7 +290,7 @@ commandParser = "create" ( info (Create <$> elasticSettingsParser <*> galleyEndpointParser) - (progDesc ("Create the ES user index, if it doesn't already exist. ")) + (progDesc "Create the ES user index, if it doesn't already exist. ") ) <> command "update-mapping" @@ -307,7 +302,7 @@ commandParser = "reset" ( info (Reset <$> restrictedElasticSettingsParser <*> galleyEndpointParser) - (progDesc ("Delete and re-create the ES user index. Only works on a test index (directory_test).")) + (progDesc "Delete and re-create the ES user index. Only works on a test index (directory_test).") ) <> command "reindex" diff --git a/services/brig/src/Brig/InternalEvent/Types.hs b/services/brig/src/Brig/InternalEvent/Types.hs index b5cf86800d..c9ac85e3ac 100644 --- a/services/brig/src/Brig/InternalEvent/Types.hs +++ b/services/brig/src/Brig/InternalEvent/Types.hs @@ -36,8 +36,8 @@ data InternalNotificationType instance FromJSON InternalNotificationType where parseJSON = \case - "user.delete" -> return UserDeletion - "service.delete" -> return ServiceDeletion + "user.delete" -> pure UserDeletion + "service.delete" -> pure ServiceDeletion x -> fail $ "InternalNotificationType: Unknown type " <> show x instance ToJSON InternalNotificationType where diff --git a/services/brig/src/Brig/Password.hs b/services/brig/src/Brig/Password.hs index d5889d1be7..9c52d9268e 100644 --- a/services/brig/src/Brig/Password.hs +++ b/services/brig/src/Brig/Password.hs @@ -42,7 +42,7 @@ instance Show Password where instance Cql Password where ctype = Tagged BlobColumn - fromCql (CqlBlob lbs) = return . Password . EncryptedPass $ toStrict lbs + fromCql (CqlBlob lbs) = pure . Password . EncryptedPass $ toStrict lbs fromCql _ = Left "password: expected blob" toCql = CqlBlob . fromStrict . getEncryptedPass . fromPassword diff --git a/services/brig/src/Brig/Phone.hs b/services/brig/src/Brig/Phone.hs index c8c54f048a..44eb72f796 100644 --- a/services/brig/src/Brig/Phone.hs +++ b/services/brig/src/Brig/Phone.hs @@ -93,12 +93,12 @@ sendCall call = unless (isTestPhone $ Nexmo.callTo call) $ do Nexmo.CallUnroutable -> unreachable ex Nexmo.CallDestinationBarred -> barred ex _ -> throwM ex - Right _ -> return () + Right _ -> pure () where nexmoHandlers = httpHandlers ++ [ const . Handler $ \(ex :: Nexmo.CallErrorResponse) -> - return $ case Nexmo.caStatus ex of + pure $ case Nexmo.caStatus ex of Nexmo.CallThrottled -> True Nexmo.CallInternal -> True _ -> False @@ -140,7 +140,7 @@ sendSms loc SMSMessage {..} = unless (isTestPhone smsTo) $ do 21610 -> barred ex' -- A real problem _ -> throwM ex' - Right () -> return () + Right () -> pure () where sendNexmoSms :: (MonadIO f, MonadReader Env f) => Manager -> f () sendNexmoSms mgr = do @@ -167,14 +167,14 @@ sendSms loc SMSMessage {..} = unless (isTestPhone smsTo) $ do Twilio.sendMessage crd mgr (Twilio.Message smsFrom smsTo smsText) nexmoFailed = [ Handler $ \(ex :: HttpException) -> - return (Just (SomeException ex)), + pure (Just (SomeException ex)), Handler $ \(ex :: Nexmo.MessageErrorResponse) -> - return (Just (SomeException ex)) + pure (Just (SomeException ex)) ] nexmoHandlers = httpHandlers ++ [ const . Handler $ \(ex :: Nexmo.MessageErrorResponse) -> - return $ case Nexmo.erStatus ex of + pure $ case Nexmo.erStatus ex of Nexmo.MessageThrottled -> True Nexmo.MessageInternal -> True Nexmo.MessageCommunicationFailed -> True @@ -183,7 +183,7 @@ sendSms loc SMSMessage {..} = unless (isTestPhone smsTo) $ do twilioHandlers = httpHandlers ++ [ const . Handler $ \(ex :: Twilio.ErrorResponse) -> - return $ case Twilio.errStatus ex of + pure $ case Twilio.errStatus ex of 20429 -> True -- Too Many Requests 20500 -> True -- Internal Server Error 20503 -> True -- Temporarily Unavailable @@ -204,7 +204,7 @@ sendSms loc SMSMessage {..} = unless (isTestPhone smsTo) $ do -- E.164 format of the given phone number on success. validatePhone :: (MonadClient m, MonadReader Env m) => Phone -> m (Maybe Phone) validatePhone (Phone p) - | isTestPhone p = return (Just (Phone p)) + | isTestPhone p = pure (Just (Phone p)) | otherwise = do c <- view twilioCreds m <- view httpManager @@ -214,8 +214,8 @@ validatePhone (Phone p) const $ Twilio.lookupPhone c m p LookupNoDetail Nothing case r of - Right x -> return (Just (Phone (Twilio.lookupE164 x))) - Left e | Twilio.errStatus e == 404 -> return Nothing + Right x -> pure (Just (Phone (Twilio.lookupE164 x))) + Left e | Twilio.errStatus e == 404 -> pure Nothing Left e -> throwM e isTestPhone :: Text -> Bool @@ -254,7 +254,7 @@ withSmsBudget phone go = do msg (val "SMS budget deducted.") ~~ field "budget" b ~~ field "phone" phone - return a + pure a -------------------------------------------------------------------------------- -- Voice Call Budgeting @@ -289,7 +289,7 @@ withCallBudget phone go = do msg (val "Voice call budget deducted.") ~~ field "budget" b ~~ field "phone" phone - return a + pure a -------------------------------------------------------------------------------- -- Unique Keys diff --git a/services/brig/src/Brig/Provider/API.hs b/services/brig/src/Brig/Provider/API.hs index eb273b4402..8a8f96c561 100644 --- a/services/brig/src/Brig/Provider/API.hs +++ b/services/brig/src/Brig/Provider/API.hs @@ -332,7 +332,7 @@ newAccountH req = do newAccount :: Public.NewProvider -> (Handler r) Public.NewProviderResponse newAccount new = do email <- case validateEmail (Public.newProviderEmail new) of - Right em -> return em + Right em -> pure em Left _ -> throwStd (errorToWai @'InvalidEmail) let name = Public.newProviderName new let pass = Public.newProviderPassword new @@ -345,7 +345,7 @@ newAccount new = do Nothing -> do newPass <- genPassword safePass <- mkSafePassword newPass - return (safePass, Just newPass) + pure (safePass, Just newPass) pid <- wrapClientE $ DB.insertAccount name safePass url descr gen <- Code.mkGen (Code.ForEmail email) code <- @@ -359,7 +359,7 @@ newAccount new = do let key = Code.codeKey code let val = Code.codeValue code lift $ sendActivationMail name email key val False - return $ Public.NewProviderResponse pid newPass + pure $ Public.NewProviderResponse pid newPass activateAccountKeyH :: Code.Key ::: Code.Value -> (Handler r) Response activateAccountKeyH (key ::: val) = do @@ -370,23 +370,23 @@ activateAccountKey :: Code.Key -> Code.Value -> (Handler r) (Maybe Public.Provid activateAccountKey key val = do c <- wrapClientE (Code.verify key Code.IdentityVerification val) >>= maybeInvalidCode (pid, email) <- case (Code.codeAccount c, Code.codeForEmail c) of - (Just p, Just e) -> return (Id p, e) + (Just p, Just e) -> pure (Id p, e) _ -> throwStd (errorToWai @'InvalidCode) (name, memail, _url, _descr) <- wrapClientE (DB.lookupAccountData pid) >>= maybeInvalidCode case memail of - Just email' | email == email' -> return Nothing + Just email' | email == email' -> pure Nothing Just email' -> do -- Ensure we remove any pending password reset gen <- Code.mkGen (Code.ForEmail email') lift $ wrapClient $ Code.delete (Code.genKey gen) Code.PasswordReset -- Activate the new and remove the old key activate pid (Just email') email - return . Just $ Public.ProviderActivationResponse email + pure . Just $ Public.ProviderActivationResponse email -- Immediate approval for everybody (for now). Nothing -> do activate pid Nothing email lift $ sendApprovalConfirmMail name email - return . Just $ Public.ProviderActivationResponse email + pure . Just $ Public.ProviderActivationResponse email getActivationCodeH :: Public.Email -> (Handler r) Response getActivationCodeH e = do @@ -396,11 +396,11 @@ getActivationCodeH e = do getActivationCode :: Public.Email -> (Handler r) FoundActivationCode getActivationCode e = do email <- case validateEmail e of - Right em -> return em + Right em -> pure em Left _ -> throwStd (errorToWai @'InvalidEmail) gen <- Code.mkGen (Code.ForEmail email) code <- wrapClientE $ Code.lookup (Code.genKey gen) Code.IdentityVerification - maybe (throwStd activationKeyNotFound) (return . FoundActivationCode) code + maybe (throwStd activationKeyNotFound) (pure . FoundActivationCode) code newtype FoundActivationCode = FoundActivationCode Code.Code @@ -514,7 +514,7 @@ updateAccountEmailH (pid ::: req) = do updateAccountEmail :: ProviderId -> Public.EmailUpdate -> (Handler r) () updateAccountEmail pid (Public.EmailUpdate new) = do email <- case validateEmail new of - Right em -> return em + Right em -> pure em Left _ -> throwStd (errorToWai @'InvalidEmail) let emailKey = mkEmailKey email wrapClientE (DB.lookupKey emailKey) >>= mapM_ (const $ throwStd emailExists) @@ -559,10 +559,10 @@ addService pid new = do let assets = newServiceAssets new let tags = fromRange (newServiceTags new) (pk, fp) <- validateServiceKey pubkey >>= maybeInvalidServiceKey - token <- maybe randServiceToken return (newServiceToken new) + token <- maybe randServiceToken pure (newServiceToken new) sid <- wrapClientE $ DB.insertService pid name summary descr baseUrl token pk fp assets tags let rstoken = maybe (Just token) (const Nothing) (newServiceToken new) - return $ Public.NewServiceResponse sid rstoken + pure $ Public.NewServiceResponse sid rstoken listServicesH :: ProviderId -> (Handler r) Response listServicesH pid = do @@ -736,8 +736,8 @@ deleteAccount :: Public.DeleteProvider -> ExceptT Error m () deleteAccount pid del = do - prov <- (DB.lookupAccount pid) >>= maybeInvalidProvider - pass <- (DB.lookupPassword pid) >>= maybeBadCredentials + prov <- DB.lookupAccount pid >>= maybeInvalidProvider + pass <- DB.lookupPassword pid >>= maybeBadCredentials unless (verifyPassword (deleteProviderPassword del) pass) $ throwStd (errorToWai @'BadCredentials) svcs <- DB.listServices pid @@ -828,7 +828,7 @@ getServiceTagListH () = do json <$> getServiceTagList () getServiceTagList :: () -> Monad m => m Public.ServiceTagList -getServiceTagList () = return (Public.ServiceTagList allTags) +getServiceTagList () = pure (Public.ServiceTagList allTags) where allTags = [(minBound :: Public.ServiceTag) ..] @@ -856,11 +856,11 @@ updateServiceWhitelist uid con tid upd = do -- Add to various tables whitelisted <- wrapClientE $ DB.getServiceWhitelistStatus tid pid sid case (whitelisted, newWhitelisted) of - (False, False) -> return UpdateServiceWhitelistRespUnchanged - (True, True) -> return UpdateServiceWhitelistRespUnchanged + (False, False) -> pure UpdateServiceWhitelistRespUnchanged + (True, True) -> pure UpdateServiceWhitelistRespUnchanged (False, True) -> do wrapClientE $ DB.insertServiceWhitelist tid pid sid - return UpdateServiceWhitelistRespChanged + pure UpdateServiceWhitelistRespChanged (True, False) -> do -- When the service is de-whitelisted, remove its bots from team -- conversations @@ -876,7 +876,7 @@ updateServiceWhitelist uid con tid upd = do ) ) wrapClientE $ DB.deleteServiceWhitelist (Just tid) pid sid - return UpdateServiceWhitelistRespChanged + pure UpdateServiceWhitelistRespChanged addBotH :: UserId ::: ConnId ::: ConvId ::: JsonRequest Public.AddBot -> (Handler r) Response addBotH (zuid ::: zcon ::: cid ::: req) = do @@ -947,7 +947,7 @@ addBot zuid zcon cid add = do -- Add the bot to the conversation ev <- lift $ RPC.addBotMember zuid zcon cid bid (clientId clt) pid sid - return $ + pure $ Public.AddBotResponse { Public.rsAddBotId = bid, Public.rsAddBotClient = bcl, @@ -973,9 +973,9 @@ removeBot zusr zcon cid bid = do let busr = botUserId bid let bot = List.find ((== busr) . qUnqualified . omQualifiedId) (cmOthers mems) case bot >>= omService of - Nothing -> return Nothing + Nothing -> pure Nothing Just _ -> do - lift $ Public.RemoveBotResponse <$$> (wrapHttpClient $ deleteBot zusr (Just zcon) bid cid) + lift $ Public.RemoveBotResponse <$$> wrapHttpClient (deleteBot zusr (Just zcon) bid cid) -------------------------------------------------------------------------------- -- Bot API @@ -988,7 +988,7 @@ botGetSelfH bot = do botGetSelf :: BotId -> (Handler r) Public.UserProfile botGetSelf bot = do p <- lift $ wrapClient $ User.lookupUser NoPendingInvitations (botUserId bot) - maybe (throwStd (errorToWai @'UserNotFound)) (return . (`Public.publicProfile` UserLegalHoldNoConsent)) p + maybe (throwStd (errorToWai @'UserNotFound)) (pure . (`Public.publicProfile` UserLegalHoldNoConsent)) p botGetClientH :: BotId -> (Handler r) Response botGetClientH bot = do @@ -1008,7 +1008,7 @@ botListPrekeys :: BotId -> (Handler r) [Public.PrekeyId] botListPrekeys bot = do clt <- lift $ listToMaybe <$> wrapClient (User.lookupClients (botUserId bot)) case clientId <$> clt of - Nothing -> return [] + Nothing -> pure [] Just ci -> lift (wrapClient $ User.lookupPrekeyIds (botUserId bot) ci) botUpdatePrekeysH :: BotId ::: JsonRequest Public.UpdateBotPrekeys -> (Handler r) Response @@ -1045,7 +1045,7 @@ botListUserProfilesH uids = do botListUserProfiles :: List UserId -> (Handler r) [Public.BotUserView] botListUserProfiles uids = do us <- lift . wrapClient $ User.lookupUsers NoPendingInvitations (fromList uids) - return (map mkBotUserView us) + pure (map mkBotUserView us) botGetUserClientsH :: UserId -> (Handler r) Response botGetUserClientsH uid = do @@ -1069,7 +1069,7 @@ botDeleteSelf bid cid = do bot <- lift . wrapClient $ User.lookupUser NoPendingInvitations (botUserId bid) _ <- maybeInvalidBot (userService =<< bot) _ <- lift $ wrapHttpClient $ deleteBot (botUserId bid) Nothing bid cid - return () + pure () -------------------------------------------------------------------------------- -- Utilities @@ -1129,28 +1129,28 @@ deleteBot zusr zcon bid cid = do -- TODO: Consider if we can actually delete the bot user entirely, -- i.e. not just marking the account as deleted. void $ runExceptT $ User.updateStatus buid Deleted - return ev + pure ev validateServiceKey :: MonadIO m => Public.ServiceKeyPEM -> m (Maybe (Public.ServiceKey, Fingerprint Rsa)) validateServiceKey pem = liftIO $ readPublicKey >>= \pk -> case SSL.toPublicKey =<< pk of - Nothing -> return Nothing + Nothing -> pure Nothing Just pk' -> do Just sha <- SSL.getDigestByName "SHA256" let size = SSL.rsaSize (pk' :: SSL.RSAPubKey) if size < minRsaKeySize - then return Nothing + then pure Nothing else do fpr <- Fingerprint <$> SSL.rsaFingerprint sha pk' let bits = fromIntegral size * 8 let key = Public.ServiceKey Public.RsaServiceKey bits pem - return $ Just (key, fpr) + pure $ Just (key, fpr) where readPublicKey = handleAny - (const $ return Nothing) + (const $ pure Nothing) (SSL.readPublicKey (LC8.unpack (toByteString pem)) <&> Just) mkBotUserView :: User -> Public.BotUserView @@ -1167,7 +1167,7 @@ setProviderCookie :: ZAuth.ProviderToken -> Response -> (Handler r) Response setProviderCookie t r = do s <- view settings let hdr = toByteString' (Cookie.renderSetCookie (cookie s)) - return (addHeader "Set-Cookie" hdr r) + pure (addHeader "Set-Cookie" hdr r) where cookie s = Cookie.def @@ -1180,34 +1180,34 @@ setProviderCookie t r = do } maybeInvalidProvider :: Monad m => Maybe a -> (ExceptT Error m) a -maybeInvalidProvider = maybe (throwStd invalidProvider) return +maybeInvalidProvider = maybe (throwStd invalidProvider) pure maybeInvalidCode :: Monad m => Maybe a -> (ExceptT Error m) a -maybeInvalidCode = maybe (throwStd (errorToWai @'InvalidCode)) return +maybeInvalidCode = maybe (throwStd (errorToWai @'InvalidCode)) pure maybeServiceNotFound :: Monad m => Maybe a -> (ExceptT Error m) a -maybeServiceNotFound = maybe (throwStd (notFound "Service not found")) return +maybeServiceNotFound = maybe (throwStd (notFound "Service not found")) pure maybeProviderNotFound :: Monad m => Maybe a -> (ExceptT Error m) a -maybeProviderNotFound = maybe (throwStd (notFound "Provider not found")) return +maybeProviderNotFound = maybe (throwStd (notFound "Provider not found")) pure maybeConvNotFound :: Monad m => Maybe a -> (ExceptT Error m) a -maybeConvNotFound = maybe (throwStd (notFound "Conversation not found")) return +maybeConvNotFound = maybe (throwStd (notFound "Conversation not found")) pure maybeBadCredentials :: Monad m => Maybe a -> (ExceptT Error m) a -maybeBadCredentials = maybe (throwStd (errorToWai @'BadCredentials)) return +maybeBadCredentials = maybe (throwStd (errorToWai @'BadCredentials)) pure maybeInvalidServiceKey :: Monad m => Maybe a -> (ExceptT Error m) a -maybeInvalidServiceKey = maybe (throwStd invalidServiceKey) return +maybeInvalidServiceKey = maybe (throwStd invalidServiceKey) pure maybeInvalidBot :: Monad m => Maybe a -> (ExceptT Error m) a -maybeInvalidBot = maybe (throwStd invalidBot) return +maybeInvalidBot = maybe (throwStd invalidBot) pure maybeInvalidUser :: Monad m => Maybe a -> (ExceptT Error m) a -maybeInvalidUser = maybe (throwStd (errorToWai @'InvalidUser)) return +maybeInvalidUser = maybe (throwStd (errorToWai @'InvalidUser)) pure rangeChecked :: (Within a n m, Monad monad) => a -> (ExceptT Error monad) (Range n m a) -rangeChecked = either (throwStd . invalidRange . fromString) return . checkedEither +rangeChecked = either (throwStd . invalidRange . fromString) pure . checkedEither invalidServiceKey :: Wai.Error invalidServiceKey = Wai.mkError status400 "invalid-service-key" "Invalid service key." diff --git a/services/brig/src/Brig/Provider/DB.hs b/services/brig/src/Brig/Provider/DB.hs index d2dc915989..bf14143ddf 100644 --- a/services/brig/src/Brig/Provider/DB.hs +++ b/services/brig/src/Brig/Provider/DB.hs @@ -52,7 +52,7 @@ insertAccount :: insertAccount name pass url descr = do pid <- randomId retry x5 $ write cql $ params LocalQuorum (pid, name, pass, url, descr) - return pid + pure pid where cql :: PrepQuery W (ProviderId, Name, Password, HttpsUrl, Text) () cql = "INSERT INTO provider (id, name, password, url, descr) VALUES (?, ?, ?, ?, ?)" @@ -204,7 +204,7 @@ insertService pid name summary descr url token key fprint assets tags = do params LocalQuorum (pid, sid, name, summary, descr, url, [token], [key], [fprint], assets, tagSet, False) - return sid + pure sid where cql :: PrepQuery @@ -516,7 +516,7 @@ updateServiceTags :: (Name, RangedServiceTags) -> BatchM () updateServiceTags pid sid (oldName, oldTags) (newName, newTags) - | eqTags && eqNames = return () + | eqTags && eqNames = pure () | eqNames = do let name = oldNameLower let added = diffTags newTags oldTags @@ -582,21 +582,21 @@ paginateServiceTags tags start size providerFilter = liftClient $ do p <- filterResults providerFilter start' <$> queryAll start' size' tags' r <- mapConcurrently resolveRow (result p) -- See Note [buggy pagination] - return $! ServiceProfilePage (hasMore p) (catMaybes r) + pure $! ServiceProfilePage (hasMore p) (catMaybes r) where start' = maybe "" Text.toLower start unpackTags :: QueryAnyTags 1 3 -> [QueryAllTags 1 3] unpackTags = Set.toList . fromRange . queryAnyTagsRange queryAll :: Text -> Int32 -> [QueryAllTags 1 3] -> Client (Page IndexRow) - queryAll _ _ [] = return emptyPage + queryAll _ _ [] = pure emptyPage queryAll s l [t] = do p <- queryTags s l t - return $! p {result = trim size (result p)} + pure $! p {result = trim size (result p)} queryAll s l ts = do ps <- mapConcurrently (queryTags s l) ts let rows = trim l (unfoldr nextRow (map result ps)) let more = any hasMore ps || length rows > fromIntegral size - return $! emptyPage {hasMore = more, result = trim size rows} + pure $! emptyPage {hasMore = more, result = trim size rows} nextRow :: [[IndexRow]] -> Maybe (IndexRow, [[IndexRow]]) nextRow rs = case mapMaybe uncons rs of [] -> Nothing @@ -670,7 +670,7 @@ paginateServiceNames mbPrefix size providerFilter = liftClient $ do in filterResults providerFilter prefix' <$> queryPrefixes prefix' size' r <- mapConcurrently resolveRow (result p) -- See Note [buggy pagination] - return $! ServiceProfilePage (hasMore p) (catMaybes r) + pure $! ServiceProfilePage (hasMore p) (catMaybes r) where queryAll len = do let cql :: PrepQuery R () IndexRow @@ -678,7 +678,7 @@ paginateServiceNames mbPrefix size providerFilter = liftClient $ do "SELECT name, provider, service \ \FROM service_prefix" p <- retry x1 $ paginate cql $ paramsP One () len - return $! p {result = trim size (result p)} + pure $! p {result = trim size (result p)} queryPrefixes prefix len = do let cql :: PrepQuery R (Text, Text) IndexRow cql = @@ -689,7 +689,7 @@ paginateServiceNames mbPrefix size providerFilter = liftClient $ do retry x1 $ paginate cql $ paramsP One (mkPrefixIndex (Name prefix), prefix) len - return $! p {result = trim size (result p)} + pure $! p {result = trim size (result p)} -- Pagination utilities filterResults :: Maybe ProviderId -> Text -> Page IndexRow -> Page IndexRow @@ -705,7 +705,7 @@ filterbyProvider pid p = do filterPrefix :: Text -> Page IndexRow -> Page IndexRow filterPrefix prefix p = do - let prefixed = filter (\(Name n, _, _) -> prefix `Text.isPrefixOf` (Text.toLower n)) (result p) + let prefixed = filter (\(Name n, _, _) -> prefix `Text.isPrefixOf` Text.toLower n) (result p) -- if they were all valid prefixes, there may be more in Cassandra allValid = length prefixed == length (result p) more = allValid && hasMore p @@ -795,7 +795,7 @@ paginateServiceWhitelist tid mbPrefix filterDisabled size = liftClient $ do . maybeFilterDisabled . catMaybes <$> mapConcurrently (uncurry lookupServiceProfile) p - return + pure $! ServiceProfilePage (length r > fromIntegral size) (trim size r) diff --git a/services/brig/src/Brig/Provider/RPC.hs b/services/brig/src/Brig/Provider/RPC.hs index 4c5ef88120..2a26239f39 100644 --- a/services/brig/src/Brig/Provider/RPC.hs +++ b/services/brig/src/Brig/Provider/RPC.hs @@ -88,7 +88,7 @@ createBot scon new = do -- here, not a @Response (Maybe ByteString)@. decodeBytes ctx bs = case eitherDecode' bs of Left e -> throwM $ ParseException ctx e - Right a -> return a + Right a -> pure a reqBuilder = extReq scon ["bots"] . method POST @@ -235,7 +235,7 @@ removeBotMember zusr zcon conv bot = do rs <- galleyRequest DELETE req if isJust (responseBody rs) && Bilge.statusCode rs == 200 then Just <$> decodeBody "galley" rs - else return Nothing + else pure Nothing where req = path "/i/bots" diff --git a/services/brig/src/Brig/Queue/Stomp.hs b/services/brig/src/Brig/Queue/Stomp.hs index 6ee788475e..63741dbba0 100644 --- a/services/brig/src/Brig/Queue/Stomp.hs +++ b/services/brig/src/Brig/Queue/Stomp.hs @@ -167,7 +167,7 @@ listen b q callback = msg (val "Exception when listening to a STOMP queue") ~~ field "queue" (show q) ~~ field "error" (show e) - return True + pure True -- Note [exception handling] -- ~~~ diff --git a/services/brig/src/Brig/Run.hs b/services/brig/src/Brig/Run.hs index 069af57954..a2b87e71a1 100644 --- a/services/brig/src/Brig/Run.hs +++ b/services/brig/src/Brig/Run.hs @@ -110,7 +110,7 @@ run o = do mkApp :: Opts -> IO (Wai.Application, Env) mkApp o = do e <- newEnv o - return (middleware e $ \reqId -> servantApp (e & requestId .~ reqId), e) + pure (middleware e $ \reqId -> servantApp (e & requestId .~ reqId), e) where rtree :: Tree (App (Handler BrigCanonicalEffects)) rtree = compile sitemap diff --git a/services/brig/src/Brig/SMTP.hs b/services/brig/src/Brig/SMTP.hs index f0b9eccad0..920752199b 100644 --- a/services/brig/src/Brig/SMTP.hs +++ b/services/brig/src/Brig/SMTP.hs @@ -73,14 +73,14 @@ initSMTP lg host port credentials connType = do SMTP.defaultSettingsSMTPSSL {SMTP.sslPort = p} ok <- case credentials of (Just (Username u, Password p)) -> SMTP.authenticate SMTP.LOGIN (unpack u) (unpack p) conn - _ -> return True - return (ok, conn) + _ -> pure True + pure (ok, conn) create = do (ok, conn) <- connect if ok then Logger.log lg Logger.Debug (msg $ val "Established connection to: " +++ host) else Logger.log lg Logger.Warn (msg $ val "Failed to established connection, check your credentials to connect to: " +++ host) - return conn + pure conn destroy c = do SMTP.closeSMTP c Logger.log lg Logger.Debug (msg $ val "Closing connection to: " +++ host) diff --git a/services/brig/src/Brig/Sem/CodeStore/Cassandra.hs b/services/brig/src/Brig/Sem/CodeStore/Cassandra.hs index 0aff544c97..7ebc58d057 100644 --- a/services/brig/src/Brig/Sem/CodeStore/Cassandra.hs +++ b/services/brig/src/Brig/Sem/CodeStore/Cassandra.hs @@ -85,8 +85,8 @@ genPhoneCode = mkPwdResetKey :: MonadIO m => UserId -> m PasswordResetKey mkPwdResetKey u = do - d <- liftIO $ getDigestByName "SHA256" >>= maybe (error "SHA256 not found") return - return . PasswordResetKey . encodeBase64Url . digestBS d $ toByteString' u + d <- liftIO $ getDigestByName "SHA256" >>= maybe (error "SHA256 not found") pure + pure . PasswordResetKey . encodeBase64Url . digestBS d $ toByteString' u interpretClientToIO :: Member (Final IO) r => diff --git a/services/brig/src/Brig/Sem/PasswordResetStore/CodeStore.hs b/services/brig/src/Brig/Sem/PasswordResetStore/CodeStore.hs index b16e51b619..c509f3c3a5 100644 --- a/services/brig/src/Brig/Sem/PasswordResetStore/CodeStore.hs +++ b/services/brig/src/Brig/Sem/PasswordResetStore/CodeStore.hs @@ -59,7 +59,7 @@ create u target = do key (PRQueryData code u (Identity maxAttempts) (Identity (ttl `addUTCTime` now))) (round ttl) - return (key, code) + pure (key, code) lookup :: Members '[CodeStore, Now] r => @@ -70,8 +70,8 @@ lookup u = do now <- Now.get validate now =<< codeSelect key where - validate now (Just (PRQueryData c _ _ (Just t))) | t > now = return $ Just c - validate _ _ = return Nothing + validate now (Just (PRQueryData c _ _ (Just t))) | t > now = pure $ Just c + validate _ _ = pure Nothing verify :: Members '[CodeStore, Now] r => @@ -81,9 +81,9 @@ verify (k, c) = do now <- Now.get code <- codeSelect k case code of - Just (PRQueryData c' u _ (Just t)) | c == c' && t >= now -> return (Just u) + Just (PRQueryData c' u _ (Just t)) | c == c' && t >= now -> pure (Just u) Just (PRQueryData c' u (Just n) (Just t)) | n > 1 && t > now -> do codeInsert k (PRQueryData c' u (Identity (n - 1)) (Identity t)) (round ttl) - return Nothing + pure Nothing Just PRQueryData {} -> codeDelete k $> Nothing - Nothing -> return Nothing + Nothing -> pure Nothing diff --git a/services/brig/src/Brig/Team/API.hs b/services/brig/src/Brig/Team/API.hs index 025a926f04..25b63a9e4f 100644 --- a/services/brig/src/Brig/Team/API.hs +++ b/services/brig/src/Brig/Team/API.hs @@ -229,7 +229,7 @@ getInvitationCodeH (_ ::: t ::: r) = do getInvitationCode :: TeamId -> InvitationId -> (Handler r) FoundInvitationCode getInvitationCode t r = do code <- lift . wrapClient $ DB.lookupInvitationCode t r - maybe (throwStd $ errorToWai @'E.InvalidInvitationCode) (return . FoundInvitationCode) code + maybe (throwStd $ errorToWai @'E.InvalidInvitationCode) (pure . FoundInvitationCode) code newtype FoundInvitationCode = FoundInvitationCode InvitationCode deriving (Eq, Show, Generic) @@ -258,8 +258,8 @@ createInvitationPublic uid tid body = do let inviteeRole = fromMaybe Team.defaultRole . irRole $ body inviter <- do let inviteePerms = Team.rolePermissions inviteeRole - idt <- maybe (throwStd (errorToWai @'E.NoIdentity)) return =<< lift (fetchUserIdentity uid) - from <- maybe (throwStd noEmail) return (emailIdentity idt) + idt <- maybe (throwStd (errorToWai @'E.NoIdentity)) pure =<< lift (fetchUserIdentity uid) + from <- maybe (throwStd noEmail) pure (emailIdentity idt) ensurePermissionToAddUser uid tid inviteePerms pure $ CreateInvitationInviter uid from @@ -322,7 +322,7 @@ createInvitation' tid inviteeRole mbInviterUid fromEmail body = do -- sendActivationCode. Refactor this to a single place -- Validate e-mail - inviteeEmail <- either (const $ throwStd (errorToWai @'E.InvalidEmail)) return (Email.validateEmail (irInviteeEmail body)) + inviteeEmail <- either (const $ throwStd (errorToWai @'E.InvalidEmail)) pure (Email.validateEmail (irInviteeEmail body)) let uke = userEmailKey inviteeEmail blacklistedEm <- lift $ wrapClient $ Blacklist.exists uke when blacklistedEm $ @@ -333,7 +333,7 @@ createInvitation' tid inviteeRole mbInviterUid fromEmail body = do -- Validate phone inviteePhone <- for (irInviteePhone body) $ \p -> do - validatedPhone <- maybe (throwStd (errorToWai @'E.InvalidPhone)) return =<< lift (wrapClient $ Phone.validatePhone p) + validatedPhone <- maybe (throwStd (errorToWai @'E.InvalidPhone)) pure =<< lift (wrapClient $ Phone.validatePhone p) let ukp = userPhoneKey validatedPhone blacklistedPh <- lift $ wrapClient $ Blacklist.exists ukp when blacklistedPh $ @@ -341,7 +341,7 @@ createInvitation' tid inviteeRole mbInviterUid fromEmail body = do phoneTaken <- lift $ isJust <$> wrapClient (Data.lookupKey ukp) when phoneTaken $ throwStd phoneExists - return validatedPhone + pure validatedPhone maxSize <- setMaxTeamSize <$> view settings pending <- lift $ wrapClient $ DB.countInvitations tid when (fromIntegral pending >= maxSize) $ @@ -385,12 +385,12 @@ listInvitations :: UserId -> TeamId -> Maybe InvitationId -> Range 1 500 Int32 - listInvitations uid tid start size = do ensurePermissions uid tid [Team.AddTeamMember] rs <- lift $ wrapClient $ DB.lookupInvitations tid start size - return $! Public.InvitationList (DB.resultList rs) (DB.resultHasMore rs) + pure $! Public.InvitationList (DB.resultList rs) (DB.resultHasMore rs) getInvitationH :: JSON ::: UserId ::: TeamId ::: InvitationId -> (Handler r) Response getInvitationH (_ ::: uid ::: tid ::: iid) = do inv <- getInvitation uid tid iid - return $ case inv of + pure $ case inv of Just i -> json i Nothing -> setStatus status404 empty @@ -406,12 +406,12 @@ getInvitationByCodeH (_ ::: c) = do getInvitationByCode :: Public.InvitationCode -> (Handler r) Public.Invitation getInvitationByCode c = do inv <- lift . wrapClient $ DB.lookupInvitationByCode c - maybe (throwStd $ errorToWai @'E.InvalidInvitationCode) return inv + maybe (throwStd $ errorToWai @'E.InvalidInvitationCode) pure inv headInvitationByEmailH :: JSON ::: Email -> (Handler r) Response headInvitationByEmailH (_ ::: e) = do inv <- lift $ wrapClient $ DB.lookupInvitationInfoByEmail e - return $ case inv of + pure $ case inv of DB.InvitationByEmail _ -> setStatus status200 empty DB.InvitationByEmailNotFound -> setStatus status404 empty DB.InvitationByEmailMoreThanOne -> setStatus status409 empty @@ -426,7 +426,7 @@ getInvitationByEmailH (_ ::: email) = getInvitationByEmail :: Email -> (Handler r) Public.Invitation getInvitationByEmail email = do inv <- lift $ wrapClient $ DB.lookupInvitationByEmail email - maybe (throwStd (notFound "Invitation not found")) return inv + maybe (throwStd (notFound "Invitation not found")) pure inv suspendTeamH :: JSON ::: TeamId -> (Handler r) Response suspendTeamH (_ ::: tid) = do @@ -458,5 +458,5 @@ changeTeamAccountStatuses tid s = do uids <- toList1 =<< lift (fmap (view Team.userId) . view Team.teamMembers <$> wrapHttp (Intra.getTeamMembers tid)) wrapHttpClientE (API.changeAccountStatus uids s) !>> accountStatusError where - toList1 (x : xs) = return $ List1.list1 x xs + toList1 (x : xs) = pure $ List1.list1 x xs toList1 [] = throwStd (notFound "Team not found or no members") diff --git a/services/brig/src/Brig/Team/DB.hs b/services/brig/src/Brig/Team/DB.hs index 920abedd76..6a28ec19b8 100644 --- a/services/brig/src/Brig/Team/DB.hs +++ b/services/brig/src/Brig/Team/DB.hs @@ -99,7 +99,7 @@ insertInvitation iid t role (toUTCTimeMillis -> now) minviter email inviteeName addPrepQuery cqlInvitation (t, role, iid, code, email, now, minviter, inviteeName, phone, round timeout) addPrepQuery cqlInvitationInfo (code, t, iid, round timeout) addPrepQuery cqlInvitationByEmail (email, t, iid, code, round timeout) - return (inv, code) + pure (inv, code) where cqlInvitationInfo :: PrepQuery W (InvitationCode, TeamId, InvitationId, Int32) () cqlInvitationInfo = "INSERT INTO team_invitation_info (code, team, id) VALUES (?, ?, ?) USING TTL ?" @@ -121,7 +121,7 @@ lookupInvitationByCode :: MonadClient m => InvitationCode -> m (Maybe Invitation lookupInvitationByCode i = lookupInvitationInfo i >>= \case Just InvitationInfo {..} -> lookupInvitation iiTeam iiInvId - _ -> return Nothing + _ -> pure Nothing lookupInvitationCode :: MonadClient m => TeamId -> InvitationId -> m (Maybe InvitationCode) lookupInvitationCode t r = @@ -142,7 +142,7 @@ lookupInvitations team start (fromRange -> size) = do page <- case start of Just ref -> retry x1 $ paginate cqlSelectFrom (paramsP LocalQuorum (team, ref) (size + 1)) Nothing -> retry x1 $ paginate cqlSelect (paramsP LocalQuorum (Identity team) (size + 1)) - return $ toResult (hasMore page) $ map toInvitation (trim page) + pure $ toResult (hasMore page) $ map toInvitation (trim page) where trim p = take (fromIntegral size) (result p) toResult more invs = @@ -188,7 +188,7 @@ deleteInvitations t = lookupInvitationInfo :: MonadClient m => InvitationCode -> m (Maybe InvitationInfo) lookupInvitationInfo ic@(InvitationCode c) - | c == mempty = return Nothing + | c == mempty = pure Nothing | otherwise = fmap (toInvitationInfo ic) <$> retry x1 (query1 cqlInvitationInfo (params LocalQuorum (Identity ic))) @@ -201,29 +201,29 @@ lookupInvitationByEmail :: (Log.MonadLogger m, MonadClient m) => Email -> m (May lookupInvitationByEmail e = lookupInvitationInfoByEmail e >>= \case InvitationByEmail InvitationInfo {..} -> lookupInvitation iiTeam iiInvId - _ -> return Nothing + _ -> pure Nothing lookupInvitationInfoByEmail :: (Log.MonadLogger m, MonadClient m) => Email -> m InvitationByEmail lookupInvitationInfoByEmail email = do res <- retry x1 (query cqlInvitationEmail (params LocalQuorum (Identity email))) case res of - [] -> return InvitationByEmailNotFound - (tid, invId, code) : [] -> + [] -> pure InvitationByEmailNotFound + [(tid, invId, code)] -> -- one invite pending - return $ InvitationByEmail (InvitationInfo code tid invId) + pure $ InvitationByEmail (InvitationInfo code tid invId) _ : _ : _ -> do -- edge case: more than one pending invite from different teams Log.info $ Log.msg (Log.val "team_invidation_email: multiple pending invites from different teams for the same email") Log.~~ Log.field "email" (show email) - return InvitationByEmailMoreThanOne + pure InvitationByEmailMoreThanOne where cqlInvitationEmail :: PrepQuery R (Identity Email) (TeamId, InvitationId, InvitationCode) cqlInvitationEmail = "SELECT team, invitation, code FROM team_invitation_email WHERE email = ?" countInvitations :: MonadClient m => TeamId -> m Int64 countInvitations t = - fromMaybe 0 . fmap runIdentity + maybe 0 runIdentity <$> retry x1 (query1 cqlSelect (params LocalQuorum (Identity t))) where cqlSelect :: PrepQuery R (Identity TeamId) (Identity Int64) diff --git a/services/brig/src/Brig/Unique.hs b/services/brig/src/Brig/Unique.hs index c30884ca10..88e325e8c4 100644 --- a/services/brig/src/Brig/Unique.hs +++ b/services/brig/src/Brig/Unique.hs @@ -61,7 +61,7 @@ withClaim u v t io = do case claims of [] -> claim -- Free [u'] | u == u' -> claim -- Claimed by 'u' (retries are allowed). - _ -> return Nothing -- Conflicting claims, TTL must expire. + _ -> pure Nothing -- Conflicting claims, TTL must expire. where -- [Note: Guarantees] claim = do @@ -70,7 +70,7 @@ withClaim u v t io = do claimed <- (== [u]) <$> lookupClaims v if claimed then liftIO $ timeout (fromIntegral ttl # Second) io - else return Nothing + else pure Nothing cql :: PrepQuery W (Int32, C.Set (Id a), Text) () cql = "UPDATE unique_claims USING TTL ? SET claims = claims + ? WHERE value = ?" diff --git a/services/brig/src/Brig/User/API/Auth.hs b/services/brig/src/Brig/User/API/Auth.hs index 757aba32a8..daa60d91f2 100644 --- a/services/brig/src/Brig/User/API/Auth.hs +++ b/services/brig/src/Brig/User/API/Auth.hs @@ -219,7 +219,7 @@ sendLoginCode :: Public.SendLoginCode -> (Handler r) Public.LoginCodeTimeout sendLoginCode (Public.SendLoginCode phone call force) = do checkWhitelist (Right phone) c <- wrapClientE (Auth.sendLoginCode phone call force) !>> sendLoginCodeError - return $ Public.LoginCodeTimeout (pendingLoginTimeout c) + pure $ Public.LoginCodeTimeout (pendingLoginTimeout c) getLoginCodeH :: JSON ::: Phone -> (Handler r) Response getLoginCodeH (_ ::: phone) = json <$> getLoginCode phone @@ -227,12 +227,12 @@ getLoginCodeH (_ ::: phone) = json <$> getLoginCode phone getLoginCode :: Phone -> (Handler r) Public.PendingLoginCode getLoginCode phone = do code <- lift $ wrapClient $ Auth.lookupLoginCode phone - maybe (throwStd loginCodeNotFound) return code + maybe (throwStd loginCodeNotFound) pure code reAuthUserH :: UserId ::: JsonRequest ReAuthUser -> (Handler r) Response reAuthUserH (uid ::: req) = do reAuthUser uid =<< parseJsonBody req - return empty + pure empty reAuthUser :: UserId -> ReAuthUser -> (Handler r) () reAuthUser uid body = do @@ -401,7 +401,7 @@ tokenRequest = opt (userToken ||| legalHoldUserToken) .&. opt (accessToken ||| l bearer (Okay _ b) = let (prefix, suffix) = BS.splitAt 7 b in if prefix == "Bearer " - then return suffix + then pure suffix else Fail ( setReason @@ -419,7 +419,7 @@ tokenRequest = opt (userToken ||| legalHoldUserToken) .&. opt (accessToken ||| l TypeError (setMessage "Invalid access token" (err status403)) ) - Just t -> return t + Just t -> pure t tokenResponse :: ZAuth.UserTokenLike u => Auth.Access u -> (AppT r) Response tokenResponse (Auth.Access t Nothing) = pure $ json t @@ -438,7 +438,7 @@ cookies k r = cc -> case mapMaybe fromByteString cc of [] -> Fail . addLabel "cookie" . typeError k $ "Failed to get zuid cookies" - (x : xs) -> return $ List1.list1 x xs + (x : xs) -> pure $ List1.list1 x xs notAvailable :: ByteString -> P.Error notAvailable k = e400 & setReason NotAvailable . setSource k diff --git a/services/brig/src/Brig/User/API/Handle.hs b/services/brig/src/Brig/User/API/Handle.hs index 3f40f8767c..db71c04406 100644 --- a/services/brig/src/Brig/User/API/Handle.hs +++ b/services/brig/src/Brig/User/API/Handle.hs @@ -63,12 +63,12 @@ getLocalHandleInfo self handle = do lift . Log.info $ Log.msg $ Log.val "getHandleInfo - local lookup" maybeOwnerId <- lift . wrapClient $ API.lookupHandle handle case maybeOwnerId of - Nothing -> return Nothing + Nothing -> pure Nothing Just ownerId -> do domain <- viewFederationDomain ownerProfile <- wrapHttpClientE (API.lookupProfile self (Qualified ownerId domain)) !>> fedError owner <- filterHandleResults self (maybeToList ownerProfile) - return $ listToMaybe owner + pure $ listToMaybe owner -- | Checks search permissions and filters accordingly filterHandleResults :: Local UserId -> [Public.UserProfile] -> (Handler r) [Public.UserProfile] @@ -77,10 +77,10 @@ filterHandleResults searchingUser us = do if sameTeamSearchOnly then do fromTeam <- lift . wrapClient $ Data.lookupUserTeam (tUnqualified searchingUser) - return $ case fromTeam of + pure $ case fromTeam of Just team -> filter (\x -> Public.profileTeam x == Just team) us Nothing -> us - else return us + else pure us contactFromProfile :: Public.UserProfile -> Public.Contact contactFromProfile profile = diff --git a/services/brig/src/Brig/User/API/Search.hs b/services/brig/src/Brig/User/API/Search.hs index 41dbeb51b1..50ab3490aa 100644 --- a/services/brig/src/Brig/User/API/Search.hs +++ b/services/brig/src/Brig/User/API/Search.hs @@ -180,11 +180,11 @@ searchLocally searcherId searchTerm maybeMaxResults = do mkTeamSearchInfo searcherTeamId = lift $ do sameTeamSearchOnly <- fromMaybe False <$> view (settings . Opts.searchSameTeamOnly) case searcherTeamId of - Nothing -> return Search.NoTeam + Nothing -> pure Search.NoTeam Just t -> -- This flag in brig overrules any flag on galley - it is system wide if sameTeamSearchOnly - then return (Search.TeamOnly t) + then pure (Search.TeamOnly t) else do -- For team users, we need to check the visibility flag handleTeamVisibility t <$> wrapHttp (Intra.getTeamSearchVisibility t) diff --git a/services/brig/src/Brig/User/Auth.hs b/services/brig/src/Brig/User/Auth.hs index 35be4024b8..a649fc9fcd 100644 --- a/services/brig/src/Brig/User/Auth.hs +++ b/services/brig/src/Brig/User/Auth.hs @@ -100,7 +100,7 @@ sendLoginCode phone call force = do pk <- maybe (throwE $ SendLoginInvalidPhone phone) - (return . userPhoneKey) + (pure . userPhoneKey) =<< lift (validatePhone phone) user <- lift $ Data.lookupKey pk case user of @@ -117,7 +117,7 @@ sendLoginCode phone call force = do if call then sendLoginCall ph (pendingLoginCode c) l else sendLoginSms ph (pendingLoginCode c) l - return c + pure c lookupLoginCode :: ( MonadClient m, @@ -128,7 +128,7 @@ lookupLoginCode :: m (Maybe PendingLoginCode) lookupLoginCode phone = Data.lookupKey (userPhoneKey phone) >>= \case - Nothing -> return Nothing + Nothing -> pure Nothing Just u -> do Log.debug $ field "user" (toByteString u) . field "action" (Log.val "User.lookupLoginCode") Data.lookupLoginCode u @@ -277,7 +277,7 @@ renewAccess uts at = do catchSuspendInactiveUser uid ZAuth.Expired ck' <- lift $ nextCookie ck at' <- lift $ newAccessToken (fromMaybe ck ck') at - return $ Access at' ck' + pure $ Access at' ck' revokeAccess :: (MonadClient m, Log.MonadLogger m) => @@ -348,7 +348,7 @@ newAccess uid ct cl = do Left delay -> throwE $ LoginThrottled delay Right ck -> do t <- lift $ newAccessToken @u @a ck Nothing - return $ Access t (Just ck) + pure $ Access t (Just ck) resolveLoginId :: (MonadClient m, MonadReader Env m) => LoginId -> ExceptT LoginError m UserId resolveLoginId li = do @@ -360,32 +360,32 @@ resolveLoginId li = do if pending then LoginPendingActivation else LoginFailed - Just uid -> return uid + Just uid -> pure uid validateLoginId :: (MonadClient m, MonadReader Env m) => LoginId -> ExceptT LoginError m (Either UserKey Handle) validateLoginId (LoginByEmail email) = either (const $ throwE LoginFailed) - (return . Left . userEmailKey) + (pure . Left . userEmailKey) (validateEmail email) validateLoginId (LoginByPhone phone) = maybe (throwE LoginFailed) - (return . Left . userPhoneKey) + (pure . Left . userPhoneKey) =<< lift (validatePhone phone) validateLoginId (LoginByHandle h) = - return (Right h) + pure (Right h) isPendingActivation :: (MonadClient m, MonadReader Env m) => LoginId -> m Bool isPendingActivation ident = case ident of - (LoginByHandle _) -> return False + (LoginByHandle _) -> pure False (LoginByEmail e) -> checkKey (userEmailKey e) (LoginByPhone p) -> checkKey (userPhoneKey p) where checkKey k = do usr <- (>>= fst) <$> Data.lookupActivationCode k case usr of - Nothing -> return False + Nothing -> pure False Just u -> maybe False (checkAccount k) <$> Data.lookupAccount u checkAccount k a = let i = userIdentity (accountUser a) @@ -421,7 +421,7 @@ validateTokens uts at = do List1 (Either ZAuth.Failure (UserId, Cookie (ZAuth.Token u))) -> ExceptT ZAuth.Failure m (UserId, Cookie (ZAuth.Token u)) getFirstSuccessOrFirstFail tks = case (lefts $ NE.toList $ List1.toNonEmpty tks, rights $ NE.toList $ List1.toNonEmpty tks) of - (_, suc : _) -> return suc + (_, suc : _) -> pure suc (e : _, _) -> throwE e _ -> throwE ZAuth.Invalid -- Impossible @@ -442,8 +442,8 @@ validateToken ut at = do ExceptT (ZAuth.validateToken token) `catchE` \e -> unless (e == ZAuth.Expired) (throwE e) - ck <- lift (lookupCookie ut) >>= maybe (throwE ZAuth.Invalid) return - return (ZAuth.userTokenOf ut, ck) + ck <- lift (lookupCookie ut) >>= maybe (throwE ZAuth.Invalid) pure + pure (ZAuth.userTokenOf ut, ck) -- | Allow to login as any user without having the credentials. ssoLogin :: diff --git a/services/brig/src/Brig/User/Auth/Cookie.hs b/services/brig/src/Brig/User/Auth/Cookie.hs index 222a78422e..461f136a3c 100644 --- a/services/brig/src/Brig/User/Auth/Cookie.hs +++ b/services/brig/src/Brig/User/Auth/Cookie.hs @@ -95,7 +95,7 @@ newCookie uid typ label = do cookieValue = tok } DB.insertCookie uid c Nothing - return c + pure c -- | Renew the given cookie with a fresh token, if its age -- exceeds the configured minimum threshold. @@ -119,7 +119,7 @@ nextCookie c = do -- a different zauth key index, regardless of age. if persist c && diffUTCTime now created > renewAge then Just <$> getNext - else return Nothing + else pure Nothing where persist = (PersistentCookie ==) . cookieType getNext = case cookieSucc c of @@ -132,7 +132,7 @@ nextCookie c = do Nothing -> renewCookie c Just c' -> do t <- ZAuth.mkUserToken uid (cookieIdNum ck) (cookieExpires c') - return c' {cookieValue = t} + pure c' {cookieValue = t} -- | Renew the given cookie with a fresh token. renewCookie :: @@ -154,7 +154,7 @@ renewCookie old = do let old' = old {cookieSucc = Just (cookieId new)} ttl <- setUserCookieRenewAge <$> view settings DB.insertCookie uid old' (Just (DB.TTL (fromIntegral ttl))) - return new + pure new -- | Whether a user has not renewed any of her cookies for longer than -- 'suspendCookiesOlderThanSecs'. Call this always before 'newCookie', 'nextCookie', @@ -189,7 +189,7 @@ newAccessToken c mt = do Just t -> ZAuth.renewAccessToken t zSettings <- view (zauthEnv . ZAuth.settings) let ttl = view (ZAuth.settingsTTL (Proxy @a)) zSettings - return $ + pure $ bearerToken (ZAuth.accessTokenOf t') (toByteString t') @@ -248,7 +248,7 @@ newCookieLimited u typ label = do if null evict then Right <$> newCookie u typ label else case throttleCookies now thr cs of - Just wait -> return (Left wait) + Just wait -> pure (Left wait) Nothing -> do revokeCookies u evict [] Right <$> newCookie u typ label @@ -263,7 +263,7 @@ setResponseCookie :: m Response setResponseCookie c r = do hdr <- toByteString' . WebCookie.renderSetCookie <$> toWebCookie c - return (addHeader "Set-Cookie" hdr r) + pure (addHeader "Set-Cookie" hdr r) toWebCookie :: (Monad m, MonadReader Env m, ZAuth.UserTokenLike u) => Cookie (ZAuth.Token u) -> m WebCookie.SetCookie toWebCookie c = do diff --git a/services/brig/src/Brig/User/Auth/DB/Instances.hs b/services/brig/src/Brig/User/Auth/DB/Instances.hs index 9e4e60436b..a724bf1bcf 100644 --- a/services/brig/src/Brig/User/Auth/DB/Instances.hs +++ b/services/brig/src/Brig/User/Auth/DB/Instances.hs @@ -39,7 +39,7 @@ instance Cql CookieId where ctype = Tagged BigIntColumn toCql = CqlBigInt . fromIntegral . cookieIdNum - fromCql (CqlBigInt i) = return (CookieId (fromIntegral i)) + fromCql (CqlBigInt i) = pure (CookieId (fromIntegral i)) fromCql _ = Left "fromCql: invalid cookie id" instance Cql CookieType where @@ -48,6 +48,6 @@ instance Cql CookieType where toCql SessionCookie = CqlInt 0 toCql PersistentCookie = CqlInt 1 - fromCql (CqlInt 0) = return SessionCookie - fromCql (CqlInt 1) = return PersistentCookie + fromCql (CqlInt 0) = pure SessionCookie + fromCql (CqlInt 1) = pure PersistentCookie fromCql _ = Left "fromCql: invalid cookie type" diff --git a/services/brig/src/Brig/User/Handle.hs b/services/brig/src/Brig/User/Handle.hs index 1cee4911a8..245679ae51 100644 --- a/services/brig/src/Brig/User/Handle.hs +++ b/services/brig/src/Brig/User/Handle.hs @@ -39,7 +39,7 @@ claimHandle uid oldHandle newHandle = isJust <$> do owner <- lookupHandle newHandle case owner of - Just uid' | uid /= uid' -> return Nothing + Just uid' | uid /= uid' -> pure Nothing _ -> do env <- ask let key = "@" <> fromHandle newHandle @@ -53,7 +53,7 @@ claimHandle uid oldHandle newHandle = -- Free old handle (if it changed) for_ (mfilter (/= newHandle) oldHandle) $ wrapClient . freeHandle uid - return result + pure result -- | Free a 'Handle', making it available to be claimed again. freeHandle :: MonadClient m => UserId -> Handle -> m () diff --git a/services/brig/src/Brig/User/Search/Index.hs b/services/brig/src/Brig/User/Search/Index.hs index bee7ad759f..1211c5ff8d 100644 --- a/services/brig/src/Brig/User/Search/Index.hs +++ b/services/brig/src/Brig/User/Search/Index.hs @@ -384,7 +384,7 @@ resetIndex ciSettings = liftIndexIO $ do gone <- ES.indexExists idx >>= \case True -> ES.isSuccess <$> traceES "Delete Index" (ES.deleteIndex idx) - False -> return True + False -> pure True if gone then createIndex ciSettings else throwM (IndexError "Index deletion failed.") @@ -432,7 +432,7 @@ traceES descr act = liftIndexIO $ do info (msg descr) r <- act info . msg $ (r & statusCode . responseStatus) +++ val " - " +++ responseBody r - return r + pure r -- | This mapping defines how elasticsearch will treat each field in a document. Here -- is how it treats each field: @@ -865,18 +865,16 @@ reindexRowToIndexUser version :: [Maybe (Writetime Name)] -> m IndexVersion version = mkIndexVersion . getMax . mconcat . fmap Max . catMaybes shouldIndex = - and - [ case status of - Nothing -> True - Just Active -> True - Just Suspended -> True - Just Deleted -> False - Just Ephemeral -> False - Just PendingInvitation -> False, - activated, -- FUTUREWORK: how is this adding to the first case? - isNothing service - ] - + ( case status of + Nothing -> True + Just Active -> True + Just Suspended -> True + Just Deleted -> False + Just Ephemeral -> False + Just PendingInvitation -> False + ) + && activated -- FUTUREWORK: how is this adding to the first case? + && isNothing service idpUrl :: UserSSOId -> Maybe Text idpUrl (UserSSOId (SAML.UserRef (SAML.Issuer uri) _subject)) = Just $ fromUri uri @@ -928,7 +926,7 @@ getTeamSearchVisibilityInboundMulti tids = do res <- try $ RPC.httpLbs rq id case res of Left x -> throwM $ RPCException nm rq x - Right x -> return x + Right x -> pure x where mkEndpoint service = RPC.host (encodeUtf8 (service ^. epHost)) . RPC.port (service ^. epPort) $ RPC.empty diff --git a/services/brig/src/Brig/User/Search/SearchIndex.hs b/services/brig/src/Brig/User/Search/SearchIndex.hs index f25ce87680..8f18d0d659 100644 --- a/services/brig/src/Brig/User/Search/SearchIndex.hs +++ b/services/brig/src/Brig/User/Search/SearchIndex.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} diff --git a/services/brig/src/Brig/User/Search/TeamSize.hs b/services/brig/src/Brig/User/Search/TeamSize.hs index b26d7286f0..2949c8e2fc 100644 --- a/services/brig/src/Brig/User/Search/TeamSize.hs +++ b/services/brig/src/Brig/User/Search/TeamSize.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE StrictData #-} -- This file is part of the Wire Server implementation. diff --git a/services/brig/src/Brig/Whitelist.hs b/services/brig/src/Brig/Whitelist.hs index 1e2beeb4da..5dc27a352b 100644 --- a/services/brig/src/Brig/Whitelist.hs +++ b/services/brig/src/Brig/Whitelist.hs @@ -55,13 +55,13 @@ instance FromJSON Whitelist verify :: (MonadIO m, MonadMask m, MonadHttp m) => Whitelist -> Either Email Phone -> m Bool verify (Whitelist url user pass) key = if isKnownDomain key - then return True + then pure True else recovering x3 httpHandlers . const $ do rq <- parseRequest $ unpack url rsp <- get' rq $ req (encodeUtf8 user) (encodeUtf8 pass) case statusCode rsp of - 200 -> return True - 404 -> return False + 200 -> pure True + 404 -> pure False _ -> throwM $ HttpExceptionRequest rq (StatusCodeException (rsp {responseBody = ()}) mempty) diff --git a/services/brig/src/Brig/ZAuth.hs b/services/brig/src/Brig/ZAuth.hs index a7ba3d520f..e5579aa1cd 100644 --- a/services/brig/src/Brig/ZAuth.hs +++ b/services/brig/src/Brig/ZAuth.hs @@ -237,7 +237,7 @@ mkEnv :: NonEmpty SecretKey -> NonEmpty PublicKey -> Settings -> IO Env mkEnv sk pk sets = do zc <- ZC.mkEnv (NonEmpty.head sk) (NonEmpty.tail sk) let zv = ZV.mkEnv (NonEmpty.head pk) (NonEmpty.tail pk) - return $! Env zc zv sets + pure $! Env zc zv sets class (UserTokenLike u, AccessTokenLike a) => TokenPair u a where newAccessToken :: MonadZAuth m => Token u -> m (Token a) diff --git a/services/brig/test/integration/API/Calling.hs b/services/brig/test/integration/API/Calling.hs index d6df765201..bc09a07712 100644 --- a/services/brig/test/integration/API/Calling.hs +++ b/services/brig/test/integration/API/Calling.hs @@ -46,7 +46,7 @@ import Wire.API.Call.Config tests :: Manager -> Brig -> Opts.Opts -> FilePath -> FilePath -> IO TestTree tests m b opts turn turnV2 = do - return $ + pure $ testGroup "calling" $ [ testGroup "turn" $ [ test m "basic /calls/config - 200" $ testCallsConfig b, @@ -253,7 +253,7 @@ toTurnURILegacy :: ByteString -> Port -> TurnURI toTurnURILegacy h p = toTurnURI SchemeTurn h p Nothing toTurnURI :: Scheme -> ByteString -> Port -> Maybe Transport -> TurnURI -toTurnURI s h p t = turnURI s ip p t +toTurnURI s h = turnURI s ip where ip = fromMaybe (error "Failed to parse host address") $ diff --git a/services/brig/test/integration/API/Federation.hs b/services/brig/test/integration/API/Federation.hs index f099586e80..74612a2919 100644 --- a/services/brig/test/integration/API/Federation.hs +++ b/services/brig/test/integration/API/Federation.hs @@ -61,7 +61,7 @@ import Wire.API.UserMap (UserMap (UserMap)) -- Note: POST /federation/send-connection-action is implicitly tested in API.User.Connection tests :: Manager -> Opt.Opts -> Brig -> Cannon -> FedClient 'Brig -> IO TestTree tests m opts brig cannon fedBrigClient = - return $ + pure $ testGroup "federation" [ test m "POST /federation/search-users : Found" (testSearchSuccess opts brig), diff --git a/services/brig/test/integration/API/Internal.hs b/services/brig/test/integration/API/Internal.hs index 3ec78c59df..6d4ab3f1a7 100644 --- a/services/brig/test/integration/API/Internal.hs +++ b/services/brig/test/integration/API/Internal.hs @@ -56,7 +56,7 @@ import qualified Wire.API.Team.Member as Team tests :: Opt.Opts -> Manager -> Cass.ClientState -> Brig -> Endpoint -> Gundeck -> Galley -> IO TestTree tests opts mgr db brig brigep gundeck galley = do - return $ + pure $ testGroup "api/internal" $ [ test mgr "ejpd requests" $ testEJPDRequest mgr brig brigep gundeck, test mgr "account features: conferenceCalling" $ @@ -244,7 +244,7 @@ keyPackageCreate brig = do Nothing -> liftIO $ assertFailure "Claim response empty" Just bundle -> case toList $ kpbEntries bundle of [] -> liftIO $ assertFailure "Claim response held no bundles" - (h : _) -> return $ kpbeRef h + (h : _) -> pure $ kpbeRef h kpcPut :: HasCallStack => Brig -> KeyPackageRef -> Qualified ConvId -> Http () kpcPut brig ref qConv = do @@ -262,8 +262,8 @@ kpcGet brig ref = do resp <- get (brig . paths ["i", "mls", "key-packages", toByteString' $ toUrlPiece ref, "conversation"]) liftIO $ case statusCode resp of - 404 -> return Nothing - 200 -> return $ responseBody resp >>= decode + 404 -> pure Nothing + 200 -> pure $ responseBody resp >>= decode _ -> assertFailure "GET i/mls/key-packages/:ref/conversation failed" testKpcFreshGet :: Brig -> Http () diff --git a/services/brig/test/integration/API/Internal/Util.hs b/services/brig/test/integration/API/Internal/Util.hs index b526990ab6..06e0c4832d 100644 --- a/services/brig/test/integration/API/Internal/Util.hs +++ b/services/brig/test/integration/API/Internal/Util.hs @@ -113,8 +113,8 @@ scaffolding brig gundeck = do randomToken :: MonadIO m => m PushToken.PushToken randomToken = liftIO $ do c <- liftIO $ newClientId <$> (randomIO :: IO Word64) - tok <- PushToken.Token . T.decodeUtf8 <$> B16.encode <$> randomBytes 32 - return $ PushToken.pushToken PushToken.APNSSandbox (PushToken.AppName "test") tok c + tok <- (PushToken.Token . T.decodeUtf8) . B16.encode <$> randomBytes 32 + pure $ PushToken.pushToken PushToken.APNSSandbox (PushToken.AppName "test") tok c ejpdRequestClientM :: Maybe Bool -> EJPDRequestBody -> Client.ClientM EJPDResponseBody ejpdRequestClientM = Client.client (Proxy @("i" :> IAPI.EJPDRequest)) diff --git a/services/brig/test/integration/API/MLS.hs b/services/brig/test/integration/API/MLS.hs index 7f66272578..0fefc518e3 100644 --- a/services/brig/test/integration/API/MLS.hs +++ b/services/brig/test/integration/API/MLS.hs @@ -166,9 +166,7 @@ testKeyPackageRemoteClaim opts brig = do liftIO . replicateM 2 . generate $ -- claimed key packages are not validated by the backend, so it is fine to -- make up some random data here - KeyPackageBundleEntry - <$> pure u - <*> arbitrary + KeyPackageBundleEntry u <$> arbitrary <*> (KeyPackageRef . BS.pack <$> vector 32) <*> (KeyPackageData . BS.pack <$> vector 64) let mockBundle = KeyPackageBundle (Set.fromList entries) diff --git a/services/brig/test/integration/API/Metrics.hs b/services/brig/test/integration/API/Metrics.hs index 4153a016b0..fa735a391c 100644 --- a/services/brig/test/integration/API/Metrics.hs +++ b/services/brig/test/integration/API/Metrics.hs @@ -1,8 +1,5 @@ -{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -{-# LANGUAGE TupleSections #-} -{-# LANGUAGE ViewPatterns #-} -- This file is part of the Wire Server implementation. -- @@ -39,7 +36,7 @@ import Util tests :: Manager -> Brig -> IO TestTree tests manager brig = do - return $ + pure $ testGroup "metrics" [ testCase "prometheus" . void $ runHttpT manager (testPrometheusMetrics brig), @@ -79,7 +76,7 @@ testMetricsEndpoint brig = do rsp <- responseBody <$> get (brig . path "i/metrics") -- is there some responseBodyAsText function used elsewhere? let asText = fromMaybe "" (fromByteString' (fromMaybe "" rsp)) - return $ fromRight 0 (parseOnly (parseCount endpoint m) asText) + pure $ fromRight 0 (parseOnly (parseCount endpoint m) asText) parseCount :: Text -> Text -> Parser Integer parseCount endpoint m = manyTill anyChar (string ("http_request_duration_seconds_count{handler=\"" <> endpoint <> "\",method=\"" <> m <> "\",status_code=\"200\"} ")) diff --git a/services/brig/test/integration/API/Provider.hs b/services/brig/test/integration/API/Provider.hs index 0c5904bf2c..7cd730553b 100644 --- a/services/brig/test/integration/API/Provider.hs +++ b/services/brig/test/integration/API/Provider.hs @@ -1,5 +1,4 @@ {-# LANGUAGE NondecreasingIndentation #-} -{-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-} -- This file is part of the Wire Server implementation. @@ -93,7 +92,7 @@ import qualified Wire.API.Team.Feature as Public tests :: Domain -> Config -> Manager -> DB.ClientState -> Brig -> Cannon -> Galley -> IO TestTree tests dom conf p db b c g = do - return $ + pure $ testGroup "provider" [ testGroup @@ -457,14 +456,14 @@ testListServices config db brig = do ("search for " <> show name <> " without and with tags") (serviceProfilePageResults r1) (serviceProfilePageResults r2) - return r1 + pure r1 -- This function searches for a prefix and check that the results match -- our known list of services let searchAndCheck :: HasCallStack => Name -> Http [ServiceProfile] searchAndCheck name = do result <- search name assertServiceDetails ("name " <> show name) (select name services) result - return (serviceProfilePageResults result) + pure (serviceProfilePageResults result) -- Search for our unique prefix and check that all services are found search (Name uniq) >>= assertServiceDetails ("all with prefix " <> show uniq) services -- Search by exact name and check that only one service is found @@ -594,7 +593,7 @@ testMessageBot config db brig galley cannon = withTestService config db brig def usr <- createUser "User" brig let uid = userId usr let quid = userQualifiedId usr - let new = defNewClient PermanentClientType [somePrekeys !! 0] (someLastPrekeys !! 0) + let new = defNewClient PermanentClientType [head somePrekeys] (head someLastPrekeys) _rs <- addClient brig uid new responseJsonMaybe _rs -- Create conversation @@ -616,7 +615,7 @@ testBadFingerprint config db brig galley _cannon = do -- Prepare user with client usr <- createUser "User" brig let uid = userId usr - let new = defNewClient PermanentClientType [somePrekeys !! 0] (someLastPrekeys !! 0) + let new = defNewClient PermanentClientType [head somePrekeys] (head someLastPrekeys) _rs <- addClient brig uid new responseJsonMaybe _rs -- Whitelist the bot @@ -804,7 +803,7 @@ testSearchWhitelist config db brig galley = do ("search for " <> show mbName <> " with and without filtering") r1 r2 - return r1 + pure r1 -- Check that search finds all services that we created search (Just uniq) >>= assertServiceDetails ("all with prefix " <> show uniq) services @@ -826,7 +825,7 @@ testSearchWhitelist config db brig galley = do searchAndCheck (Name name) = do result <- search (Just name) assertServiceDetails ("name " <> show name) (select name services) result - return (serviceProfilePageResults result) + pure (serviceProfilePageResults result) -- Search by exact name and check that only one service is found forM_ (take 3 services) $ \(sid, Name name) -> search (Just name) >>= assertServiceDetails ("name " <> show name) [(sid, Name name)] @@ -1491,7 +1490,7 @@ randomProvider db brig = do -- Fetch _rs <- getProvider brig pid Brig -> ProviderId -> NewService -> Http Service addGetService brig pid new = do @@ -1500,7 +1499,7 @@ addGetService brig pid new = do let sid = rsNewServiceId srs _rs <- getService brig pid sid Brig -> ProviderId -> ServiceId -> Http () enableService brig pid sid = do @@ -1555,7 +1554,7 @@ dewhitelistService brig uid tid pid sid = defNewService :: MonadIO m => Config -> m NewService defNewService config = liftIO $ do key <- readServiceKey (publicKey config) - return + pure NewService { newServiceName = defServiceName, newServiceSummary = unsafeRange defProviderSummary, @@ -1617,19 +1616,19 @@ readServiceKey :: MonadIO m => FilePath -> m ServiceKeyPEM readServiceKey fp = liftIO $ do bs <- BS.readFile fp let Right [k] = pemParseBS bs - return (ServiceKeyPEM k) + pure (ServiceKeyPEM k) randServiceKey :: MonadIO m => m ServiceKeyPEM randServiceKey = liftIO $ do kp <- generateRSAKey' 4096 65537 Right [k] <- pemParseBS . C8.pack <$> writePublicKey kp - return (ServiceKeyPEM k) + pure (ServiceKeyPEM k) waitFor :: MonadIO m => Timeout -> (a -> Bool) -> m a -> m a waitFor t f ma = do a <- ma if - | f a -> return a + | f a -> pure a | t <= 0 -> liftIO $ throwM TimedOut | otherwise -> do liftIO $ threadDelay (1 # Second) @@ -1659,7 +1658,7 @@ registerService config db brig = do let pid = providerId prv let sid = serviceId svc enableService brig pid sid - return (newServiceRef sid pid) + pure (newServiceRef sid pid) runService :: Config -> @@ -1706,8 +1705,8 @@ defServiceApp buf = case eitherDecode js of Left e -> k $ responseLBS status400 [] (LC8.pack e) Right new -> do - let pks = [somePrekeys !! 0] - let lpk = someLastPrekeys !! 0 + let pks = [head somePrekeys] + let lpk = head someLastPrekeys let rsp = Ext.NewBotResponse { Ext.rsNewBotPrekeys = pks, @@ -1842,7 +1841,7 @@ svcAssertBotCreated buf bid cid = liftIO $ do assertEqual "conv" cid (testBotConv b ^. Ext.botConvId) -- TODO: Verify the conversation name -- TODO: Verify the list of members - return b + pure b _ -> throwM $ HUnitFailure Nothing "Event timeout (TestBotCreated)" svcAssertMessage :: MonadIO m => Chan TestBotEvent -> Qualified UserId -> OtrMessage -> Qualified ConvId -> m () @@ -1949,7 +1948,7 @@ testAddRemoveBotUtil localDomain pid sid cid u1 u2 h sref buf brig galley cannon forM_ [ws1, ws2] $ \ws -> wsAssertMemberJoin ws qcid quid1 [qbuid] -- Member join event for the bot svcAssertMemberJoin buf quid1 [qbuid] qcid - return (rs, bot) + pure (rs, bot) let bid = rsAddBotId rs buid = botUserId bid -- Check that the bot token grants access to the right user and conversation @@ -2033,11 +2032,11 @@ testMessageBotUtil quid uc cid pid sid sref buf brig galley cannon = do assertEqual "service" (Just sref) (omService =<< other) -- The bot greets the user WS.bracketR cannon uid $ \ws -> do - postBotMessage galley bid bc cid [(uid, uc, (toBase64Text "Hi User!"))] + postBotMessage galley bid bc cid [(uid, uc, toBase64Text "Hi User!")] !!! const 201 === statusCode wsAssertMessage ws qcid (qUntagged lbuid) bc uc (toBase64Text "Hi User!") -- The user replies - postMessage galley uid uc cid [(buid, bc, (toBase64Text "Hi Bot"))] + postMessage galley uid uc cid [(buid, bc, toBase64Text "Hi Bot")] !!! const 201 === statusCode let msg = OtrMessage uc bc (toBase64Text "Hi Bot") (Just "data") svcAssertMessage buf quid msg qcid @@ -2070,7 +2069,7 @@ prepareBotUsersTeam brig galley sref = do whitelistService brig uid1 tid pid sid -- Create conversation cid <- Team.createTeamConv galley tid uid1 [uid2] Nothing - return (u1, u2, h, tid, cid, pid, sid) + pure (u1, u2, h, tid, cid, pid, sid) addBotConv :: HasCallStack => @@ -2101,7 +2100,7 @@ addBotConv localDomain brig cannon uid1 uid2 cid pid sid buf = do forM_ [ws1, ws2] $ \ws -> wsAssertMemberJoin ws qcid quid1 [qbotId] -- Member join event for the bot svcAssertMemberJoin buf quid1 [qbotId] qcid - return (rsAddBotId rs) + pure (rsAddBotId rs) ---------------------------------------------------------------------------- -- Service search utilities (abstracted out because we have more than one diff --git a/services/brig/test/integration/API/Settings.hs b/services/brig/test/integration/API/Settings.hs index 639961890e..5f062f1bbe 100644 --- a/services/brig/test/integration/API/Settings.hs +++ b/services/brig/test/integration/API/Settings.hs @@ -38,7 +38,7 @@ import Test.Tasty.HUnit import Util tests :: Opts -> Manager -> Brig -> Galley -> IO TestTree -tests defOpts manager brig galley = return $ do +tests defOpts manager brig galley = pure $ do testGroup "settings" [ testGroup diff --git a/services/brig/test/integration/API/Team.hs b/services/brig/test/integration/API/Team.hs index 5f59e08115..dfc02eeb6d 100644 --- a/services/brig/test/integration/API/Team.hs +++ b/services/brig/test/integration/API/Team.hs @@ -66,7 +66,7 @@ tests :: Opt.Opts -> Manager -> Nginz -> Brig -> Cannon -> Galley -> AWS.Env -> tests conf m n b c g aws = do let tl = TeamSizeLimit . Opt.setMaxTeamSize . Opt.optSettings $ conf let it = Opt.setTeamInvitationTimeout . Opt.optSettings $ conf - return $ + pure $ testGroup "team" [ testGroup "invitation" $ @@ -303,7 +303,7 @@ testInvitationEmailAndPhoneAccepted brig galley = do (profile, invitation) <- createAndVerifyInvitation (extAccept inviteeEmail inviteeName inviteePhone phoneCode) extInvite brig galley liftIO $ assertEqual "Wrong name in profile" (Just inviteeName) (userDisplayName . selfUser <$> profile) liftIO $ assertEqual "Wrong name in invitation" (Just inviteeName) (inInviteeName invitation) - liftIO $ assertEqual "Wrong phone number in profile" (Just inviteePhone) (join (userPhone . selfUser <$> profile)) + liftIO $ assertEqual "Wrong phone number in profile" (Just inviteePhone) ((userPhone . selfUser) =<< profile) liftIO $ assertEqual "Wrong phone number in invitation" (Just inviteePhone) (inInviteePhone invitation) -- | FUTUREWORK: this is an alternative helper to 'createPopulatedBindingTeam'. it has been @@ -314,7 +314,7 @@ createAndVerifyInvitation :: InvitationRequest -> Brig -> Galley -> - Http ((Maybe SelfProfile), Invitation) + Http (Maybe SelfProfile, Invitation) createAndVerifyInvitation acceptFn invite brig galley = do createAndVerifyInvitation' Nothing acceptFn invite brig galley @@ -335,7 +335,7 @@ createAndVerifyInvitation' :: InvitationRequest -> Brig -> Galley -> - m ((Maybe SelfProfile), Invitation) + m (Maybe SelfProfile, Invitation) createAndVerifyInvitation' replacementBrigApp acceptFn invite brig galley = do (inviter, tid) <- createUserWithTeam brig let invitationHandshake :: @@ -375,7 +375,7 @@ createAndVerifyInvitation' replacementBrigApp acceptFn invite brig galley = do liftIO $ assertEqual "Member has no/wrong invitation metadata" invmeta (mem ^. Team.invitation) conns <- listConnections invitee brig liftIO $ assertBool "User should have no connections" (null (clConnections conns) && not (clHasMore conns)) - return (responseJsonMaybe rsp2, invitation) + pure (responseJsonMaybe rsp2, invitation) testCreateTeam :: Brig -> Galley -> AWS.Env -> Http () testCreateTeam brig galley aws = do @@ -592,7 +592,7 @@ testInvitationPaging brig = do liftIO $ assertEqual "page size" actualPageLen (length invs) liftIO $ assertEqual "has more" (count' < total) more liftIO $ validateInv `mapM_` invs - return (count', fmap inInvitation . listToMaybe . reverse $ invs) + pure (count', fmap inInvitation . listToMaybe . reverse $ invs) validateInv :: Invitation -> Assertion validateInv inv = do assertEqual "tid" tid (inTeam inv) diff --git a/services/brig/test/integration/API/Team/Util.hs b/services/brig/test/integration/API/Team/Util.hs index 9257bc2678..59e62af52b 100644 --- a/services/brig/test/integration/API/Team/Util.hs +++ b/services/brig/test/integration/API/Team/Util.hs @@ -62,11 +62,11 @@ createPopulatedBindingTeamWithNamesAndHandles :: Int -> m (TeamId, User, [User]) createPopulatedBindingTeamWithNamesAndHandles brig numMembers = do - names <- forM [1 .. numMembers] $ \_ -> randomName + names <- forM [1 .. numMembers] $ const randomName (tid, owner, mems) <- createPopulatedBindingTeamWithNames brig names membersWithHandle <- mapM (setRandomHandle brig) mems ownerWithHandle <- setRandomHandle brig owner - return (tid, ownerWithHandle, membersWithHandle) + pure (tid, ownerWithHandle, membersWithHandle) createPopulatedBindingTeam :: (MonadIO m, MonadCatch m, MonadFail m, MonadHttp m, HasCallStack) => @@ -74,9 +74,9 @@ createPopulatedBindingTeam :: Int -> m (TeamId, UserId, [User]) createPopulatedBindingTeam brig numMembers = do - names <- forM [1 .. numMembers] $ \_ -> randomName + names <- forM [1 .. numMembers] $ const randomName (tid, owner, others) <- createPopulatedBindingTeamWithNames brig names - return (tid, userId owner, others) + pure (tid, userId owner, others) createPopulatedBindingTeamWithNames :: (MonadIO m, MonadCatch m, MonadFail m, MonadHttp m, HasCallStack) => @@ -118,7 +118,7 @@ createTeam u galley = do . expect2xx . lbytes (encode newTeam) ) - maybe (error "invalid team id") return $ + maybe (error "invalid team id") pure $ fromByteString $ getHeader' "Location" r @@ -128,7 +128,7 @@ createTeam u galley = do createUserWithTeam :: (MonadIO m, MonadHttp m, MonadCatch m, MonadThrow m) => Brig -> m (UserId, TeamId) createUserWithTeam brig = do (user, tid) <- createUserWithTeam' brig - return (userId user, tid) + pure (userId user, tid) -- | Create user and binding team. -- @@ -149,7 +149,7 @@ createUserWithTeam' brig = do let Just tid = userTeam user selfTeam <- userTeam . selfUser <$> getSelfProfile brig (userId user) liftIO $ assertBool "Team ID in self profile and team table do not match" (selfTeam == Just tid) - return (user, tid) + pure (user, tid) -- | Create a team member with given permissions. createTeamMember :: @@ -165,7 +165,7 @@ createTeamMember :: createTeamMember brig galley owner tid perm = do user <- inviteAndRegisterUser owner tid brig updatePermissions owner tid (userId user, perm) galley - return user + pure user inviteAndRegisterUser :: (MonadIO m, MonadCatch m, MonadFail m, MonadHttp m, HasCallStack) => @@ -192,7 +192,7 @@ inviteAndRegisterUser u tid brig = do liftIO $ assertEqual "Team ID in registration and team table do not match" (Just tid) (userTeam invitee) selfTeam <- userTeam . selfUser <$> getSelfProfile brig (userId invitee) liftIO $ assertEqual "Team ID in self profile and team table do not match" selfTeam (Just tid) - return invitee + pure invitee updatePermissions :: HasCallStack => UserId -> TeamId -> (UserId, Team.Permissions) -> Galley -> Http () updatePermissions from tid (to, perm) galley = @@ -224,7 +224,7 @@ createTeamConv g tid u us mtimer = do ) InvitationCode -> RequestBody -accept email code = acceptWithName (Name "Bob") email code +accept = acceptWithName (Name "Bob") acceptWithName :: Name -> Email -> InvitationCode -> RequestBody acceptWithName name email code = @@ -357,7 +357,7 @@ getInvitation brig c = do brig . path "/teams/invitations/info" . queryItem "code" (toByteString' c) - return . decode . fromMaybe "" $ responseBody r + pure . decode . fromMaybe "" $ responseBody r postInvitation :: (MonadIO m, MonadHttp m, HasCallStack) => @@ -407,7 +407,7 @@ getInvitationCode brig t ref = do . queryItem "invitation_id" (toByteString' ref) ) let lbs = fromMaybe "" $ responseBody r - return $ fromByteString . fromMaybe (error "No code?") $ T.encodeUtf8 <$> (lbs ^? key "code" . _String) + pure $ fromByteString (maybe (error "No code?") T.encodeUtf8 (lbs ^? key "code" . _String)) assertNoInvitationCode :: HasCallStack => Brig -> TeamId -> InvitationId -> (MonadIO m, MonadHttp m, MonadCatch m) => m () assertNoInvitationCode brig t i = diff --git a/services/brig/test/integration/API/TeamUserSearch.hs b/services/brig/test/integration/API/TeamUserSearch.hs index dc7f59af06..7fbf184cb7 100644 --- a/services/brig/test/integration/API/TeamUserSearch.hs +++ b/services/brig/test/integration/API/TeamUserSearch.hs @@ -46,7 +46,7 @@ type TestConstraints m = (MonadFail m, MonadCatch m, MonadIO m, MonadHttp m) tests :: Opt.Opts -> Manager -> Galley -> Brig -> IO TestTree tests opts mgr _galley brig = do - return $ + pure $ testGroup "/teams/:tid/search" $ [ testWithNewIndex "can find user by email" (testSearchByEmailSameTeam brig), testWithNewIndex "empty query returns the whole team sorted" (testEmptyQuerySorted brig), diff --git a/services/brig/test/integration/API/User.hs b/services/brig/test/integration/API/User.hs index de4e9bcdd1..f2c41833e2 100644 --- a/services/brig/test/integration/API/User.hs +++ b/services/brig/test/integration/API/User.hs @@ -59,7 +59,7 @@ tests conf fbc fgc p b c ch g n aws db = do let cl = ConnectionLimit $ Opt.setUserMaxConnections (Opt.optSettings conf) let at = Opt.setActivationTimeout (Opt.optSettings conf) z <- mkZAuthEnv (Just conf) - return $ + pure $ testGroup "user" [ API.User.Client.tests cl at conf p db b c g, diff --git a/services/brig/test/integration/API/User/Account.hs b/services/brig/test/integration/API/User/Account.hs index b45ebf2db2..86883e9615 100644 --- a/services/brig/test/integration/API/User/Account.hs +++ b/services/brig/test/integration/API/User/Account.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE NumericUnderscores #-} {-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-} -- This file is part of the Wire Server implementation. @@ -68,6 +67,7 @@ import qualified Data.Vector as Vec import Federator.MockServer (FederatedRequest (..), MockException (..)) import Galley.Types.Teams (noPermissions) import Imports hiding (head) +import qualified Imports import qualified Network.HTTP.Types as HTTP import qualified Network.HTTP.Types as Http import qualified Network.Wai as Wai @@ -393,7 +393,7 @@ testCreateUserPending _ brig = do const 200 === statusCode const (Just True) === \rs' -> do self <- responseJsonMaybe rs' - return $! isNothing (userIdentity (selfUser self)) + pure $! isNothing (userIdentity (selfUser self)) -- should not appear in search suid <- userId <$> randomUser brig Search.refreshIndex brig @@ -767,12 +767,12 @@ testCreateUserAnonExpiry b = do alice <- randomUser b now <- liftIO getCurrentTime bob <- createAnonUserExpiry (Just 2) "bob" b - liftIO $ assertBool "expiry not set on regular creation" (not $ isJust $ userExpire alice) + liftIO $ assertBool "expiry not set on regular creation" (isNothing (userExpire alice)) ensureExpiry now (fromUTCTimeMillis <$> userExpire bob) "bob/register" resAlice <- getProfile (userId u1) (userId alice) resBob <- getProfile (userId u1) (userId bob) selfBob <- get (b . zUser (userId bob) . path "self") deleted selfBob)) + liftIO $ assertBool "Bob must not be in a deleted state initially" (maybe True not (deleted selfBob)) liftIO $ assertBool "Regular user should not have any expiry" (null $ expire resAlice) ensureExpiry now (expire resBob) "bob/public" ensureExpiry now (expire selfBob) "bob/self" @@ -786,7 +786,7 @@ testCreateUserAnonExpiry b = do awaitExpiry n zusr uid = do -- after expiration, a profile lookup should trigger garbage collection of ephemeral users r <- getProfile zusr uid - when (statusCode r == 200 && deleted r == Nothing && n > 0) $ do + when (statusCode r == 200 && isNothing (deleted r) && n > 0) $ do liftIO $ threadDelay 1000000 awaitExpiry (n -1) zusr uid ensureExpiry :: UTCTime -> Maybe UTCTime -> String -> Http () @@ -799,9 +799,9 @@ testCreateUserAnonExpiry b = do liftIO $ assertBool "expiry must in be the future" (diff >= fromIntegral minExp) liftIO $ assertBool "expiry must be less than 10 days" (diff < fromIntegral maxExp) expire :: ResponseLBS -> Maybe UTCTime - expire r = join $ field "expires_at" <$> responseJsonMaybe r + expire r = field "expires_at" =<< responseJsonMaybe r deleted :: ResponseLBS -> Maybe Bool - deleted r = join $ field "deleted" <$> responseJsonMaybe r + deleted r = field "deleted" =<< responseJsonMaybe r field :: FromJSON a => Text -> Value -> Maybe a field f u = u ^? key f >>= maybeFromJSON @@ -1030,7 +1030,7 @@ testGetByIdentity brig = do const 200 === statusCode const (Just [uid]) === getUids where - getUids r = return . fmap (userId . accountUser) =<< responseJsonMaybe r + getUids r = fmap (userId . accountUser) <$> responseJsonMaybe r testPasswordSet :: Brig -> Http () testPasswordSet brig = do @@ -1254,7 +1254,7 @@ testDeleteUserByPassword brig cannon aws = do con32 <- putConnection brig uid3 uid2 Accepted (responseJsonError =<< get (brig . path "/self" . zUser (userId member))) let ssoids1 = [UserSSOId (mkSampleUref "1" "1"), UserSSOId (mkSampleUref "1" "2")] @@ -1487,8 +1487,8 @@ testUpdateSSOId brig galley = do -- , mkMember False False -- , mkMember False True ] - sequence_ $ zipWith go users ssoids1 - sequence_ $ zipWith go users ssoids2 + zipWithM_ go users ssoids1 + zipWithM_ go users ssoids2 testDomainsBlockedForRegistration :: Opt.Opts -> Brig -> Http () testDomainsBlockedForRegistration opts brig = withDomainsBlockedForRegistration opts ["bad1.domain.com", "bad2.domain.com"] $ do diff --git a/services/brig/test/integration/API/User/Auth.hs b/services/brig/test/integration/API/User/Auth.hs index 215832218e..b13b261d5a 100644 --- a/services/brig/test/integration/API/User/Auth.hs +++ b/services/brig/test/integration/API/User/Auth.hs @@ -171,7 +171,7 @@ randomAccessToken :: forall u a. ZAuth.TokenPair u a => ZAuth (ZAuth.Token a) randomAccessToken = randomUserToken @u >>= ZAuth.newAccessToken randomUserToken :: ZAuth.UserTokenLike u => ZAuth (ZAuth.Token u) -randomUserToken = (Id <$> liftIO UUID.nextRandom) >>= ZAuth.newUserToken +randomUserToken = liftIO UUID.nextRandom >>= ZAuth.newUserToken . Id ------------------------------------------------------------------------------- -- Nginz authentication tests (end-to-end sanity checks) @@ -192,14 +192,14 @@ testNginz b n = do -- Note: If you get 403 test failures: -- 1. check that the private/public keys in brig and nginz match. -- 2. check that the nginz acl file is correct. - _rs <- get (n . path "/clients" . header "Authorization" ("Bearer " <> (toByteString' t))) + _rs <- get (n . path "/clients" . header "Authorization" ("Bearer " <> toByteString' t)) liftIO $ assertEqual "Ensure nginz is started. Ensure nginz and brig share the same private/public zauth keys. Ensure ACL file is correct." 200 (statusCode _rs) -- ensure nginz allows refresh at /access _rs <- - post (n . path "/access" . cookie c . header "Authorization" ("Bearer " <> (toByteString' t))) toByteString' t)) (toByteString' t))) !!! const 200 === statusCode + get (n . path "/notifications" . header "Authorization" ("Bearer " <> toByteString' t)) !!! const 200 === statusCode testNginzLegalHold :: Brig -> Galley -> Nginz -> Http () testNginzLegalHold b g n = do @@ -226,13 +226,13 @@ testNginzLegalHold b g n = do pure (c, t) -- ensure nginz allows passing legalhold cookies / tokens through to /access - post (n . path "/access" . cookie c . header "Authorization" ("Bearer " <> (toByteString' t))) !!! do + post (n . path "/access" . cookie c . header "Authorization" ("Bearer " <> toByteString' t)) !!! do const 200 === statusCode -- ensure legalhold tokens CANNOT fetch /clients - get (n . path "/clients" . header "Authorization" ("Bearer " <> (toByteString' t))) !!! const 403 === statusCode - get (n . path "/self" . header "Authorization" ("Bearer " <> (toByteString' t))) !!! const 403 === statusCode + get (n . path "/clients" . header "Authorization" ("Bearer " <> toByteString' t)) !!! const 403 === statusCode + get (n . path "/self" . header "Authorization" ("Bearer " <> toByteString' t)) !!! const 403 === statusCode -- ensure legal hold tokens can fetch notifications - get (n . path "/notifications" . header "Authorization" ("Bearer " <> (toByteString' t))) !!! const 200 === statusCode + get (n . path "/notifications" . header "Authorization" ("Bearer " <> toByteString' t)) !!! const 200 === statusCode -- | Corner case for 'testNginz': when upgrading a wire backend from the old behavior (setting -- cookie domain to eg. @*.wire.com@) to the new behavior (leaving cookie domain empty, @@ -901,7 +901,7 @@ getAndTestDBSupersededCookieAndItsValidSuccessor config b n = do [Nothing] @=? map cookieSucc _cs -- Return non-expired cookie but removed from DB (because it was renewed) -- and a valid cookie - return (c, c') + pure (c, c') testNewSessionCookie :: Opts.Opts -> Brig -> Http () testNewSessionCookie config b = do @@ -1073,7 +1073,7 @@ testTooManyCookies config b = do loginWhenAllowed pwl t = do x <- login b pwl t <* wait case statusCode x of - 200 -> return $ decodeCookie x + 200 -> pure $ decodeCookie x 429 -> do -- After the amount of time specified in "Retry-After", though, -- throttling should stop and login should work again @@ -1126,12 +1126,12 @@ testReauthentication b = do ----------------------------------------------------------------------------- -- Helpers -prepareLegalHoldUser :: Brig -> Galley -> Http (UserId) +prepareLegalHoldUser :: Brig -> Galley -> Http UserId prepareLegalHoldUser brig galley = do (uid, tid) <- createUserWithTeam brig -- enable it for this team - without that, legalhold login will fail. putLHWhitelistTeam galley tid !!! const 200 === statusCode - return uid + pure uid getCookieId :: forall u. (HasCallStack, ZAuth.UserTokenLike u) => Http.Cookie -> CookieId getCookieId c = @@ -1153,7 +1153,7 @@ listCookiesWithLabel b u l = do ) responseJsonMaybe rs - return cs + pure cs where labels = BS.intercalate "," $ map toByteString' l diff --git a/services/brig/test/integration/API/User/Connection.hs b/services/brig/test/integration/API/User/Connection.hs index 0b73129ce8..555f9e576f 100644 --- a/services/brig/test/integration/API/User/Connection.hs +++ b/services/brig/test/integration/API/User/Connection.hs @@ -624,7 +624,7 @@ testLocalConnectionsPaging b = do let (conns, more) = (fmap clConnections &&& fmap clHasMore) $ responseJsonMaybe r liftIO $ assertEqual "page size" (Just n) (length <$> conns) liftIO $ assertEqual "has more" (Just (count' < total)) more - return . (count',) $ (conns >>= fmap (qUnqualified . ucTo) . listToMaybe . reverse) + pure . (count',) $ (conns >>= fmap (qUnqualified . ucTo) . listToMaybe . reverse) testAllConnectionsPaging :: Brig -> DB.ClientState -> Http () testAllConnectionsPaging b db = do @@ -688,7 +688,7 @@ testConnectionLimit brig (ConnectionLimit l) = do newConn from = do to <- userId <$> randomUser brig postConnection brig from to !!! const 201 === statusCode - return to + pure to assertLimited = do const 403 === statusCode const (Just "connection-limit") === fmap Error.label . responseJsonMaybe @@ -713,7 +713,7 @@ testConnectionLimitQualified brig (ConnectionLimit l) = do newConn from = do to <- userQualifiedId <$> randomUser brig postConnectionQualified brig from to !!! const 201 === statusCode - return to + pure to assertLimited = do const 403 === statusCode const (Just "connection-limit") === fmap Error.label . responseJsonMaybe diff --git a/services/brig/test/integration/API/User/RichInfo.hs b/services/brig/test/integration/API/User/RichInfo.hs index 1597867584..66c8b9b247 100644 --- a/services/brig/test/integration/API/User/RichInfo.hs +++ b/services/brig/test/integration/API/User/RichInfo.hs @@ -124,7 +124,7 @@ testRichInfoSizeLimit brig conf = do ] bad2 = mkRichInfoAssocList $ - [0 .. ((maxSize `div` 2))] + [0 .. (maxSize `div` 2)] <&> \i -> RichField (CI.mk $ Text.pack $ show i) "#" putRichInfo brig owner bad1 !!! const 413 === statusCode putRichInfo brig owner bad2 !!! const 413 === statusCode diff --git a/services/brig/test/integration/API/User/Util.hs b/services/brig/test/integration/API/User/Util.hs index c13591cbf4..916c527260 100644 --- a/services/brig/test/integration/API/User/Util.hs +++ b/services/brig/test/integration/API/User/Util.hs @@ -105,7 +105,7 @@ setRandomHandle brig user = do ) !!! const 200 === statusCode - return user {userHandle = Just (Handle h)} + pure user {userHandle = Just (Handle h)} -- Note: This actually _will_ send out an email, so we ensure that the email -- used here has a domain 'simulator.amazonses.com'. @@ -139,7 +139,7 @@ createRandomPhoneUser brig = do get (brig . path "/self" . zUser uid) !!! do const 200 === statusCode const (Just phn) === (userPhone <=< responseJsonMaybe) - return (uid, phn) + pure (uid, phn) initiatePasswordReset :: Brig -> Email -> (MonadIO m, MonadHttp m) => m ResponseLBS initiatePasswordReset brig email = @@ -205,7 +205,7 @@ preparePasswordReset brig cs email uid newpw = do let Just pwcode = PasswordResetCode . Ascii.unsafeFromText <$> (lbs ^? key "code" . _String) ident <- PasswordResetIdentityKey <$> runSem (mkPasswordResetKey uid) let complete = CompletePasswordReset ident pwcode newpw - return complete + pure complete where runSem = liftIO . runFinal @IO . interpretClientToIO cs . codeStoreToCassandra @DB.Client @@ -331,7 +331,7 @@ countCookies brig u label = do ) (preview (key "cookies" . _Array) =<< responseJsonMaybe @Value r) + pure $ Vec.length <$> (preview (key "cookies" . _Array) =<< responseJsonMaybe @Value r) assertConnections :: (MonadCatch m, MonadIO m, MonadHttp m, HasCallStack) => Brig -> UserId -> [ConnectionStatus] -> m () assertConnections brig u connections = diff --git a/services/brig/test/integration/API/UserPendingActivation.hs b/services/brig/test/integration/API/UserPendingActivation.hs index 4e3e02b60b..b42b51868a 100644 --- a/services/brig/test/integration/API/UserPendingActivation.hs +++ b/services/brig/test/integration/API/UserPendingActivation.hs @@ -70,7 +70,7 @@ import Wire.API.User.Scim (CreateScimToken (..), ScimToken, ScimUserExtra (ScimU tests :: Opts -> Manager -> ClientState -> Brig -> Galley -> Spar -> IO TestTree tests opts m db brig galley spar = do - return $ + pure $ testGroup "cleanExpiredPendingInvitations" [ test m "expired users get cleaned" (testCleanExpiredPendingInvitations opts db brig galley spar), @@ -139,7 +139,7 @@ userExists uid = do case x of Nothing -> False Just (_, mbStatus) -> - maybe True (/= Deleted) mbStatus + Just Deleted /= mbStatus where usersSelect :: PrepQuery R (Identity UserId) (UserId, Maybe AccountStatus) usersSelect = "SELECT id, status FROM user where id = ?" @@ -176,7 +176,7 @@ createUserWithTeamDisableSSO brg gly = do () <- Control.Exception.assert {- "Team ID in self profile and team table do not match" -} (selfTeam == Just tid) $ pure () - return (uid, tid) + pure (uid, tid) randomScimUser :: (HasCallStack, MonadRandom m, MonadIO m) => m (Scim.User.User SparTag) randomScimUser = fst <$> randomScimUserWithSubject @@ -310,7 +310,7 @@ getInvitationCode brig t ref = do . queryItem "invitation_id" (toByteString' ref) ) let lbs = fromMaybe "" $ responseBody r - return $ fromByteString . fromMaybe (error "No code?") $ encodeUtf8 <$> (lbs ^? key "code" . _String) + pure $ fromByteString (maybe (error "No code?") encodeUtf8 (lbs ^? key "code" . _String)) -- | Create a SCIM token. createToken_ :: diff --git a/services/brig/test/integration/Federation/End2end.hs b/services/brig/test/integration/Federation/End2end.hs index 3f7ad9d58b..9e11e07d72 100644 --- a/services/brig/test/integration/Federation/End2end.hs +++ b/services/brig/test/integration/Federation/End2end.hs @@ -498,7 +498,7 @@ testSendMessage brig1 brig2 galley2 cannon1 = do <$> addClient brig1 (userId alice) - (defNewClient PermanentClientType [] (someLastPrekeys !! 0)) + (defNewClient PermanentClientType [] (Imports.head someLastPrekeys)) -- create bob user and client on domain 2 bob <- randomUser brig2 @@ -523,7 +523,7 @@ testSendMessage brig1 brig2 galley2 cannon1 = do rcpts = [(userQualifiedId alice, aliceClient, msgText)] msg = mkQualifiedOtrPayload bobClient rcpts "" MismatchReportAll - WS.bracketR cannon1 (userId alice) $ \(wsAlice) -> do + WS.bracketR cannon1 (userId alice) $ \wsAlice -> do post ( galley2 . paths @@ -562,7 +562,7 @@ testSendMessageToRemoteConv brig1 brig2 galley1 galley2 cannon1 = do alice <- randomUser brig1 aliceClient <- fmap clientId . responseJsonError - =<< addClient brig1 (userId alice) (defNewClient PermanentClientType [] (someLastPrekeys !! 0)) + =<< addClient brig1 (userId alice) (defNewClient PermanentClientType [] (Imports.head someLastPrekeys)) do + WS.bracketR cannon1 (userId alice) $ \wsAlice -> do post ( galley2 . paths diff --git a/services/brig/test/integration/Federation/Util.hs b/services/brig/test/integration/Federation/Util.hs index 9131cd1fa7..a78bf654a7 100644 --- a/services/brig/test/integration/Federation/Util.hs +++ b/services/brig/test/integration/Federation/Util.hs @@ -1,5 +1,4 @@ {-# LANGUAGE PartialTypeSignatures #-} -{-# LANGUAGE QuasiQuotes #-} {-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-} {-# OPTIONS_GHC -Wno-partial-type-signatures #-} {-# OPTIONS_GHC -Wno-unused-imports #-} diff --git a/services/brig/test/integration/Index/Create.hs b/services/brig/test/integration/Index/Create.hs index 1b703647a3..686af9e33f 100644 --- a/services/brig/test/integration/Index/Create.hs +++ b/services/brig/test/integration/Index/Create.hs @@ -51,7 +51,7 @@ testCreateIndexWhenNotPresent brigOpts = do case parseURI strictURIParserOptions (Text.encodeUtf8 esURL) of Left e -> fail $ "Invalid ES URL: " <> show esURL <> "\nerror: " <> show e Right esURI -> do - indexName <- ES.IndexName . Text.pack <$> (replicateM 20 $ Random.randomRIO ('a', 'z')) + indexName <- ES.IndexName . Text.pack <$> replicateM 20 (Random.randomRIO ('a', 'z')) let replicas = 2 shards = 2 refreshInterval = 5 @@ -59,7 +59,7 @@ testCreateIndexWhenNotPresent brigOpts = do IndexOpts.localElasticSettings & IndexOpts.esServer .~ esURI & IndexOpts.esIndex .~ indexName - & IndexOpts.esIndexReplicas .~ (ES.ReplicaCount replicas) + & IndexOpts.esIndexReplicas .~ ES.ReplicaCount replicas & IndexOpts.esIndexShardCount .~ shards & IndexOpts.esIndexRefreshInterval .~ refreshInterval devNullLogger <- Log.create (Log.Path "/dev/null") @@ -83,7 +83,7 @@ testCreateIndexWhenPresent brigOpts = do case parseURI strictURIParserOptions (Text.encodeUtf8 esURL) of Left e -> fail $ "Invalid ES URL: " <> show esURL <> "\nerror: " <> show e Right esURI -> do - indexName <- ES.IndexName . Text.pack <$> (replicateM 20 $ Random.randomRIO ('a', 'z')) + indexName <- ES.IndexName . Text.pack <$> replicateM 20 (Random.randomRIO ('a', 'z')) ES.withBH HTTP.defaultManagerSettings (ES.Server esURL) $ do _ <- ES.createIndex (ES.IndexSettings (ES.ShardCount 1) (ES.ReplicaCount 1)) indexName indexExists <- ES.indexExists indexName @@ -96,7 +96,7 @@ testCreateIndexWhenPresent brigOpts = do IndexOpts.localElasticSettings & IndexOpts.esServer .~ esURI & IndexOpts.esIndex .~ indexName - & IndexOpts.esIndexReplicas .~ (ES.ReplicaCount replicas) + & IndexOpts.esIndexReplicas .~ ES.ReplicaCount replicas & IndexOpts.esIndexShardCount .~ shards & IndexOpts.esIndexRefreshInterval .~ refreshInterval devNullLogger <- Log.create (Log.Path "/dev/null") diff --git a/services/brig/test/integration/Main.hs b/services/brig/test/integration/Main.hs index e39c075e45..586273d439 100644 --- a/services/brig/test/integration/Main.hs +++ b/services/brig/test/integration/Main.hs @@ -117,9 +117,9 @@ runTests iConf brigOpts otherArgs = do Opts.TurnSourceFiles files -> files Opts.TurnSourceDNS _ -> error "The integration tests can only be run when TurnServers are sourced from files" localDomain = brigOpts ^. Opts.optionSettings . Opts.federationDomain - casHost = (\v -> (Opts.cassandra v) ^. casEndpoint . epHost) brigOpts - casPort = (\v -> (Opts.cassandra v) ^. casEndpoint . epPort) brigOpts - casKey = (\v -> (Opts.cassandra v) ^. casKeyspace) brigOpts + casHost = (\v -> Opts.cassandra v ^. casEndpoint . epHost) brigOpts + casPort = (\v -> Opts.cassandra v ^. casEndpoint . epPort) brigOpts + casKey = (\v -> Opts.cassandra v ^. casKeyspace) brigOpts awsOpts = Opts.aws brigOpts lg <- Logger.new Logger.defSettings -- TODO: use mkLogger'? db <- defInitCassandra casKey casHost casPort lg @@ -176,8 +176,8 @@ runTests iConf brigOpts otherArgs = do parseEmailAWSOpts :: IO (Maybe Opts.EmailAWSOpts) parseEmailAWSOpts = case Opts.email . Opts.emailSMS $ brigOpts of - (Opts.EmailAWS aws) -> return (Just aws) - (Opts.EmailSMTP _) -> return Nothing + (Opts.EmailAWS aws) -> pure (Just aws) + (Opts.EmailSMTP _) -> pure Nothing main :: IO () main = withOpenSSL $ do @@ -187,8 +187,8 @@ main = withOpenSSL $ do let configArgs = getConfigArgs args let otherArgs = args \\ configArgs (iPath, bPath) <- withArgs configArgs parseConfigPaths - iConf <- join $ handleParseError <$> decodeFileEither iPath - bConf <- join $ handleParseError <$> decodeFileEither bPath + iConf <- handleParseError =<< decodeFileEither iPath + bConf <- handleParseError =<< decodeFileEither bPath brigOpts <- maybe (fail "failed to parse brig options file") pure bConf integrationConfig <- maybe (fail "failed to parse integration.yaml file") pure iConf runTests integrationConfig brigOpts otherArgs @@ -211,17 +211,17 @@ parseConfigPaths = do pathParser :: Parser (String, String) pathParser = (,) - <$> ( strOption $ - long "integration-config" - <> short 'i' - <> help "Integration config to load" - <> showDefault - <> value defaultIntPath - ) - <*> ( strOption $ - long "service-config" - <> short 's' - <> help "Brig application config to load" - <> showDefault - <> value defaultBrigPath - ) + <$> strOption + ( long "integration-config" + <> short 'i' + <> help "Integration config to load" + <> showDefault + <> value defaultIntPath + ) + <*> strOption + ( long "service-config" + <> short 's' + <> help "Brig application config to load" + <> showDefault + <> value defaultBrigPath + ) diff --git a/services/brig/test/integration/Util.hs b/services/brig/test/integration/Util.hs index ef7894df17..a6f8138f15 100644 --- a/services/brig/test/integration/Util.hs +++ b/services/brig/test/integration/Util.hs @@ -190,7 +190,7 @@ instance ToJSON SESNotification where [ "notificationType" .= ("Bounce" :: Text), "bounce" .= object - [ "bouncedRecipients" .= (fmap (\e -> object ["emailAddress" .= e]) ems), + [ "bouncedRecipients" .= fmap (\e -> object ["emailAddress" .= e]) ems, "bounceType" .= typ ] ] @@ -199,7 +199,7 @@ instance ToJSON SESNotification where [ "notificationType" .= ("Complaint" :: Text), "complaint" .= object - [ "complainedRecipients" .= (fmap (\e -> object ["emailAddress" .= e]) ems) + [ "complainedRecipients" .= fmap (\e -> object ["emailAddress" .= e]) ems ] ] @@ -322,13 +322,13 @@ getActivationCode brig ep = do let lbs = fromMaybe "" $ responseBody r let akey = ActivationKey . Ascii.unsafeFromText <$> (lbs ^? key "key" . _String) let acode = ActivationCode . Ascii.unsafeFromText <$> (lbs ^? key "code" . _String) - return $ (,) <$> akey <*> acode + pure $ (,) <$> akey <*> acode getPhoneLoginCode :: Brig -> Phone -> Http (Maybe LoginCode) getPhoneLoginCode brig p = do r <- get $ brig . path "/i/users/login-code" . queryItem "phone" (toByteString' p) let lbs = fromMaybe "" $ responseBody r - return (LoginCode <$> (lbs ^? key "code" . _String)) + pure (LoginCode <$> (lbs ^? key "code" . _String)) assertUpdateNotification :: WS.WebSocket -> UserId -> UserUpdate -> IO Notification assertUpdateNotification ws uid upd = WS.assertMatch (5 # Second) ws $ \n -> do @@ -411,12 +411,12 @@ postUserWithEmail hasPassword validateBody name email havePhone ssoid teamid bri postUserInternal :: Object -> Brig -> Http User postUserInternal payload brig = do rs <- post (brig . path "/i/users" . contentJson . body (RequestBodyLBS $ encode payload)) Brig -> Http User postUserRegister payload brig = do rs <- postUserRegister' payload brig Object -> Brig -> m ResponseLBS postUserRegister' payload brig = do @@ -748,8 +748,8 @@ isMember g usr cnv = do . paths ["i", "conversations", toByteString' cnv, "members", toByteString' (tUnqualified usr)] . expect2xx case responseJsonMaybe res of - Nothing -> return False - Just m -> return (qUntagged usr == memId m) + Nothing -> pure False + Just m -> pure (qUntagged usr == memId m) getStatus :: HasCallStack => Brig -> UserId -> (MonadIO m, MonadHttp m) => m AccountStatus getStatus brig u = @@ -802,7 +802,7 @@ mkEmailRandomLocalSuffix :: MonadIO m => Text -> m Email mkEmailRandomLocalSuffix e = do uid <- liftIO UUID.nextRandom case parseEmail e of - Just (Email loc dom) -> return $ Email (loc <> "+" <> UUID.toText uid) dom + Just (Email loc dom) -> pure $ Email (loc <> "+" <> UUID.toText uid) dom Nothing -> error $ "Invalid email address: " ++ Text.unpack e -- | Generate emails that are in the trusted whitelist of domains whose @+@ suffices count for email @@ -825,7 +825,7 @@ randomPhone :: MonadIO m => m Phone randomPhone = liftIO $ do nrs <- map show <$> replicateM 14 (randomRIO (0, 9) :: IO Int) let phone = parsePhone . Text.pack $ "+0" ++ concat nrs - return $ fromMaybe (error "Invalid random phone#") phone + pure $ fromMaybe (error "Invalid random phone#") phone randomActivationCode :: (HasCallStack, MonadIO m) => m ActivationCode randomActivationCode = @@ -938,7 +938,7 @@ randomBytes n = BS.pack <$> replicateM n randomIO randomHandle :: MonadIO m => m Text randomHandle = liftIO $ do nrs <- replicateM 21 (randomRIO (97, 122)) -- a-z - return (Text.pack (map chr nrs)) + pure (Text.pack (map chr nrs)) randomName :: MonadIO m => m Name randomName = randomNameWithMaxLen 128 @@ -956,9 +956,9 @@ randomNameWithMaxLen :: MonadIO m => Word -> m Name randomNameWithMaxLen maxLen = liftIO $ do len <- randomRIO (2, maxLen) chars <- fill len [] - return $ Name (Text.pack chars) + pure $ Name (Text.pack chars) where - fill 0 chars = return chars + fill 0 chars = pure chars fill 1 chars = (: chars) <$> randLetter fill n chars = do c <- randChar @@ -969,14 +969,14 @@ randomNameWithMaxLen maxLen = liftIO $ do randLetter = do c <- randChar if isLetter c - then return c + then pure c else randLetter retryWhileN :: (MonadIO m) => Int -> (a -> Bool) -> m a -> m a retryWhileN n f m = retrying (constantDelay 1000000 <> limitRetries n) - (const (return . f)) + (const (pure . f)) (const m) recoverN :: (MonadIO m, MonadMask m) => Int -> m a -> m a @@ -1036,7 +1036,7 @@ aFewTimes retrying (exponentialBackoff 1000 <> limitRetries retries) (\_ -> pure . not . good) - (\_ -> action) + (const action) assertOne :: (HasCallStack, MonadIO m, Show a) => [a] -> m a assertOne [a] = pure a diff --git a/services/brig/test/integration/Util/AWS.hs b/services/brig/test/integration/Util/AWS.hs index 92a3d8e687..8e10d0cfea 100644 --- a/services/brig/test/integration/Util/AWS.hs +++ b/services/brig/test/integration/Util/AWS.hs @@ -109,7 +109,7 @@ assertUserId :: String -> UserId -> PU.UserEvent -> IO () assertUserId l uid ev = assertEqual (l <> "userId") uid (Id $ fromMaybe (error "failed to decode userId") $ UUID.fromByteString $ Lazy.fromStrict (ev ^. PU.userId)) assertTeamId :: String -> Maybe TeamId -> PU.UserEvent -> IO () -assertTeamId l (Just tid) ev = assertEqual (l <> "teamId should exist") tid (Id . fromMaybe (error "failed to parse teamId") . join $ fmap (UUID.fromByteString . Lazy.fromStrict) (ev ^? PU.teamId)) +assertTeamId l (Just tid) ev = assertEqual (l <> "teamId should exist") tid ((Id . fromMaybe (error "failed to parse teamId")) ((UUID.fromByteString . Lazy.fromStrict) =<< (ev ^? PU.teamId))) assertTeamId l Nothing ev = assertEqual (l <> "teamId should not exist") Nothing (ev ^. PU.maybe'teamId) assertName :: String -> Maybe Name -> PU.UserEvent -> IO ()