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

module Test.PasswordReset where

import API.Brig
import API.BrigInternal hiding (activate)
import API.Common
import SetupHelpers
import Testlib.Prelude

-- @SF.Provisioning @TSFI.RESTfulAPI @S1
--
-- This test checks the password reset functionality of the application.
-- Besides a successful password reset the following scenarios are tested:
-- - Subsequent password reset requests should succeed without errors.
-- - Attempting to reset the password with an incorrect key or code should fail.
-- - Attempting to log in with the old password after a successful reset should fail.
-- - Attempting to log in with the new password after a successful reset should succeed.
-- - Attempting to reset the password again to the same new password should fail.
testPasswordResetShouldSucceedButFailOnWrongInputs :: (HasCallStack) => App ()
testPasswordResetShouldSucceedButFailOnWrongInputs :: HasCallStack => App ()
testPasswordResetShouldSucceedButFailOnWrongInputs = do
  let noRateLimitCfg :: ServiceOverrides
noRateLimitCfg =
        ServiceOverrides
forall a. Default a => a
def
          { brigCfg =
              setField "optSettings.setPasswordHashingRateLimit.userLimit.inverseRate" (0 :: Int)
          }
  ServiceOverrides -> (HasCallStack => String -> App ()) -> App ()
forall a.
HasCallStack =>
ServiceOverrides -> (HasCallStack => String -> App a) -> App a
withModifiedBackend ServiceOverrides
noRateLimitCfg ((HasCallStack => String -> App ()) -> App ())
-> (HasCallStack => String -> App ()) -> App ()
forall a b. (a -> b) -> a -> b
$ \String
domain -> do
    u <- String -> CreateUser -> App Value
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> CreateUser -> App Value
randomUser String
domain CreateUser
forall a. Default a => a
def
    email <- u %. "email" & asString
    passwordReset u email >>= assertSuccess
    -- Even though a password reset is now in progress
    -- we expect a successful response from a subsequent request to not leak any information
    -- about the requested email.
    passwordReset u email >>= assertSuccess

    (key, code) <- getPasswordResetData domain email
    let newPassword = String
"newpassword"

    -- complete password reset with incorrect key/code should fail
    completePasswordReset u "wrong-key" code newPassword >>= assertStatus 400
    login u email newPassword >>= assertStatus 403
    completePasswordReset u key "wrong-code" newPassword >>= assertStatus 400
    login u email newPassword >>= assertStatus 403

    -- complete password reset with correct key and code should succeed
    completePasswordReset u key code newPassword >>= assertSuccess

    -- try login with old password should fail
    login u email defPassword >>= assertStatus 403
    -- login with new password should succeed
    login u email newPassword >>= assertSuccess
    -- reset password again to the same new password should fail
    passwordReset u email >>= assertSuccess
    (nextKey, nextCode) <- getPasswordResetData domain email
    bindResponse (completePasswordReset u nextKey nextCode newPassword) $ \Response
resp -> do
      Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
409
      Response
resp.json App Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"label" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"password-must-differ"

-- @END

testPasswordResetAfterEmailUpdate :: (HasCallStack) => App ()
testPasswordResetAfterEmailUpdate :: HasCallStack => App ()
testPasswordResetAfterEmailUpdate = do
  u <- Domain -> CreateUser -> App Value
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> CreateUser -> App Value
randomUser Domain
OwnDomain CreateUser
forall a. Default a => a
def
  email <- u %. "email" & asString
  (cookie, token) <- bindResponse (login u email defPassword) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    token <- Response
resp.json App Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"access_token" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString
    let cookie = Maybe String -> String
forall a. HasCallStack => Maybe a -> a
fromJust (Maybe String -> String) -> Maybe String -> String
forall a b. (a -> b) -> a -> b
$ String -> Response -> Maybe String
getCookie String
"zuid" Response
resp
    pure ("zuid=" <> cookie, token)

  -- initiate email update
  newEmail <- randomEmail
  updateEmail u newEmail cookie token >>= assertSuccess

  -- initiate password reset
  passwordReset u email >>= assertSuccess
  (key, code) <- getPasswordResetData OwnDomain email

  -- activate new email
  bindResponse (getActivationCode u newEmail) $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    activationKey <- Response
resp.json App Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"key" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString
    activationCode <- resp.json %. "code" & asString
    activate u activationKey activationCode >>= assertSuccess

  bindResponse (getSelf u) $ \Response
resp -> do
    actualEmail <- Response
resp.json App Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"email"
    actualEmail `shouldMatch` newEmail

  -- attempting to complete password reset should fail
  bindResponse (completePasswordReset u key code "newpassword") $ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
400
    Response
resp.json App Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"label" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"invalid-code"

testPasswordResetInvalidPasswordLength :: App ()
testPasswordResetInvalidPasswordLength :: App ()
testPasswordResetInvalidPasswordLength = do
  u <- Domain -> CreateUser -> App Value
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> CreateUser -> App Value
randomUser Domain
OwnDomain CreateUser
forall a. Default a => a
def
  email <- u %. "email" & asString
  passwordReset u email >>= assertSuccess
  (key, code) <- getPasswordResetData OwnDomain email

  -- complete password reset with a password that is too short should fail
  let shortPassword = String
"123456"
  completePasswordReset u key code shortPassword >>= assertStatus 400

  -- try login with new password should fail
  login u email shortPassword >>= assertStatus 403

getPasswordResetData :: (HasCallStack, MakesValue domain) => domain -> String -> App (String, String)
getPasswordResetData :: forall domain.
(HasCallStack, MakesValue domain) =>
domain -> String -> App (String, String)
getPasswordResetData domain
domain String
email = do
  App Response
-> (Response -> App (String, String)) -> App (String, String)
forall a.
HasCallStack =>
App Response -> (Response -> App a) -> App a
bindResponse (domain -> String -> App Response
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> String -> App Response
getPasswordResetCode domain
domain String
email) ((Response -> App (String, String)) -> App (String, String))
-> (Response -> App (String, String)) -> App (String, String)
forall a b. (a -> b) -> a -> b
$ \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    (,) (String -> String -> (String, String))
-> App String -> App (String -> (String, String))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Response
resp.json App Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"key" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString) App (String -> (String, String))
-> App String -> App (String, String)
forall a b. App (a -> b) -> App a -> App b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> (Response
resp.json App Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"code" App Value -> (App Value -> App String) -> App String
forall a b. a -> (a -> b) -> b
& App Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString)