{-# LANGUAGE DuplicateRecordFields #-}
{-# OPTIONS_GHC -Wno-ambiguous-fields #-}

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

-- | SCIM is the only writer of the user attributes it owns: since we never push SCIM data
-- back to the IdP\/provisioning side, any change by somebody else would silently put wire
-- and the SCIM client out of sync.  So for a user with @managed_by == scim@, every field of
-- @Wire.API.User.User@ that SCIM can write (ie., that is derived from
-- @Wire.API.User.Scim.ValidScimUser@) must be rejected for all other actors.
--
-- The remaining @User@ fields (@userTextStatus@, @userPict@, @userAssets@, @userAccentId@,
-- @userSupportedProtocols@, @userSearchable@, ...) are not SCIM-managed and stay writable;
-- 'testNonScimManagedFieldsStayWritable' pins that down so the guards above don't
-- accidentally grow into a blanket lock.  SCIM-provisioned user /groups/ are not
-- write-protected either; see 'testScimGroupIsWritableByTeamAdmin'.
module Test.Spar.SCIM where

import API.Brig
import API.BrigInternal (getUsersByEmail)
import API.Common (defPassword, randomEmail)
import qualified API.Galley as Galley
import API.Spar
import SetupHelpers
import Testlib.Prelude

-- | Team with a SCIM token, one SCIM-provisioned (and registered, hence password-owning)
-- member, and one ordinary wire-managed member.  Returns (owner, scim user, wire user).
setupScimTeam :: (HasCallStack) => App (Value, Value, Value)
setupScimTeam :: HasCallStack => App (Value, Value, Value)
setupScimTeam = do
  (owner, tid, [wireUser]) <- Domain -> Int -> App (Value, String, [Value])
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> Int -> App (Value, String, [Value])
createTeam Domain
OwnDomain Int
2
  tok <- createScimToken owner def >>= getJSON 200 >>= (%. "token") >>= asString
  scimUser <- randomScimUser
  email <- scimUser %. "emails" >>= asList >>= assertOne >>= (%. "value") >>= asString
  void $ createScimUser OwnDomain tok scimUser >>= getJSON 201
  registerInvitedUser OwnDomain tid email
  user <- getUsersByEmail OwnDomain [email] >>= getJSON 200 >>= asList >>= assertOne
  user %. "managed_by" `shouldMatch` "scim"
  pure (owner, user, wireUser)

-- | @userHandle@ and @userDisplayName@ are SCIM-managed, so the user may not change them
-- herself.
testScimUserIsNotAllowedToChangeName :: (HasCallStack) => App ()
testScimUserIsNotAllowedToChangeName :: HasCallStack => App ()
testScimUserIsNotAllowedToChangeName = do
  (_owner, scimUser, _wireUser) <- App (Value, Value, Value)
HasCallStack => App (Value, Value, Value)
setupScimTeam
  putHandle scimUser "foo" `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
403
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"label" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"managed-by-scim"
  putSelf scimUser def {name = Just "foo"} `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
403
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"label" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"managed-by-scim"

-- | @userLocale@ is SCIM-managed, so the user may not change it herself.  (The same is
-- checked for e2eid teams in 'Test.Spar.testAllowUpdatesBySCIMWhenE2EIdEnabled'; here the
-- team has no e2eid, so the lock can only come from @managed_by == scim@.)
testScimManagedLocaleIsLockedForUser :: (HasCallStack) => App ()
testScimManagedLocaleIsLockedForUser :: HasCallStack => App ()
testScimManagedLocaleIsLockedForUser = do
  (_owner, scimUser, wireUser) <- App (Value, Value, Value)
HasCallStack => App (Value, Value, Value)
setupScimTeam
  localeBefore <- scimUser %. "locale"

  putSelfLocale scimUser "de" `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
403
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"label" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"managed-by-scim"
  getSelf scimUser `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"locale" App Value -> Value -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` Value
localeBefore

  -- control: the same request is fine for a wire-managed team member
  putSelfLocale wireUser "de" >>= assertStatus 200

-- | @userIdentity@ (the email part) is SCIM-managed, so the user may not change it herself.
testScimManagedEmailIsLockedForUser :: (HasCallStack) => App ()
testScimManagedEmailIsLockedForUser :: HasCallStack => App ()
testScimManagedEmailIsLockedForUser = do
  (_owner, scimUser, _wireUser) <- App (Value, Value, Value)
HasCallStack => App (Value, Value, Value)
setupScimTeam
  emailBefore <- scimUser %. "email" >>= asString
  (cookie, token) <- loginWithCookieAndToken OwnDomain emailBefore defPassword

  newEmail <- randomEmail
  updateEmail scimUser newEmail cookie token `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
403
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"label" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"managed-by-scim"
  getSelf scimUser `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"email" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
emailBefore
    Maybe Value -> String -> App (Maybe Value)
forall a.
(HasCallStack, MakesValue a) =>
a -> String -> App (Maybe Value)
lookupField Response
resp.json String
"email_unvalidated" App (Maybe Value) -> Maybe Value -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` (Maybe Value
forall a. Maybe a
Nothing :: Maybe Value)

-- | Removing a SCIM-managed email must be rejected without changing the identity.
testScimManagedEmailCannotBeRemoved :: (HasCallStack) => App ()
testScimManagedEmailCannotBeRemoved :: HasCallStack => App ()
testScimManagedEmailCannotBeRemoved = do
  (_owner, scimUser, _wireUser) <- App (Value, Value, Value)
HasCallStack => App (Value, Value, Value)
setupScimTeam
  emailBefore <- scimUser %. "email"

  deleteSelfEmail scimUser `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
403
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"label" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"managed-by-scim"
  getSelf scimUser `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"email" App Value -> Value -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` Value
emailBefore

-- | ... and neither may a team admin, who can change the email address of any other
-- wire-managed member of her team (@PUT \/users\/:uid\/email@).
testScimManagedEmailIsLockedForTeamAdmin :: (HasCallStack) => App ()
testScimManagedEmailIsLockedForTeamAdmin :: HasCallStack => App ()
testScimManagedEmailIsLockedForTeamAdmin = do
  (owner, scimUser, wireUser) <- App (Value, Value, Value)
HasCallStack => App (Value, Value, Value)
setupScimTeam
  emailBefore <- scimUser %. "email"

  newEmail <- randomEmail
  putUserEmail owner scimUser newEmail `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
403
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"label" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"managed-by-scim"
  getSelf scimUser `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"email" App Value -> Value -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` Value
emailBefore
    Maybe Value -> String -> App (Maybe Value)
forall a.
(HasCallStack, MakesValue a) =>
a -> String -> App (Maybe Value)
lookupField Response
resp.json String
"email_unvalidated" App (Maybe Value) -> Maybe Value -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` (Maybe Value
forall a. Maybe a
Nothing :: Maybe Value)

  -- control: the same request is fine for a wire-managed team member
  otherEmail <- randomEmail
  putUserEmail owner wireUser otherEmail >>= assertStatus 200

-- | A team owner must not overwrite a SCIM-provisioned role.
testScimManagedRoleIsLockedForTeamAdmin :: (HasCallStack) => App ()
testScimManagedRoleIsLockedForTeamAdmin :: HasCallStack => App ()
testScimManagedRoleIsLockedForTeamAdmin = do
  (owner, scimUser, wireUser) <- App (Value, Value, Value)
HasCallStack => App (Value, Value, Value)
setupScimTeam
  tid <- scimUser %. "team" >>= asString
  uid <- scimUser %. "id" >>= asString
  before <- Galley.getTeamMember owner tid uid >>= getJSON 200 >>= (%. "permissions")
  Galley.updateTeamMember tid owner scimUser Galley.Admin `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
403
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"label" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"managed-by-scim"
  after <- Galley.getTeamMember owner tid uid >>= getJSON 200 >>= (%. "permissions")
  after `shouldMatch` before
  Galley.updateTeamMember tid owner wireUser Galley.Admin >>= assertSuccess

-- | Missing or empty roles on creation default to member; empty roles on update
-- preserve the existing role rather than leaving the user without one.
testScimUserAlwaysHasRole :: (HasCallStack) => App ()
testScimUserAlwaysHasRole :: HasCallStack => App ()
testScimUserAlwaysHasRole = do
  (owner, tid, _) <- Domain -> Int -> App (Value, String, [Value])
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> Int -> App (Value, String, [Value])
createTeam Domain
OwnDomain Int
1
  tok <- createScimToken owner def >>= getJSON 200 >>= (%. "token") >>= asString
  let assertRole :: (HasCallStack) => String -> String -> App ()
      assertRole String
uid String
expected = do
        stored <- Domain -> String -> String -> App Response
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> String -> String -> App Response
getScimUser Domain
OwnDomain String
tok String
uid App Response -> (Response -> App Value) -> App Value
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= HasCallStack => Int -> Response -> App Value
Int -> Response -> App Value
getJSON Int
200
        role <- stored %. "roles" >>= asList >>= assertOne
        role %. "value" `shouldMatch` expected

  forM_ [False, True] $ \Bool
explicitEmptyRoles -> do
    -- creating new user without role gives it the default role.
    user <- App Value
randomScimUser
    withoutRoles <-
      if explicitEmptyRoles
        then setField "roles" ([] :: [Value]) user
        else removeField "roles" user
    created <- createScimUser OwnDomain tok withoutRoles >>= getJSON 201
    uid <- created %. "id" >>= asString
    assertRole uid "member"
    -- Accept the invitation so role updates operate on an actual team member,
    -- rather than reading back the default role for a pending invitation.
    email <- user %. "emails" >>= asList >>= assertOne >>= (%. "value") >>= asString
    registerInvitedUser OwnDomain tid email

    -- Setting roles to '[]' explicitly in an update preserves the existing role.
    admin <- setField "roles" [object ["value" .= ("admin" :: String)]] created
    updateScimUser OwnDomain tok uid admin >>= assertStatus 200
    assertRole uid "admin"
    before <- Galley.getTeamMember owner tid uid >>= getJSON 200 >>= (%. "permissions")
    emptyRoles <- setField "roles" ([] :: [Value]) admin
    updateScimUser OwnDomain tok uid emptyRoles >>= assertStatus 200
    assertRole uid "admin"
    after <- Galley.getTeamMember owner tid uid >>= getJSON 200 >>= (%. "permissions")
    after `shouldMatch` before

-- | Role changes must also apply before the SCIM invitation is accepted.
testScimInvitationRoleCanBeUpdated :: (HasCallStack) => App ()
testScimInvitationRoleCanBeUpdated :: HasCallStack => App ()
testScimInvitationRoleCanBeUpdated = do
  (owner, tid, _) <- Domain -> Int -> App (Value, String, [Value])
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> Int -> App (Value, String, [Value])
createTeam Domain
OwnDomain Int
1
  tok <- createScimToken owner def >>= getJSON 200 >>= (%. "token") >>= asString
  let assertRole :: (HasCallStack) => String -> String -> App ()
      assertRole String
uid String
expected = do
        stored <- Domain -> String -> String -> App Response
forall domain.
(HasCallStack, MakesValue domain) =>
domain -> String -> String -> App Response
getScimUser Domain
OwnDomain String
tok String
uid App Response -> (Response -> App Value) -> App Value
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= HasCallStack => Int -> Response -> App Value
Int -> Response -> App Value
getJSON Int
200
        role <- stored %. "roles" >>= asList >>= assertOne
        role %. "value" `shouldMatch` expected

  user <- randomScimUser >>= setField "roles" [object ["value" .= ("admin" :: String)]]
  created <- createScimUser OwnDomain tok user >>= getJSON 201
  uid <- created %. "id" >>= asString
  assertRole uid "admin"
  forM_ ["member", "admin"] $ \String
role -> do
    updated <- String -> [Value] -> Value -> App Value
forall a b.
(HasCallStack, MakesValue a, ToJSON b) =>
String -> b -> a -> App Value
setField String
"roles" [[Pair] -> Value
object [String
"value" String -> String -> Pair
forall a. ToJSON a => String -> a -> Pair
.= (String
role :: String)]] Value
created
    updateScimUser OwnDomain tok uid updated >>= assertStatus 200
    assertRole uid role
  emptyRoles <- setField "roles" ([] :: [Value]) created
  updateScimUser OwnDomain tok uid emptyRoles >>= assertStatus 200
  assertRole uid "admin"

  email <- user %. "emails" >>= asList >>= assertOne >>= (%. "value") >>= asString
  registerInvitedUser OwnDomain tid email
  -- This read now derives the role from Galley, not the pending invitation.
  assertRole uid "admin"

-- | Unlike the user attributes above, a SCIM-provisioned /group/ is not write-protected:
-- a team admin may rename it, change its membership and delete it through the public API.
testScimGroupIsWritableByTeamAdmin :: (HasCallStack) => App ()
testScimGroupIsWritableByTeamAdmin :: HasCallStack => App ()
testScimGroupIsWritableByTeamAdmin = do
  (owner, scimUser, wireUser) <- App (Value, Value, Value)
HasCallStack => App (Value, Value, Value)
setupScimTeam
  tok <- createScimToken owner def >>= getJSON 200 >>= (%. "token") >>= asString
  uid <- scimUser %. "id" >>= asString
  other <- wireUser %. "id" >>= asString
  let newScimGroup =
        Domain -> String -> Value -> App Response
forall domain scimUser.
(HasCallStack, MakesValue domain, MakesValue scimUser) =>
domain -> String -> scimUser -> App Response
createScimUserGroup Domain
OwnDomain String
tok (String -> [Value] -> Value
mkScimGroup String
"original" [String -> Value
mkScimUser String
uid])
          App Response -> (Response -> App Value) -> App Value
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= HasCallStack => Int -> Response -> App Value
Int -> Response -> App Value
getJSON Int
201
          App Value -> (Value -> App Value) -> App Value
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"id")
          App Value -> (Value -> App String) -> App String
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App String
forall a. (HasCallStack, MakesValue a) => a -> App String
asString

  gid <- newScimGroup
  updateUserGroup owner gid (object ["name" .= ("changed" :: String)]) >>= assertSuccess
  addUserToGroup owner gid other >>= assertSuccess
  removeUserFromGroup owner gid other >>= assertSuccess
  addUsersToGroup owner gid [other] >>= assertSuccess
  updateUserGroupUsers owner gid [other] >>= assertSuccess
  getScimUserGroup OwnDomain tok gid `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"displayName" App Value -> String -> App ()
forall a b.
(MakesValue a, MakesValue b, HasCallStack) =>
a -> b -> App ()
`shouldMatch` String
"changed"
    members <- Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"members" App Value -> (Value -> App [Value]) -> App [Value]
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Value -> App [Value]
forall a. (HasCallStack, MakesValue a) => a -> App [Value]
asList App [Value] -> ([Value] -> App [Value]) -> App [Value]
forall a b. App a -> (a -> App b) -> App b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (Value -> App Value) -> [Value] -> App [Value]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"value")
    members `shouldMatch` [other]

  deleteUserGroup owner gid >>= assertSuccess
  getScimUserGroup OwnDomain tok gid >>= assertStatus 404

-- | Non-provisioned profile fields must not acquire a blanket SCIM lock.
testNonScimManagedFieldsStayWritable :: (HasCallStack) => App ()
testNonScimManagedFieldsStayWritable :: HasCallStack => App ()
testNonScimManagedFieldsStayWritable = do
  (_owner, scimUser, _wireUser) <- App (Value, Value, Value)
HasCallStack => App (Value, Value, Value)
setupScimTeam
  putSelf scimUser def {accent = Just 5} >>= assertStatus 200
  getSelf scimUser `bindResponse` \Response
resp -> do
    Response
resp.status Int -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
200
    Response
resp.json Maybe Value -> String -> App Value
forall a. (HasCallStack, MakesValue a) => a -> String -> App Value
%. String
"accent_id" App Value -> Int -> App ()
forall a. (MakesValue a, HasCallStack) => a -> Int -> App ()
`shouldMatchInt` Int
5