test_user.py 161 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528
  1. # Copyright 2018-2022 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import hashlib
  15. import hmac
  16. import os
  17. import urllib.parse
  18. from binascii import unhexlify
  19. from typing import List, Optional
  20. from unittest.mock import Mock, patch
  21. from parameterized import parameterized, parameterized_class
  22. from twisted.test.proto_helpers import MemoryReactor
  23. import synapse.rest.admin
  24. from synapse.api.constants import ApprovalNoticeMedium, LoginType, UserTypes
  25. from synapse.api.errors import Codes, HttpResponseException, ResourceLimitError
  26. from synapse.api.room_versions import RoomVersions
  27. from synapse.media.filepath import MediaFilePaths
  28. from synapse.rest.client import devices, login, logout, profile, register, room, sync
  29. from synapse.server import HomeServer
  30. from synapse.types import JsonDict, UserID, create_requester
  31. from synapse.util import Clock
  32. from tests import unittest
  33. from tests.server import FakeSite, make_request
  34. from tests.test_utils import SMALL_PNG, make_awaitable
  35. from tests.unittest import override_config
  36. class UserRegisterTestCase(unittest.HomeserverTestCase):
  37. servlets = [
  38. synapse.rest.admin.register_servlets_for_client_rest_resource,
  39. profile.register_servlets,
  40. ]
  41. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  42. self.url = "/_synapse/admin/v1/register"
  43. self.registration_handler = Mock()
  44. self.identity_handler = Mock()
  45. self.login_handler = Mock()
  46. self.device_handler = Mock()
  47. self.device_handler.check_device_registered = Mock(return_value="FAKE")
  48. self.datastore = Mock(return_value=Mock())
  49. self.datastore.get_current_state_deltas = Mock(return_value=(0, []))
  50. self.hs = self.setup_test_homeserver()
  51. self.hs.config.registration.registration_shared_secret = "shared"
  52. self.hs.get_media_repository = Mock() # type: ignore[assignment]
  53. self.hs.get_deactivate_account_handler = Mock() # type: ignore[assignment]
  54. return self.hs
  55. def test_disabled(self) -> None:
  56. """
  57. If there is no shared secret, registration through this method will be
  58. prevented.
  59. """
  60. self.hs.config.registration.registration_shared_secret = None
  61. channel = self.make_request("POST", self.url, b"{}")
  62. self.assertEqual(400, channel.code, msg=channel.json_body)
  63. self.assertEqual(
  64. "Shared secret registration is not enabled", channel.json_body["error"]
  65. )
  66. def test_get_nonce(self) -> None:
  67. """
  68. Calling GET on the endpoint will return a randomised nonce, using the
  69. homeserver's secrets provider.
  70. """
  71. with patch("secrets.token_hex") as token_hex:
  72. # Patch secrets.token_hex for the duration of this context
  73. token_hex.return_value = "abcd"
  74. channel = self.make_request("GET", self.url)
  75. self.assertEqual(channel.json_body, {"nonce": "abcd"})
  76. def test_expired_nonce(self) -> None:
  77. """
  78. Calling GET on the endpoint will return a randomised nonce, which will
  79. only last for SALT_TIMEOUT (60s).
  80. """
  81. channel = self.make_request("GET", self.url)
  82. nonce = channel.json_body["nonce"]
  83. # 59 seconds
  84. self.reactor.advance(59)
  85. body = {"nonce": nonce}
  86. channel = self.make_request("POST", self.url, body)
  87. self.assertEqual(400, channel.code, msg=channel.json_body)
  88. self.assertEqual("username must be specified", channel.json_body["error"])
  89. # 61 seconds
  90. self.reactor.advance(2)
  91. channel = self.make_request("POST", self.url, body)
  92. self.assertEqual(400, channel.code, msg=channel.json_body)
  93. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  94. def test_register_incorrect_nonce(self) -> None:
  95. """
  96. Only the provided nonce can be used, as it's checked in the MAC.
  97. """
  98. channel = self.make_request("GET", self.url)
  99. nonce = channel.json_body["nonce"]
  100. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  101. want_mac.update(b"notthenonce\x00bob\x00abc123\x00admin")
  102. want_mac_str = want_mac.hexdigest()
  103. body = {
  104. "nonce": nonce,
  105. "username": "bob",
  106. "password": "abc123",
  107. "admin": True,
  108. "mac": want_mac_str,
  109. }
  110. channel = self.make_request("POST", self.url, body)
  111. self.assertEqual(403, channel.code, msg=channel.json_body)
  112. self.assertEqual("HMAC incorrect", channel.json_body["error"])
  113. def test_register_correct_nonce(self) -> None:
  114. """
  115. When the correct nonce is provided, and the right key is provided, the
  116. user is registered.
  117. """
  118. channel = self.make_request("GET", self.url)
  119. nonce = channel.json_body["nonce"]
  120. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  121. want_mac.update(
  122. nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin\x00support"
  123. )
  124. want_mac_str = want_mac.hexdigest()
  125. body = {
  126. "nonce": nonce,
  127. "username": "bob",
  128. "password": "abc123",
  129. "admin": True,
  130. "user_type": UserTypes.SUPPORT,
  131. "mac": want_mac_str,
  132. }
  133. channel = self.make_request("POST", self.url, body)
  134. self.assertEqual(200, channel.code, msg=channel.json_body)
  135. self.assertEqual("@bob:test", channel.json_body["user_id"])
  136. def test_nonce_reuse(self) -> None:
  137. """
  138. A valid unrecognised nonce.
  139. """
  140. channel = self.make_request("GET", self.url)
  141. nonce = channel.json_body["nonce"]
  142. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  143. want_mac.update(nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin")
  144. want_mac_str = want_mac.hexdigest()
  145. body = {
  146. "nonce": nonce,
  147. "username": "bob",
  148. "password": "abc123",
  149. "admin": True,
  150. "mac": want_mac_str,
  151. }
  152. channel = self.make_request("POST", self.url, body)
  153. self.assertEqual(200, channel.code, msg=channel.json_body)
  154. self.assertEqual("@bob:test", channel.json_body["user_id"])
  155. # Now, try and reuse it
  156. channel = self.make_request("POST", self.url, body)
  157. self.assertEqual(400, channel.code, msg=channel.json_body)
  158. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  159. def test_missing_parts(self) -> None:
  160. """
  161. Synapse will complain if you don't give nonce, username, password, and
  162. mac. Admin and user_types are optional. Additional checks are done for length
  163. and type.
  164. """
  165. def nonce() -> str:
  166. channel = self.make_request("GET", self.url)
  167. return channel.json_body["nonce"]
  168. #
  169. # Nonce check
  170. #
  171. # Must be an empty body present
  172. channel = self.make_request("POST", self.url, {})
  173. self.assertEqual(400, channel.code, msg=channel.json_body)
  174. self.assertEqual("nonce must be specified", channel.json_body["error"])
  175. #
  176. # Username checks
  177. #
  178. # Must be present
  179. channel = self.make_request("POST", self.url, {"nonce": nonce()})
  180. self.assertEqual(400, channel.code, msg=channel.json_body)
  181. self.assertEqual("username must be specified", channel.json_body["error"])
  182. # Must be a string
  183. body = {"nonce": nonce(), "username": 1234}
  184. channel = self.make_request("POST", self.url, body)
  185. self.assertEqual(400, channel.code, msg=channel.json_body)
  186. self.assertEqual("Invalid username", channel.json_body["error"])
  187. # Must not have null bytes
  188. body = {"nonce": nonce(), "username": "abcd\u0000"}
  189. channel = self.make_request("POST", self.url, body)
  190. self.assertEqual(400, channel.code, msg=channel.json_body)
  191. self.assertEqual("Invalid username", channel.json_body["error"])
  192. # Must not have null bytes
  193. body = {"nonce": nonce(), "username": "a" * 1000}
  194. channel = self.make_request("POST", self.url, body)
  195. self.assertEqual(400, channel.code, msg=channel.json_body)
  196. self.assertEqual("Invalid username", channel.json_body["error"])
  197. #
  198. # Password checks
  199. #
  200. # Must be present
  201. body = {"nonce": nonce(), "username": "a"}
  202. channel = self.make_request("POST", self.url, body)
  203. self.assertEqual(400, channel.code, msg=channel.json_body)
  204. self.assertEqual("password must be specified", channel.json_body["error"])
  205. # Must be a string
  206. body = {"nonce": nonce(), "username": "a", "password": 1234}
  207. channel = self.make_request("POST", self.url, body)
  208. self.assertEqual(400, channel.code, msg=channel.json_body)
  209. self.assertEqual("Invalid password", channel.json_body["error"])
  210. # Must not have null bytes
  211. body = {"nonce": nonce(), "username": "a", "password": "abcd\u0000"}
  212. channel = self.make_request("POST", self.url, body)
  213. self.assertEqual(400, channel.code, msg=channel.json_body)
  214. self.assertEqual("Invalid password", channel.json_body["error"])
  215. # Super long
  216. body = {"nonce": nonce(), "username": "a", "password": "A" * 1000}
  217. channel = self.make_request("POST", self.url, body)
  218. self.assertEqual(400, channel.code, msg=channel.json_body)
  219. self.assertEqual("Invalid password", channel.json_body["error"])
  220. #
  221. # user_type check
  222. #
  223. # Invalid user_type
  224. body = {
  225. "nonce": nonce(),
  226. "username": "a",
  227. "password": "1234",
  228. "user_type": "invalid",
  229. }
  230. channel = self.make_request("POST", self.url, body)
  231. self.assertEqual(400, channel.code, msg=channel.json_body)
  232. self.assertEqual("Invalid user type", channel.json_body["error"])
  233. def test_displayname(self) -> None:
  234. """
  235. Test that displayname of new user is set
  236. """
  237. # set no displayname
  238. channel = self.make_request("GET", self.url)
  239. nonce = channel.json_body["nonce"]
  240. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  241. want_mac.update(nonce.encode("ascii") + b"\x00bob1\x00abc123\x00notadmin")
  242. want_mac_str = want_mac.hexdigest()
  243. body = {
  244. "nonce": nonce,
  245. "username": "bob1",
  246. "password": "abc123",
  247. "mac": want_mac_str,
  248. }
  249. channel = self.make_request("POST", self.url, body)
  250. self.assertEqual(200, channel.code, msg=channel.json_body)
  251. self.assertEqual("@bob1:test", channel.json_body["user_id"])
  252. channel = self.make_request("GET", "/profile/@bob1:test/displayname")
  253. self.assertEqual(200, channel.code, msg=channel.json_body)
  254. self.assertEqual("bob1", channel.json_body["displayname"])
  255. # displayname is None
  256. channel = self.make_request("GET", self.url)
  257. nonce = channel.json_body["nonce"]
  258. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  259. want_mac.update(nonce.encode("ascii") + b"\x00bob2\x00abc123\x00notadmin")
  260. want_mac_str = want_mac.hexdigest()
  261. body = {
  262. "nonce": nonce,
  263. "username": "bob2",
  264. "displayname": None,
  265. "password": "abc123",
  266. "mac": want_mac_str,
  267. }
  268. channel = self.make_request("POST", self.url, body)
  269. self.assertEqual(200, channel.code, msg=channel.json_body)
  270. self.assertEqual("@bob2:test", channel.json_body["user_id"])
  271. channel = self.make_request("GET", "/profile/@bob2:test/displayname")
  272. self.assertEqual(200, channel.code, msg=channel.json_body)
  273. self.assertEqual("bob2", channel.json_body["displayname"])
  274. # displayname is empty
  275. channel = self.make_request("GET", self.url)
  276. nonce = channel.json_body["nonce"]
  277. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  278. want_mac.update(nonce.encode("ascii") + b"\x00bob3\x00abc123\x00notadmin")
  279. want_mac_str = want_mac.hexdigest()
  280. body = {
  281. "nonce": nonce,
  282. "username": "bob3",
  283. "displayname": "",
  284. "password": "abc123",
  285. "mac": want_mac_str,
  286. }
  287. channel = self.make_request("POST", self.url, body)
  288. self.assertEqual(200, channel.code, msg=channel.json_body)
  289. self.assertEqual("@bob3:test", channel.json_body["user_id"])
  290. channel = self.make_request("GET", "/profile/@bob3:test/displayname")
  291. self.assertEqual(404, channel.code, msg=channel.json_body)
  292. # set displayname
  293. channel = self.make_request("GET", self.url)
  294. nonce = channel.json_body["nonce"]
  295. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  296. want_mac.update(nonce.encode("ascii") + b"\x00bob4\x00abc123\x00notadmin")
  297. want_mac_str = want_mac.hexdigest()
  298. body = {
  299. "nonce": nonce,
  300. "username": "bob4",
  301. "displayname": "Bob's Name",
  302. "password": "abc123",
  303. "mac": want_mac_str,
  304. }
  305. channel = self.make_request("POST", self.url, body)
  306. self.assertEqual(200, channel.code, msg=channel.json_body)
  307. self.assertEqual("@bob4:test", channel.json_body["user_id"])
  308. channel = self.make_request("GET", "/profile/@bob4:test/displayname")
  309. self.assertEqual(200, channel.code, msg=channel.json_body)
  310. self.assertEqual("Bob's Name", channel.json_body["displayname"])
  311. @override_config(
  312. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  313. )
  314. def test_register_mau_limit_reached(self) -> None:
  315. """
  316. Check we can register a user via the shared secret registration API
  317. even if the MAU limit is reached.
  318. """
  319. handler = self.hs.get_registration_handler()
  320. store = self.hs.get_datastores().main
  321. # Set monthly active users to the limit
  322. store.get_monthly_active_count = Mock(
  323. return_value=make_awaitable(self.hs.config.server.max_mau_value)
  324. )
  325. # Check that the blocking of monthly active users is working as expected
  326. # The registration of a new user fails due to the limit
  327. self.get_failure(
  328. handler.register_user(localpart="local_part"), ResourceLimitError
  329. )
  330. # Register new user with admin API
  331. channel = self.make_request("GET", self.url)
  332. nonce = channel.json_body["nonce"]
  333. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  334. want_mac.update(
  335. nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin\x00support"
  336. )
  337. want_mac_str = want_mac.hexdigest()
  338. body = {
  339. "nonce": nonce,
  340. "username": "bob",
  341. "password": "abc123",
  342. "admin": True,
  343. "user_type": UserTypes.SUPPORT,
  344. "mac": want_mac_str,
  345. }
  346. channel = self.make_request("POST", self.url, body)
  347. self.assertEqual(200, channel.code, msg=channel.json_body)
  348. self.assertEqual("@bob:test", channel.json_body["user_id"])
  349. class UsersListTestCase(unittest.HomeserverTestCase):
  350. servlets = [
  351. synapse.rest.admin.register_servlets,
  352. login.register_servlets,
  353. ]
  354. url = "/_synapse/admin/v2/users"
  355. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  356. self.store = hs.get_datastores().main
  357. self.admin_user = self.register_user("admin", "pass", admin=True)
  358. self.admin_user_tok = self.login("admin", "pass")
  359. def test_no_auth(self) -> None:
  360. """
  361. Try to list users without authentication.
  362. """
  363. channel = self.make_request("GET", self.url, b"{}")
  364. self.assertEqual(401, channel.code, msg=channel.json_body)
  365. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  366. def test_requester_is_no_admin(self) -> None:
  367. """
  368. If the user is not a server admin, an error is returned.
  369. """
  370. self._create_users(1)
  371. other_user_token = self.login("user1", "pass1")
  372. channel = self.make_request("GET", self.url, access_token=other_user_token)
  373. self.assertEqual(403, channel.code, msg=channel.json_body)
  374. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  375. def test_all_users(self) -> None:
  376. """
  377. List all users, including deactivated users.
  378. """
  379. self._create_users(2)
  380. channel = self.make_request(
  381. "GET",
  382. self.url + "?deactivated=true",
  383. {},
  384. access_token=self.admin_user_tok,
  385. )
  386. self.assertEqual(200, channel.code, msg=channel.json_body)
  387. self.assertEqual(3, len(channel.json_body["users"]))
  388. self.assertEqual(3, channel.json_body["total"])
  389. # Check that all fields are available
  390. self._check_fields(channel.json_body["users"])
  391. def test_search_term(self) -> None:
  392. """Test that searching for a users works correctly"""
  393. def _search_test(
  394. expected_user_id: Optional[str],
  395. search_term: str,
  396. search_field: Optional[str] = "name",
  397. expected_http_code: Optional[int] = 200,
  398. ) -> None:
  399. """Search for a user and check that the returned user's id is a match
  400. Args:
  401. expected_user_id: The user_id expected to be returned by the API. Set
  402. to None to expect zero results for the search
  403. search_term: The term to search for user names with
  404. search_field: Field which is to request: `name` or `user_id`
  405. expected_http_code: The expected http code for the request
  406. """
  407. url = self.url + "?%s=%s" % (
  408. search_field,
  409. search_term,
  410. )
  411. channel = self.make_request(
  412. "GET",
  413. url,
  414. access_token=self.admin_user_tok,
  415. )
  416. self.assertEqual(expected_http_code, channel.code, msg=channel.json_body)
  417. if expected_http_code != 200:
  418. return
  419. # Check that users were returned
  420. self.assertTrue("users" in channel.json_body)
  421. self._check_fields(channel.json_body["users"])
  422. users = channel.json_body["users"]
  423. # Check that the expected number of users were returned
  424. expected_user_count = 1 if expected_user_id else 0
  425. self.assertEqual(len(users), expected_user_count)
  426. self.assertEqual(channel.json_body["total"], expected_user_count)
  427. if expected_user_id:
  428. # Check that the first returned user id is correct
  429. u = users[0]
  430. self.assertEqual(expected_user_id, u["name"])
  431. self._create_users(2)
  432. user1 = "@user1:test"
  433. user2 = "@user2:test"
  434. # Perform search tests
  435. _search_test(user1, "er1")
  436. _search_test(user1, "me 1")
  437. _search_test(user2, "er2")
  438. _search_test(user2, "me 2")
  439. _search_test(user1, "er1", "user_id")
  440. _search_test(user2, "er2", "user_id")
  441. # Test case insensitive
  442. _search_test(user1, "ER1")
  443. _search_test(user1, "NAME 1")
  444. _search_test(user2, "ER2")
  445. _search_test(user2, "NAME 2")
  446. _search_test(user1, "ER1", "user_id")
  447. _search_test(user2, "ER2", "user_id")
  448. _search_test(None, "foo")
  449. _search_test(None, "bar")
  450. _search_test(None, "foo", "user_id")
  451. _search_test(None, "bar", "user_id")
  452. @override_config(
  453. {
  454. "experimental_features": {
  455. "msc3866": {
  456. "enabled": True,
  457. "require_approval_for_new_accounts": True,
  458. }
  459. }
  460. }
  461. )
  462. def test_invalid_parameter(self) -> None:
  463. """
  464. If parameters are invalid, an error is returned.
  465. """
  466. # negative limit
  467. channel = self.make_request(
  468. "GET",
  469. self.url + "?limit=-5",
  470. access_token=self.admin_user_tok,
  471. )
  472. self.assertEqual(400, channel.code, msg=channel.json_body)
  473. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  474. # negative from
  475. channel = self.make_request(
  476. "GET",
  477. self.url + "?from=-5",
  478. access_token=self.admin_user_tok,
  479. )
  480. self.assertEqual(400, channel.code, msg=channel.json_body)
  481. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  482. # invalid guests
  483. channel = self.make_request(
  484. "GET",
  485. self.url + "?guests=not_bool",
  486. access_token=self.admin_user_tok,
  487. )
  488. self.assertEqual(400, channel.code, msg=channel.json_body)
  489. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  490. # invalid deactivated
  491. channel = self.make_request(
  492. "GET",
  493. self.url + "?deactivated=not_bool",
  494. access_token=self.admin_user_tok,
  495. )
  496. self.assertEqual(400, channel.code, msg=channel.json_body)
  497. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  498. # invalid approved
  499. channel = self.make_request(
  500. "GET",
  501. self.url + "?approved=not_bool",
  502. access_token=self.admin_user_tok,
  503. )
  504. self.assertEqual(400, channel.code, msg=channel.json_body)
  505. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  506. # unkown order_by
  507. channel = self.make_request(
  508. "GET",
  509. self.url + "?order_by=bar",
  510. access_token=self.admin_user_tok,
  511. )
  512. self.assertEqual(400, channel.code, msg=channel.json_body)
  513. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  514. # invalid search order
  515. channel = self.make_request(
  516. "GET",
  517. self.url + "?dir=bar",
  518. access_token=self.admin_user_tok,
  519. )
  520. self.assertEqual(400, channel.code, msg=channel.json_body)
  521. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  522. def test_limit(self) -> None:
  523. """
  524. Testing list of users with limit
  525. """
  526. number_users = 20
  527. # Create one less user (since there's already an admin user).
  528. self._create_users(number_users - 1)
  529. channel = self.make_request(
  530. "GET",
  531. self.url + "?limit=5",
  532. access_token=self.admin_user_tok,
  533. )
  534. self.assertEqual(200, channel.code, msg=channel.json_body)
  535. self.assertEqual(channel.json_body["total"], number_users)
  536. self.assertEqual(len(channel.json_body["users"]), 5)
  537. self.assertEqual(channel.json_body["next_token"], "5")
  538. self._check_fields(channel.json_body["users"])
  539. def test_from(self) -> None:
  540. """
  541. Testing list of users with a defined starting point (from)
  542. """
  543. number_users = 20
  544. # Create one less user (since there's already an admin user).
  545. self._create_users(number_users - 1)
  546. channel = self.make_request(
  547. "GET",
  548. self.url + "?from=5",
  549. access_token=self.admin_user_tok,
  550. )
  551. self.assertEqual(200, channel.code, msg=channel.json_body)
  552. self.assertEqual(channel.json_body["total"], number_users)
  553. self.assertEqual(len(channel.json_body["users"]), 15)
  554. self.assertNotIn("next_token", channel.json_body)
  555. self._check_fields(channel.json_body["users"])
  556. def test_limit_and_from(self) -> None:
  557. """
  558. Testing list of users with a defined starting point and limit
  559. """
  560. number_users = 20
  561. # Create one less user (since there's already an admin user).
  562. self._create_users(number_users - 1)
  563. channel = self.make_request(
  564. "GET",
  565. self.url + "?from=5&limit=10",
  566. access_token=self.admin_user_tok,
  567. )
  568. self.assertEqual(200, channel.code, msg=channel.json_body)
  569. self.assertEqual(channel.json_body["total"], number_users)
  570. self.assertEqual(channel.json_body["next_token"], "15")
  571. self.assertEqual(len(channel.json_body["users"]), 10)
  572. self._check_fields(channel.json_body["users"])
  573. def test_next_token(self) -> None:
  574. """
  575. Testing that `next_token` appears at the right place
  576. """
  577. number_users = 20
  578. # Create one less user (since there's already an admin user).
  579. self._create_users(number_users - 1)
  580. # `next_token` does not appear
  581. # Number of results is the number of entries
  582. channel = self.make_request(
  583. "GET",
  584. self.url + "?limit=20",
  585. access_token=self.admin_user_tok,
  586. )
  587. self.assertEqual(200, channel.code, msg=channel.json_body)
  588. self.assertEqual(channel.json_body["total"], number_users)
  589. self.assertEqual(len(channel.json_body["users"]), number_users)
  590. self.assertNotIn("next_token", channel.json_body)
  591. # `next_token` does not appear
  592. # Number of max results is larger than the number of entries
  593. channel = self.make_request(
  594. "GET",
  595. self.url + "?limit=21",
  596. access_token=self.admin_user_tok,
  597. )
  598. self.assertEqual(200, channel.code, msg=channel.json_body)
  599. self.assertEqual(channel.json_body["total"], number_users)
  600. self.assertEqual(len(channel.json_body["users"]), number_users)
  601. self.assertNotIn("next_token", channel.json_body)
  602. # `next_token` does appear
  603. # Number of max results is smaller than the number of entries
  604. channel = self.make_request(
  605. "GET",
  606. self.url + "?limit=19",
  607. access_token=self.admin_user_tok,
  608. )
  609. self.assertEqual(200, channel.code, msg=channel.json_body)
  610. self.assertEqual(channel.json_body["total"], number_users)
  611. self.assertEqual(len(channel.json_body["users"]), 19)
  612. self.assertEqual(channel.json_body["next_token"], "19")
  613. # Check
  614. # Set `from` to value of `next_token` for request remaining entries
  615. # `next_token` does not appear
  616. channel = self.make_request(
  617. "GET",
  618. self.url + "?from=19",
  619. access_token=self.admin_user_tok,
  620. )
  621. self.assertEqual(200, channel.code, msg=channel.json_body)
  622. self.assertEqual(channel.json_body["total"], number_users)
  623. self.assertEqual(len(channel.json_body["users"]), 1)
  624. self.assertNotIn("next_token", channel.json_body)
  625. def test_order_by(self) -> None:
  626. """
  627. Testing order list with parameter `order_by`
  628. """
  629. # make sure that the users do not have the same timestamps
  630. self.reactor.advance(10)
  631. user1 = self.register_user("user1", "pass1", admin=False, displayname="Name Z")
  632. self.reactor.advance(10)
  633. user2 = self.register_user("user2", "pass2", admin=False, displayname="Name Y")
  634. # Modify user
  635. self.get_success(self.store.set_user_deactivated_status(user1, True))
  636. self.get_success(self.store.set_shadow_banned(UserID.from_string(user1), True))
  637. # Set avatar URL to all users, that no user has a NULL value to avoid
  638. # different sort order between SQlite and PostreSQL
  639. self.get_success(self.store.set_profile_avatar_url("user1", "mxc://url3"))
  640. self.get_success(self.store.set_profile_avatar_url("user2", "mxc://url2"))
  641. self.get_success(self.store.set_profile_avatar_url("admin", "mxc://url1"))
  642. # order by default (name)
  643. self._order_test([self.admin_user, user1, user2], None)
  644. self._order_test([self.admin_user, user1, user2], None, "f")
  645. self._order_test([user2, user1, self.admin_user], None, "b")
  646. # order by name
  647. self._order_test([self.admin_user, user1, user2], "name")
  648. self._order_test([self.admin_user, user1, user2], "name", "f")
  649. self._order_test([user2, user1, self.admin_user], "name", "b")
  650. # order by displayname
  651. self._order_test([user2, user1, self.admin_user], "displayname")
  652. self._order_test([user2, user1, self.admin_user], "displayname", "f")
  653. self._order_test([self.admin_user, user1, user2], "displayname", "b")
  654. # order by is_guest
  655. # like sort by ascending name, as no guest user here
  656. self._order_test([self.admin_user, user1, user2], "is_guest")
  657. self._order_test([self.admin_user, user1, user2], "is_guest", "f")
  658. self._order_test([self.admin_user, user1, user2], "is_guest", "b")
  659. # order by admin
  660. self._order_test([user1, user2, self.admin_user], "admin")
  661. self._order_test([user1, user2, self.admin_user], "admin", "f")
  662. self._order_test([self.admin_user, user1, user2], "admin", "b")
  663. # order by deactivated
  664. self._order_test([self.admin_user, user2, user1], "deactivated")
  665. self._order_test([self.admin_user, user2, user1], "deactivated", "f")
  666. self._order_test([user1, self.admin_user, user2], "deactivated", "b")
  667. # order by user_type
  668. # like sort by ascending name, as no special user type here
  669. self._order_test([self.admin_user, user1, user2], "user_type")
  670. self._order_test([self.admin_user, user1, user2], "user_type", "f")
  671. self._order_test([self.admin_user, user1, user2], "is_guest", "b")
  672. # order by shadow_banned
  673. self._order_test([self.admin_user, user2, user1], "shadow_banned")
  674. self._order_test([self.admin_user, user2, user1], "shadow_banned", "f")
  675. self._order_test([user1, self.admin_user, user2], "shadow_banned", "b")
  676. # order by avatar_url
  677. self._order_test([self.admin_user, user2, user1], "avatar_url")
  678. self._order_test([self.admin_user, user2, user1], "avatar_url", "f")
  679. self._order_test([user1, user2, self.admin_user], "avatar_url", "b")
  680. # order by creation_ts
  681. self._order_test([self.admin_user, user1, user2], "creation_ts")
  682. self._order_test([self.admin_user, user1, user2], "creation_ts", "f")
  683. self._order_test([user2, user1, self.admin_user], "creation_ts", "b")
  684. @override_config(
  685. {
  686. "experimental_features": {
  687. "msc3866": {
  688. "enabled": True,
  689. "require_approval_for_new_accounts": True,
  690. }
  691. }
  692. }
  693. )
  694. def test_filter_out_approved(self) -> None:
  695. """Tests that the endpoint can filter out approved users."""
  696. # Create our users.
  697. self._create_users(2)
  698. # Get the list of users.
  699. channel = self.make_request(
  700. "GET",
  701. self.url,
  702. access_token=self.admin_user_tok,
  703. )
  704. self.assertEqual(200, channel.code, channel.result)
  705. # Exclude the admin, because we don't want to accidentally un-approve the admin.
  706. non_admin_user_ids = [
  707. user["name"]
  708. for user in channel.json_body["users"]
  709. if user["name"] != self.admin_user
  710. ]
  711. self.assertEqual(2, len(non_admin_user_ids), non_admin_user_ids)
  712. # Select a user and un-approve them. We do this rather than the other way around
  713. # because, since these users are created by an admin, we consider them already
  714. # approved.
  715. not_approved_user = non_admin_user_ids[0]
  716. channel = self.make_request(
  717. "PUT",
  718. f"/_synapse/admin/v2/users/{not_approved_user}",
  719. {"approved": False},
  720. access_token=self.admin_user_tok,
  721. )
  722. self.assertEqual(200, channel.code, channel.result)
  723. # Now get the list of users again, this time filtering out approved users.
  724. channel = self.make_request(
  725. "GET",
  726. self.url + "?approved=false",
  727. access_token=self.admin_user_tok,
  728. )
  729. self.assertEqual(200, channel.code, channel.result)
  730. non_admin_user_ids = [
  731. user["name"]
  732. for user in channel.json_body["users"]
  733. if user["name"] != self.admin_user
  734. ]
  735. # We should only have our unapproved user now.
  736. self.assertEqual(1, len(non_admin_user_ids), non_admin_user_ids)
  737. self.assertEqual(not_approved_user, non_admin_user_ids[0])
  738. def test_erasure_status(self) -> None:
  739. # Create a new user.
  740. user_id = self.register_user("eraseme", "eraseme")
  741. # They should appear in the list users API, marked as not erased.
  742. channel = self.make_request(
  743. "GET",
  744. self.url + "?deactivated=true",
  745. access_token=self.admin_user_tok,
  746. )
  747. users = {user["name"]: user for user in channel.json_body["users"]}
  748. self.assertIs(users[user_id]["erased"], False)
  749. # Deactivate that user, requesting erasure.
  750. deactivate_account_handler = self.hs.get_deactivate_account_handler()
  751. self.get_success(
  752. deactivate_account_handler.deactivate_account(
  753. user_id, erase_data=True, requester=create_requester(user_id)
  754. )
  755. )
  756. # Repeat the list users query. They should now be marked as erased.
  757. channel = self.make_request(
  758. "GET",
  759. self.url + "?deactivated=true",
  760. access_token=self.admin_user_tok,
  761. )
  762. users = {user["name"]: user for user in channel.json_body["users"]}
  763. self.assertIs(users[user_id]["erased"], True)
  764. def _order_test(
  765. self,
  766. expected_user_list: List[str],
  767. order_by: Optional[str],
  768. dir: Optional[str] = None,
  769. ) -> None:
  770. """Request the list of users in a certain order. Assert that order is what
  771. we expect
  772. Args:
  773. expected_user_list: The list of user_id in the order we expect to get
  774. back from the server
  775. order_by: The type of ordering to give the server
  776. dir: The direction of ordering to give the server
  777. """
  778. url = self.url + "?deactivated=true&"
  779. if order_by is not None:
  780. url += "order_by=%s&" % (order_by,)
  781. if dir is not None and dir in ("b", "f"):
  782. url += "dir=%s" % (dir,)
  783. channel = self.make_request(
  784. "GET",
  785. url,
  786. access_token=self.admin_user_tok,
  787. )
  788. self.assertEqual(200, channel.code, msg=channel.json_body)
  789. self.assertEqual(channel.json_body["total"], len(expected_user_list))
  790. returned_order = [row["name"] for row in channel.json_body["users"]]
  791. self.assertEqual(expected_user_list, returned_order)
  792. self._check_fields(channel.json_body["users"])
  793. def _check_fields(self, content: List[JsonDict]) -> None:
  794. """Checks that the expected user attributes are present in content
  795. Args:
  796. content: List that is checked for content
  797. """
  798. for u in content:
  799. self.assertIn("name", u)
  800. self.assertIn("is_guest", u)
  801. self.assertIn("admin", u)
  802. self.assertIn("user_type", u)
  803. self.assertIn("deactivated", u)
  804. self.assertIn("shadow_banned", u)
  805. self.assertIn("displayname", u)
  806. self.assertIn("avatar_url", u)
  807. self.assertIn("creation_ts", u)
  808. def _create_users(self, number_users: int) -> None:
  809. """
  810. Create a number of users
  811. Args:
  812. number_users: Number of users to be created
  813. """
  814. for i in range(1, number_users + 1):
  815. self.register_user(
  816. "user%d" % i,
  817. "pass%d" % i,
  818. admin=False,
  819. displayname="Name %d" % i,
  820. )
  821. class UserDevicesTestCase(unittest.HomeserverTestCase):
  822. """
  823. Tests user device management-related Admin APIs.
  824. """
  825. servlets = [
  826. synapse.rest.admin.register_servlets,
  827. login.register_servlets,
  828. sync.register_servlets,
  829. ]
  830. def prepare(
  831. self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
  832. ) -> None:
  833. # Set up an Admin user to query the Admin API with.
  834. self.admin_user_id = self.register_user("admin", "pass", admin=True)
  835. self.admin_user_token = self.login("admin", "pass")
  836. # Set up a test user to query the devices of.
  837. self.other_user_device_id = "TESTDEVICEID"
  838. self.other_user_device_display_name = "My Test Device"
  839. self.other_user_client_ip = "1.2.3.4"
  840. self.other_user_user_agent = "EquestriaTechnology/123.0"
  841. self.other_user_id = self.register_user("user", "pass", displayname="User1")
  842. self.other_user_token = self.login(
  843. "user",
  844. "pass",
  845. device_id=self.other_user_device_id,
  846. additional_request_fields={
  847. "initial_device_display_name": self.other_user_device_display_name,
  848. },
  849. )
  850. # Have the "other user" make a request so that the "last_seen_*" fields are
  851. # populated in the tests below.
  852. channel = self.make_request(
  853. "GET",
  854. "/_matrix/client/v3/sync",
  855. access_token=self.other_user_token,
  856. client_ip=self.other_user_client_ip,
  857. custom_headers=[
  858. ("User-Agent", self.other_user_user_agent),
  859. ],
  860. )
  861. self.assertEqual(200, channel.code, msg=channel.json_body)
  862. def test_list_user_devices(self) -> None:
  863. """
  864. Tests that a user's devices and attributes are listed correctly via the Admin API.
  865. """
  866. # Request all devices of "other user"
  867. channel = self.make_request(
  868. "GET",
  869. f"/_synapse/admin/v2/users/{self.other_user_id}/devices",
  870. access_token=self.admin_user_token,
  871. )
  872. self.assertEqual(200, channel.code, msg=channel.json_body)
  873. # Double-check we got the single device expected
  874. user_devices = channel.json_body["devices"]
  875. self.assertEqual(len(user_devices), 1)
  876. self.assertEqual(channel.json_body["total"], 1)
  877. # Check that all the attributes of the device reported are as expected.
  878. self._validate_attributes_of_device_response(user_devices[0])
  879. # Request just a single device for "other user" by its ID
  880. channel = self.make_request(
  881. "GET",
  882. f"/_synapse/admin/v2/users/{self.other_user_id}/devices/"
  883. f"{self.other_user_device_id}",
  884. access_token=self.admin_user_token,
  885. )
  886. self.assertEqual(200, channel.code, msg=channel.json_body)
  887. # Check that all the attributes of the device reported are as expected.
  888. self._validate_attributes_of_device_response(channel.json_body)
  889. def _validate_attributes_of_device_response(self, response: JsonDict) -> None:
  890. # Check that all device expected attributes are present
  891. self.assertEqual(response["user_id"], self.other_user_id)
  892. self.assertEqual(response["device_id"], self.other_user_device_id)
  893. self.assertEqual(response["display_name"], self.other_user_device_display_name)
  894. self.assertEqual(response["last_seen_ip"], self.other_user_client_ip)
  895. self.assertEqual(response["last_seen_user_agent"], self.other_user_user_agent)
  896. self.assertIsInstance(response["last_seen_ts"], int)
  897. self.assertGreater(response["last_seen_ts"], 0)
  898. class DeactivateAccountTestCase(unittest.HomeserverTestCase):
  899. servlets = [
  900. synapse.rest.admin.register_servlets,
  901. login.register_servlets,
  902. ]
  903. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  904. self.store = hs.get_datastores().main
  905. self.admin_user = self.register_user("admin", "pass", admin=True)
  906. self.admin_user_tok = self.login("admin", "pass")
  907. self.other_user = self.register_user("user", "pass", displayname="User1")
  908. self.other_user_token = self.login("user", "pass")
  909. self.url_other_user = "/_synapse/admin/v2/users/%s" % urllib.parse.quote(
  910. self.other_user
  911. )
  912. self.url = "/_synapse/admin/v1/deactivate/%s" % urllib.parse.quote(
  913. self.other_user
  914. )
  915. # set attributes for user
  916. self.get_success(
  917. self.store.set_profile_avatar_url("user", "mxc://servername/mediaid")
  918. )
  919. self.get_success(
  920. self.store.user_add_threepid("@user:test", "email", "foo@bar.com", 0, 0)
  921. )
  922. def test_no_auth(self) -> None:
  923. """
  924. Try to deactivate users without authentication.
  925. """
  926. channel = self.make_request("POST", self.url, b"{}")
  927. self.assertEqual(401, channel.code, msg=channel.json_body)
  928. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  929. def test_requester_is_not_admin(self) -> None:
  930. """
  931. If the user is not a server admin, an error is returned.
  932. """
  933. url = "/_synapse/admin/v1/deactivate/@bob:test"
  934. channel = self.make_request("POST", url, access_token=self.other_user_token)
  935. self.assertEqual(403, channel.code, msg=channel.json_body)
  936. self.assertEqual("You are not a server admin", channel.json_body["error"])
  937. channel = self.make_request(
  938. "POST",
  939. url,
  940. access_token=self.other_user_token,
  941. content=b"{}",
  942. )
  943. self.assertEqual(403, channel.code, msg=channel.json_body)
  944. self.assertEqual("You are not a server admin", channel.json_body["error"])
  945. def test_user_does_not_exist(self) -> None:
  946. """
  947. Tests that deactivation for a user that does not exist returns a 404
  948. """
  949. channel = self.make_request(
  950. "POST",
  951. "/_synapse/admin/v1/deactivate/@unknown_person:test",
  952. access_token=self.admin_user_tok,
  953. )
  954. self.assertEqual(404, channel.code, msg=channel.json_body)
  955. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  956. def test_erase_is_not_bool(self) -> None:
  957. """
  958. If parameter `erase` is not boolean, return an error
  959. """
  960. channel = self.make_request(
  961. "POST",
  962. self.url,
  963. content={"erase": "False"},
  964. access_token=self.admin_user_tok,
  965. )
  966. self.assertEqual(400, channel.code, msg=channel.json_body)
  967. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  968. def test_user_is_not_local(self) -> None:
  969. """
  970. Tests that deactivation for a user that is not a local returns a 400
  971. """
  972. url = "/_synapse/admin/v1/deactivate/@unknown_person:unknown_domain"
  973. channel = self.make_request("POST", url, access_token=self.admin_user_tok)
  974. self.assertEqual(400, channel.code, msg=channel.json_body)
  975. self.assertEqual("Can only deactivate local users", channel.json_body["error"])
  976. def test_deactivate_user_erase_true(self) -> None:
  977. """
  978. Test deactivating a user and set `erase` to `true`
  979. """
  980. # Get user
  981. channel = self.make_request(
  982. "GET",
  983. self.url_other_user,
  984. access_token=self.admin_user_tok,
  985. )
  986. self.assertEqual(200, channel.code, msg=channel.json_body)
  987. self.assertEqual("@user:test", channel.json_body["name"])
  988. self.assertEqual(False, channel.json_body["deactivated"])
  989. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  990. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  991. self.assertEqual("User1", channel.json_body["displayname"])
  992. self.assertFalse(channel.json_body["erased"])
  993. # Deactivate and erase user
  994. channel = self.make_request(
  995. "POST",
  996. self.url,
  997. access_token=self.admin_user_tok,
  998. content={"erase": True},
  999. )
  1000. self.assertEqual(200, channel.code, msg=channel.json_body)
  1001. # Get user
  1002. channel = self.make_request(
  1003. "GET",
  1004. self.url_other_user,
  1005. access_token=self.admin_user_tok,
  1006. )
  1007. self.assertEqual(200, channel.code, msg=channel.json_body)
  1008. self.assertEqual("@user:test", channel.json_body["name"])
  1009. self.assertEqual(True, channel.json_body["deactivated"])
  1010. self.assertEqual(0, len(channel.json_body["threepids"]))
  1011. self.assertIsNone(channel.json_body["avatar_url"])
  1012. self.assertIsNone(channel.json_body["displayname"])
  1013. self.assertTrue(channel.json_body["erased"])
  1014. self._is_erased("@user:test", True)
  1015. @override_config({"max_avatar_size": 1234})
  1016. def test_deactivate_user_erase_true_avatar_nonnull_but_empty(self) -> None:
  1017. """Check we can erase a user whose avatar is the empty string.
  1018. Reproduces #12257.
  1019. """
  1020. # Patch `self.other_user` to have an empty string as their avatar.
  1021. self.get_success(self.store.set_profile_avatar_url("user", ""))
  1022. # Check we can still erase them.
  1023. channel = self.make_request(
  1024. "POST",
  1025. self.url,
  1026. access_token=self.admin_user_tok,
  1027. content={"erase": True},
  1028. )
  1029. self.assertEqual(200, channel.code, msg=channel.json_body)
  1030. self._is_erased("@user:test", True)
  1031. def test_deactivate_user_erase_false(self) -> None:
  1032. """
  1033. Test deactivating a user and set `erase` to `false`
  1034. """
  1035. # Get user
  1036. channel = self.make_request(
  1037. "GET",
  1038. self.url_other_user,
  1039. access_token=self.admin_user_tok,
  1040. )
  1041. self.assertEqual(200, channel.code, msg=channel.json_body)
  1042. self.assertEqual("@user:test", channel.json_body["name"])
  1043. self.assertEqual(False, channel.json_body["deactivated"])
  1044. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  1045. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1046. self.assertEqual("User1", channel.json_body["displayname"])
  1047. # Deactivate user
  1048. channel = self.make_request(
  1049. "POST",
  1050. self.url,
  1051. access_token=self.admin_user_tok,
  1052. content={"erase": False},
  1053. )
  1054. self.assertEqual(200, channel.code, msg=channel.json_body)
  1055. # Get user
  1056. channel = self.make_request(
  1057. "GET",
  1058. self.url_other_user,
  1059. access_token=self.admin_user_tok,
  1060. )
  1061. self.assertEqual(200, channel.code, msg=channel.json_body)
  1062. self.assertEqual("@user:test", channel.json_body["name"])
  1063. self.assertEqual(True, channel.json_body["deactivated"])
  1064. self.assertEqual(0, len(channel.json_body["threepids"]))
  1065. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1066. self.assertEqual("User1", channel.json_body["displayname"])
  1067. self._is_erased("@user:test", False)
  1068. def test_deactivate_user_erase_true_no_profile(self) -> None:
  1069. """
  1070. Test deactivating a user and set `erase` to `true`
  1071. if user has no profile information (stored in the database table `profiles`).
  1072. """
  1073. # Users normally have an entry in `profiles`, but occasionally they are created without one.
  1074. # To test deactivation for users without a profile, we delete the profile information for our user.
  1075. self.get_success(
  1076. self.store.db_pool.simple_delete_one(
  1077. table="profiles", keyvalues={"user_id": "user"}
  1078. )
  1079. )
  1080. # Get user
  1081. channel = self.make_request(
  1082. "GET",
  1083. self.url_other_user,
  1084. access_token=self.admin_user_tok,
  1085. )
  1086. self.assertEqual(200, channel.code, msg=channel.json_body)
  1087. self.assertEqual("@user:test", channel.json_body["name"])
  1088. self.assertEqual(False, channel.json_body["deactivated"])
  1089. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  1090. self.assertIsNone(channel.json_body["avatar_url"])
  1091. self.assertIsNone(channel.json_body["displayname"])
  1092. # Deactivate and erase user
  1093. channel = self.make_request(
  1094. "POST",
  1095. self.url,
  1096. access_token=self.admin_user_tok,
  1097. content={"erase": True},
  1098. )
  1099. self.assertEqual(200, channel.code, msg=channel.json_body)
  1100. # Get user
  1101. channel = self.make_request(
  1102. "GET",
  1103. self.url_other_user,
  1104. access_token=self.admin_user_tok,
  1105. )
  1106. self.assertEqual(200, channel.code, msg=channel.json_body)
  1107. self.assertEqual("@user:test", channel.json_body["name"])
  1108. self.assertEqual(True, channel.json_body["deactivated"])
  1109. self.assertEqual(0, len(channel.json_body["threepids"]))
  1110. self.assertIsNone(channel.json_body["avatar_url"])
  1111. self.assertIsNone(channel.json_body["displayname"])
  1112. self._is_erased("@user:test", True)
  1113. def _is_erased(self, user_id: str, expect: bool) -> None:
  1114. """Assert that the user is erased or not"""
  1115. d = self.store.is_user_erased(user_id)
  1116. if expect:
  1117. self.assertTrue(self.get_success(d))
  1118. else:
  1119. self.assertFalse(self.get_success(d))
  1120. class UserRestTestCase(unittest.HomeserverTestCase):
  1121. servlets = [
  1122. synapse.rest.admin.register_servlets,
  1123. login.register_servlets,
  1124. sync.register_servlets,
  1125. register.register_servlets,
  1126. ]
  1127. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1128. self.store = hs.get_datastores().main
  1129. self.auth_handler = hs.get_auth_handler()
  1130. # create users and get access tokens
  1131. # regardless of whether password login or SSO is allowed
  1132. self.admin_user = self.register_user("admin", "pass", admin=True)
  1133. self.admin_user_tok = self.get_success(
  1134. self.auth_handler.create_access_token_for_user_id(
  1135. self.admin_user, device_id=None, valid_until_ms=None
  1136. )
  1137. )
  1138. self.other_user = self.register_user("user", "pass", displayname="User")
  1139. self.other_user_token = self.get_success(
  1140. self.auth_handler.create_access_token_for_user_id(
  1141. self.other_user, device_id=None, valid_until_ms=None
  1142. )
  1143. )
  1144. self.url_prefix = "/_synapse/admin/v2/users/%s"
  1145. self.url_other_user = self.url_prefix % self.other_user
  1146. def test_requester_is_no_admin(self) -> None:
  1147. """
  1148. If the user is not a server admin, an error is returned.
  1149. """
  1150. url = self.url_prefix % "@bob:test"
  1151. channel = self.make_request(
  1152. "GET",
  1153. url,
  1154. access_token=self.other_user_token,
  1155. )
  1156. self.assertEqual(403, channel.code, msg=channel.json_body)
  1157. self.assertEqual("You are not a server admin", channel.json_body["error"])
  1158. channel = self.make_request(
  1159. "PUT",
  1160. url,
  1161. access_token=self.other_user_token,
  1162. content=b"{}",
  1163. )
  1164. self.assertEqual(403, channel.code, msg=channel.json_body)
  1165. self.assertEqual("You are not a server admin", channel.json_body["error"])
  1166. def test_user_does_not_exist(self) -> None:
  1167. """
  1168. Tests that a lookup for a user that does not exist returns a 404
  1169. """
  1170. channel = self.make_request(
  1171. "GET",
  1172. self.url_prefix % "@unknown_person:test",
  1173. access_token=self.admin_user_tok,
  1174. )
  1175. self.assertEqual(404, channel.code, msg=channel.json_body)
  1176. self.assertEqual("M_NOT_FOUND", channel.json_body["errcode"])
  1177. def test_invalid_parameter(self) -> None:
  1178. """
  1179. If parameters are invalid, an error is returned.
  1180. """
  1181. # admin not bool
  1182. channel = self.make_request(
  1183. "PUT",
  1184. self.url_other_user,
  1185. access_token=self.admin_user_tok,
  1186. content={"admin": "not_bool"},
  1187. )
  1188. self.assertEqual(400, channel.code, msg=channel.json_body)
  1189. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  1190. # deactivated not bool
  1191. channel = self.make_request(
  1192. "PUT",
  1193. self.url_other_user,
  1194. access_token=self.admin_user_tok,
  1195. content={"deactivated": "not_bool"},
  1196. )
  1197. self.assertEqual(400, channel.code, msg=channel.json_body)
  1198. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1199. # password not str
  1200. channel = self.make_request(
  1201. "PUT",
  1202. self.url_other_user,
  1203. access_token=self.admin_user_tok,
  1204. content={"password": True},
  1205. )
  1206. self.assertEqual(400, channel.code, msg=channel.json_body)
  1207. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1208. # password not length
  1209. channel = self.make_request(
  1210. "PUT",
  1211. self.url_other_user,
  1212. access_token=self.admin_user_tok,
  1213. content={"password": "x" * 513},
  1214. )
  1215. self.assertEqual(400, channel.code, msg=channel.json_body)
  1216. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1217. # user_type not valid
  1218. channel = self.make_request(
  1219. "PUT",
  1220. self.url_other_user,
  1221. access_token=self.admin_user_tok,
  1222. content={"user_type": "new type"},
  1223. )
  1224. self.assertEqual(400, channel.code, msg=channel.json_body)
  1225. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1226. # external_ids not valid
  1227. channel = self.make_request(
  1228. "PUT",
  1229. self.url_other_user,
  1230. access_token=self.admin_user_tok,
  1231. content={
  1232. "external_ids": {"auth_provider": "prov", "wrong_external_id": "id"}
  1233. },
  1234. )
  1235. self.assertEqual(400, channel.code, msg=channel.json_body)
  1236. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1237. channel = self.make_request(
  1238. "PUT",
  1239. self.url_other_user,
  1240. access_token=self.admin_user_tok,
  1241. content={"external_ids": {"external_id": "id"}},
  1242. )
  1243. self.assertEqual(400, channel.code, msg=channel.json_body)
  1244. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1245. # threepids not valid
  1246. channel = self.make_request(
  1247. "PUT",
  1248. self.url_other_user,
  1249. access_token=self.admin_user_tok,
  1250. content={"threepids": {"medium": "email", "wrong_address": "id"}},
  1251. )
  1252. self.assertEqual(400, channel.code, msg=channel.json_body)
  1253. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1254. channel = self.make_request(
  1255. "PUT",
  1256. self.url_other_user,
  1257. access_token=self.admin_user_tok,
  1258. content={"threepids": {"address": "value"}},
  1259. )
  1260. self.assertEqual(400, channel.code, msg=channel.json_body)
  1261. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1262. def test_get_user(self) -> None:
  1263. """
  1264. Test a simple get of a user.
  1265. """
  1266. channel = self.make_request(
  1267. "GET",
  1268. self.url_other_user,
  1269. access_token=self.admin_user_tok,
  1270. )
  1271. self.assertEqual(200, channel.code, msg=channel.json_body)
  1272. self.assertEqual("@user:test", channel.json_body["name"])
  1273. self.assertEqual("User", channel.json_body["displayname"])
  1274. self._check_fields(channel.json_body)
  1275. def test_create_server_admin(self) -> None:
  1276. """
  1277. Check that a new admin user is created successfully.
  1278. """
  1279. url = self.url_prefix % "@bob:test"
  1280. # Create user (server admin)
  1281. body = {
  1282. "password": "abc123",
  1283. "admin": True,
  1284. "displayname": "Bob's name",
  1285. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1286. "avatar_url": "mxc://fibble/wibble",
  1287. }
  1288. channel = self.make_request(
  1289. "PUT",
  1290. url,
  1291. access_token=self.admin_user_tok,
  1292. content=body,
  1293. )
  1294. self.assertEqual(201, channel.code, msg=channel.json_body)
  1295. self.assertEqual("@bob:test", channel.json_body["name"])
  1296. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1297. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1298. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1299. self.assertTrue(channel.json_body["admin"])
  1300. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1301. self._check_fields(channel.json_body)
  1302. # Get user
  1303. channel = self.make_request(
  1304. "GET",
  1305. url,
  1306. access_token=self.admin_user_tok,
  1307. )
  1308. self.assertEqual(200, channel.code, msg=channel.json_body)
  1309. self.assertEqual("@bob:test", channel.json_body["name"])
  1310. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1311. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1312. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1313. self.assertTrue(channel.json_body["admin"])
  1314. self.assertFalse(channel.json_body["is_guest"])
  1315. self.assertFalse(channel.json_body["deactivated"])
  1316. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1317. self._check_fields(channel.json_body)
  1318. def test_create_user(self) -> None:
  1319. """
  1320. Check that a new regular user is created successfully.
  1321. """
  1322. url = self.url_prefix % "@bob:test"
  1323. # Create user
  1324. body = {
  1325. "password": "abc123",
  1326. "admin": False,
  1327. "displayname": "Bob's name",
  1328. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1329. "external_ids": [
  1330. {
  1331. "external_id": "external_id1",
  1332. "auth_provider": "auth_provider1",
  1333. },
  1334. ],
  1335. "avatar_url": "mxc://fibble/wibble",
  1336. }
  1337. channel = self.make_request(
  1338. "PUT",
  1339. url,
  1340. access_token=self.admin_user_tok,
  1341. content=body,
  1342. )
  1343. self.assertEqual(201, channel.code, msg=channel.json_body)
  1344. self.assertEqual("@bob:test", channel.json_body["name"])
  1345. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1346. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1347. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1348. self.assertEqual(1, len(channel.json_body["threepids"]))
  1349. self.assertEqual(
  1350. "external_id1", channel.json_body["external_ids"][0]["external_id"]
  1351. )
  1352. self.assertEqual(
  1353. "auth_provider1", channel.json_body["external_ids"][0]["auth_provider"]
  1354. )
  1355. self.assertEqual(1, len(channel.json_body["external_ids"]))
  1356. self.assertFalse(channel.json_body["admin"])
  1357. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1358. self._check_fields(channel.json_body)
  1359. # Get user
  1360. channel = self.make_request(
  1361. "GET",
  1362. url,
  1363. access_token=self.admin_user_tok,
  1364. )
  1365. self.assertEqual(200, channel.code, msg=channel.json_body)
  1366. self.assertEqual("@bob:test", channel.json_body["name"])
  1367. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1368. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1369. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1370. self.assertFalse(channel.json_body["admin"])
  1371. self.assertFalse(channel.json_body["is_guest"])
  1372. self.assertFalse(channel.json_body["deactivated"])
  1373. self.assertFalse(channel.json_body["shadow_banned"])
  1374. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1375. self._check_fields(channel.json_body)
  1376. @override_config(
  1377. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  1378. )
  1379. def test_create_user_mau_limit_reached_active_admin(self) -> None:
  1380. """
  1381. Check that an admin can register a new user via the admin API
  1382. even if the MAU limit is reached.
  1383. Admin user was active before creating user.
  1384. """
  1385. handler = self.hs.get_registration_handler()
  1386. # Sync to set admin user to active
  1387. # before limit of monthly active users is reached
  1388. channel = self.make_request("GET", "/sync", access_token=self.admin_user_tok)
  1389. if channel.code != 200:
  1390. raise HttpResponseException(
  1391. channel.code, channel.result["reason"], channel.result["body"]
  1392. )
  1393. # Set monthly active users to the limit
  1394. self.store.get_monthly_active_count = Mock(
  1395. return_value=make_awaitable(self.hs.config.server.max_mau_value)
  1396. )
  1397. # Check that the blocking of monthly active users is working as expected
  1398. # The registration of a new user fails due to the limit
  1399. self.get_failure(
  1400. handler.register_user(localpart="local_part"), ResourceLimitError
  1401. )
  1402. # Register new user with admin API
  1403. url = self.url_prefix % "@bob:test"
  1404. # Create user
  1405. channel = self.make_request(
  1406. "PUT",
  1407. url,
  1408. access_token=self.admin_user_tok,
  1409. content={"password": "abc123", "admin": False},
  1410. )
  1411. self.assertEqual(201, channel.code, msg=channel.json_body)
  1412. self.assertEqual("@bob:test", channel.json_body["name"])
  1413. self.assertFalse(channel.json_body["admin"])
  1414. @override_config(
  1415. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  1416. )
  1417. def test_create_user_mau_limit_reached_passive_admin(self) -> None:
  1418. """
  1419. Check that an admin can register a new user via the admin API
  1420. even if the MAU limit is reached.
  1421. Admin user was not active before creating user.
  1422. """
  1423. handler = self.hs.get_registration_handler()
  1424. # Set monthly active users to the limit
  1425. self.store.get_monthly_active_count = Mock(
  1426. return_value=make_awaitable(self.hs.config.server.max_mau_value)
  1427. )
  1428. # Check that the blocking of monthly active users is working as expected
  1429. # The registration of a new user fails due to the limit
  1430. self.get_failure(
  1431. handler.register_user(localpart="local_part"), ResourceLimitError
  1432. )
  1433. # Register new user with admin API
  1434. url = self.url_prefix % "@bob:test"
  1435. # Create user
  1436. channel = self.make_request(
  1437. "PUT",
  1438. url,
  1439. access_token=self.admin_user_tok,
  1440. content={"password": "abc123", "admin": False},
  1441. )
  1442. # Admin user is not blocked by mau anymore
  1443. self.assertEqual(201, channel.code, msg=channel.json_body)
  1444. self.assertEqual("@bob:test", channel.json_body["name"])
  1445. self.assertFalse(channel.json_body["admin"])
  1446. @override_config(
  1447. {
  1448. "email": {
  1449. "enable_notifs": True,
  1450. "notif_for_new_users": True,
  1451. "notif_from": "test@example.com",
  1452. },
  1453. "public_baseurl": "https://example.com",
  1454. }
  1455. )
  1456. def test_create_user_email_notif_for_new_users(self) -> None:
  1457. """
  1458. Check that a new regular user is created successfully and
  1459. got an email pusher.
  1460. """
  1461. url = self.url_prefix % "@bob:test"
  1462. # Create user
  1463. body = {
  1464. "password": "abc123",
  1465. # Note that the given email is not in canonical form.
  1466. "threepids": [{"medium": "email", "address": "Bob@bob.bob"}],
  1467. }
  1468. channel = self.make_request(
  1469. "PUT",
  1470. url,
  1471. access_token=self.admin_user_tok,
  1472. content=body,
  1473. )
  1474. self.assertEqual(201, channel.code, msg=channel.json_body)
  1475. self.assertEqual("@bob:test", channel.json_body["name"])
  1476. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1477. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1478. pushers = list(
  1479. self.get_success(self.store.get_pushers_by({"user_name": "@bob:test"}))
  1480. )
  1481. self.assertEqual(len(pushers), 1)
  1482. self.assertEqual("@bob:test", pushers[0].user_name)
  1483. @override_config(
  1484. {
  1485. "email": {
  1486. "enable_notifs": False,
  1487. "notif_for_new_users": False,
  1488. "notif_from": "test@example.com",
  1489. },
  1490. "public_baseurl": "https://example.com",
  1491. }
  1492. )
  1493. def test_create_user_email_no_notif_for_new_users(self) -> None:
  1494. """
  1495. Check that a new regular user is created successfully and
  1496. got not an email pusher.
  1497. """
  1498. url = self.url_prefix % "@bob:test"
  1499. # Create user
  1500. body = {
  1501. "password": "abc123",
  1502. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1503. }
  1504. channel = self.make_request(
  1505. "PUT",
  1506. url,
  1507. access_token=self.admin_user_tok,
  1508. content=body,
  1509. )
  1510. self.assertEqual(201, channel.code, msg=channel.json_body)
  1511. self.assertEqual("@bob:test", channel.json_body["name"])
  1512. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1513. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1514. pushers = list(
  1515. self.get_success(self.store.get_pushers_by({"user_name": "@bob:test"}))
  1516. )
  1517. self.assertEqual(len(pushers), 0)
  1518. @override_config(
  1519. {
  1520. "email": {
  1521. "enable_notifs": True,
  1522. "notif_for_new_users": True,
  1523. "notif_from": "test@example.com",
  1524. },
  1525. "public_baseurl": "https://example.com",
  1526. }
  1527. )
  1528. def test_create_user_email_notif_for_new_users_with_msisdn_threepid(self) -> None:
  1529. """
  1530. Check that a new regular user is created successfully when they have a msisdn
  1531. threepid and email notif_for_new_users is set to True.
  1532. """
  1533. url = self.url_prefix % "@bob:test"
  1534. # Create user
  1535. body = {
  1536. "password": "abc123",
  1537. "threepids": [{"medium": "msisdn", "address": "1234567890"}],
  1538. }
  1539. channel = self.make_request(
  1540. "PUT",
  1541. url,
  1542. access_token=self.admin_user_tok,
  1543. content=body,
  1544. )
  1545. self.assertEqual(201, channel.code, msg=channel.json_body)
  1546. self.assertEqual("@bob:test", channel.json_body["name"])
  1547. self.assertEqual("msisdn", channel.json_body["threepids"][0]["medium"])
  1548. self.assertEqual("1234567890", channel.json_body["threepids"][0]["address"])
  1549. def test_set_password(self) -> None:
  1550. """
  1551. Test setting a new password for another user.
  1552. """
  1553. # Change password
  1554. channel = self.make_request(
  1555. "PUT",
  1556. self.url_other_user,
  1557. access_token=self.admin_user_tok,
  1558. content={"password": "hahaha"},
  1559. )
  1560. self.assertEqual(200, channel.code, msg=channel.json_body)
  1561. self._check_fields(channel.json_body)
  1562. def test_set_displayname(self) -> None:
  1563. """
  1564. Test setting the displayname of another user.
  1565. """
  1566. # Modify user
  1567. channel = self.make_request(
  1568. "PUT",
  1569. self.url_other_user,
  1570. access_token=self.admin_user_tok,
  1571. content={"displayname": "foobar"},
  1572. )
  1573. self.assertEqual(200, channel.code, msg=channel.json_body)
  1574. self.assertEqual("@user:test", channel.json_body["name"])
  1575. self.assertEqual("foobar", channel.json_body["displayname"])
  1576. # Get user
  1577. channel = self.make_request(
  1578. "GET",
  1579. self.url_other_user,
  1580. access_token=self.admin_user_tok,
  1581. )
  1582. self.assertEqual(200, channel.code, msg=channel.json_body)
  1583. self.assertEqual("@user:test", channel.json_body["name"])
  1584. self.assertEqual("foobar", channel.json_body["displayname"])
  1585. def test_set_threepid(self) -> None:
  1586. """
  1587. Test setting threepid for an other user.
  1588. """
  1589. # Add two threepids to user
  1590. channel = self.make_request(
  1591. "PUT",
  1592. self.url_other_user,
  1593. access_token=self.admin_user_tok,
  1594. content={
  1595. "threepids": [
  1596. {"medium": "email", "address": "bob1@bob.bob"},
  1597. {"medium": "email", "address": "bob2@bob.bob"},
  1598. ],
  1599. },
  1600. )
  1601. self.assertEqual(200, channel.code, msg=channel.json_body)
  1602. self.assertEqual("@user:test", channel.json_body["name"])
  1603. self.assertEqual(2, len(channel.json_body["threepids"]))
  1604. # result does not always have the same sort order, therefore it becomes sorted
  1605. sorted_result = sorted(
  1606. channel.json_body["threepids"], key=lambda k: k["address"]
  1607. )
  1608. self.assertEqual("email", sorted_result[0]["medium"])
  1609. self.assertEqual("bob1@bob.bob", sorted_result[0]["address"])
  1610. self.assertEqual("email", sorted_result[1]["medium"])
  1611. self.assertEqual("bob2@bob.bob", sorted_result[1]["address"])
  1612. self._check_fields(channel.json_body)
  1613. # Set a new and remove a threepid
  1614. channel = self.make_request(
  1615. "PUT",
  1616. self.url_other_user,
  1617. access_token=self.admin_user_tok,
  1618. content={
  1619. "threepids": [
  1620. {"medium": "email", "address": "bob2@bob.bob"},
  1621. {"medium": "email", "address": "bob3@bob.bob"},
  1622. ],
  1623. },
  1624. )
  1625. self.assertEqual(200, channel.code, msg=channel.json_body)
  1626. self.assertEqual("@user:test", channel.json_body["name"])
  1627. self.assertEqual(2, len(channel.json_body["threepids"]))
  1628. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1629. self.assertEqual("bob2@bob.bob", channel.json_body["threepids"][0]["address"])
  1630. self.assertEqual("email", channel.json_body["threepids"][1]["medium"])
  1631. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][1]["address"])
  1632. self._check_fields(channel.json_body)
  1633. # Get user
  1634. channel = self.make_request(
  1635. "GET",
  1636. self.url_other_user,
  1637. access_token=self.admin_user_tok,
  1638. )
  1639. self.assertEqual(200, channel.code, msg=channel.json_body)
  1640. self.assertEqual("@user:test", channel.json_body["name"])
  1641. self.assertEqual(2, len(channel.json_body["threepids"]))
  1642. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1643. self.assertEqual("bob2@bob.bob", channel.json_body["threepids"][0]["address"])
  1644. self.assertEqual("email", channel.json_body["threepids"][1]["medium"])
  1645. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][1]["address"])
  1646. self._check_fields(channel.json_body)
  1647. # Remove threepids
  1648. channel = self.make_request(
  1649. "PUT",
  1650. self.url_other_user,
  1651. access_token=self.admin_user_tok,
  1652. content={"threepids": []},
  1653. )
  1654. self.assertEqual(200, channel.code, msg=channel.json_body)
  1655. self.assertEqual("@user:test", channel.json_body["name"])
  1656. self.assertEqual(0, len(channel.json_body["threepids"]))
  1657. self._check_fields(channel.json_body)
  1658. def test_set_duplicate_threepid(self) -> None:
  1659. """
  1660. Test setting the same threepid for a second user.
  1661. First user loses and second user gets mapping of this threepid.
  1662. """
  1663. # create a user to set a threepid
  1664. first_user = self.register_user("first_user", "pass")
  1665. url_first_user = self.url_prefix % first_user
  1666. # Add threepid to first user
  1667. channel = self.make_request(
  1668. "PUT",
  1669. url_first_user,
  1670. access_token=self.admin_user_tok,
  1671. content={
  1672. "threepids": [
  1673. {"medium": "email", "address": "bob1@bob.bob"},
  1674. ],
  1675. },
  1676. )
  1677. self.assertEqual(200, channel.code, msg=channel.json_body)
  1678. self.assertEqual(first_user, channel.json_body["name"])
  1679. self.assertEqual(1, len(channel.json_body["threepids"]))
  1680. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1681. self.assertEqual("bob1@bob.bob", channel.json_body["threepids"][0]["address"])
  1682. self._check_fields(channel.json_body)
  1683. # Add threepids to other user
  1684. channel = self.make_request(
  1685. "PUT",
  1686. self.url_other_user,
  1687. access_token=self.admin_user_tok,
  1688. content={
  1689. "threepids": [
  1690. {"medium": "email", "address": "bob2@bob.bob"},
  1691. ],
  1692. },
  1693. )
  1694. self.assertEqual(200, channel.code, msg=channel.json_body)
  1695. self.assertEqual("@user:test", channel.json_body["name"])
  1696. self.assertEqual(1, len(channel.json_body["threepids"]))
  1697. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1698. self.assertEqual("bob2@bob.bob", channel.json_body["threepids"][0]["address"])
  1699. self._check_fields(channel.json_body)
  1700. # Add two new threepids to other user
  1701. # one is used by first_user
  1702. channel = self.make_request(
  1703. "PUT",
  1704. self.url_other_user,
  1705. access_token=self.admin_user_tok,
  1706. content={
  1707. "threepids": [
  1708. {"medium": "email", "address": "bob1@bob.bob"},
  1709. {"medium": "email", "address": "bob3@bob.bob"},
  1710. ],
  1711. },
  1712. )
  1713. # other user has this two threepids
  1714. self.assertEqual(200, channel.code, msg=channel.json_body)
  1715. self.assertEqual("@user:test", channel.json_body["name"])
  1716. self.assertEqual(2, len(channel.json_body["threepids"]))
  1717. # result does not always have the same sort order, therefore it becomes sorted
  1718. sorted_result = sorted(
  1719. channel.json_body["threepids"], key=lambda k: k["address"]
  1720. )
  1721. self.assertEqual("email", sorted_result[0]["medium"])
  1722. self.assertEqual("bob1@bob.bob", sorted_result[0]["address"])
  1723. self.assertEqual("email", sorted_result[1]["medium"])
  1724. self.assertEqual("bob3@bob.bob", sorted_result[1]["address"])
  1725. self._check_fields(channel.json_body)
  1726. # first_user has no threepid anymore
  1727. channel = self.make_request(
  1728. "GET",
  1729. url_first_user,
  1730. access_token=self.admin_user_tok,
  1731. )
  1732. self.assertEqual(200, channel.code, msg=channel.json_body)
  1733. self.assertEqual(first_user, channel.json_body["name"])
  1734. self.assertEqual(0, len(channel.json_body["threepids"]))
  1735. self._check_fields(channel.json_body)
  1736. def test_set_external_id(self) -> None:
  1737. """
  1738. Test setting external id for an other user.
  1739. """
  1740. # Add two external_ids
  1741. channel = self.make_request(
  1742. "PUT",
  1743. self.url_other_user,
  1744. access_token=self.admin_user_tok,
  1745. content={
  1746. "external_ids": [
  1747. {
  1748. "external_id": "external_id1",
  1749. "auth_provider": "auth_provider1",
  1750. },
  1751. {
  1752. "external_id": "external_id2",
  1753. "auth_provider": "auth_provider2",
  1754. },
  1755. ]
  1756. },
  1757. )
  1758. self.assertEqual(200, channel.code, msg=channel.json_body)
  1759. self.assertEqual("@user:test", channel.json_body["name"])
  1760. self.assertEqual(2, len(channel.json_body["external_ids"]))
  1761. # result does not always have the same sort order, therefore it becomes sorted
  1762. self.assertEqual(
  1763. sorted(channel.json_body["external_ids"], key=lambda k: k["auth_provider"]),
  1764. [
  1765. {"auth_provider": "auth_provider1", "external_id": "external_id1"},
  1766. {"auth_provider": "auth_provider2", "external_id": "external_id2"},
  1767. ],
  1768. )
  1769. self._check_fields(channel.json_body)
  1770. # Set a new and remove an external_id
  1771. channel = self.make_request(
  1772. "PUT",
  1773. self.url_other_user,
  1774. access_token=self.admin_user_tok,
  1775. content={
  1776. "external_ids": [
  1777. {
  1778. "external_id": "external_id2",
  1779. "auth_provider": "auth_provider2",
  1780. },
  1781. {
  1782. "external_id": "external_id3",
  1783. "auth_provider": "auth_provider3",
  1784. },
  1785. ]
  1786. },
  1787. )
  1788. self.assertEqual(200, channel.code, msg=channel.json_body)
  1789. self.assertEqual("@user:test", channel.json_body["name"])
  1790. self.assertEqual(2, len(channel.json_body["external_ids"]))
  1791. self.assertEqual(
  1792. channel.json_body["external_ids"],
  1793. [
  1794. {"auth_provider": "auth_provider2", "external_id": "external_id2"},
  1795. {"auth_provider": "auth_provider3", "external_id": "external_id3"},
  1796. ],
  1797. )
  1798. self._check_fields(channel.json_body)
  1799. # Get user
  1800. channel = self.make_request(
  1801. "GET",
  1802. self.url_other_user,
  1803. access_token=self.admin_user_tok,
  1804. )
  1805. self.assertEqual(200, channel.code, msg=channel.json_body)
  1806. self.assertEqual("@user:test", channel.json_body["name"])
  1807. self.assertEqual(2, len(channel.json_body["external_ids"]))
  1808. self.assertEqual(
  1809. channel.json_body["external_ids"],
  1810. [
  1811. {"auth_provider": "auth_provider2", "external_id": "external_id2"},
  1812. {"auth_provider": "auth_provider3", "external_id": "external_id3"},
  1813. ],
  1814. )
  1815. self._check_fields(channel.json_body)
  1816. # Remove external_ids
  1817. channel = self.make_request(
  1818. "PUT",
  1819. self.url_other_user,
  1820. access_token=self.admin_user_tok,
  1821. content={"external_ids": []},
  1822. )
  1823. self.assertEqual(200, channel.code, msg=channel.json_body)
  1824. self.assertEqual("@user:test", channel.json_body["name"])
  1825. self.assertEqual(0, len(channel.json_body["external_ids"]))
  1826. def test_set_duplicate_external_id(self) -> None:
  1827. """
  1828. Test that setting the same external id for a second user fails and
  1829. external id from user must not be changed.
  1830. """
  1831. # create a user to use an external id
  1832. first_user = self.register_user("first_user", "pass")
  1833. url_first_user = self.url_prefix % first_user
  1834. # Add an external id to first user
  1835. channel = self.make_request(
  1836. "PUT",
  1837. url_first_user,
  1838. access_token=self.admin_user_tok,
  1839. content={
  1840. "external_ids": [
  1841. {
  1842. "external_id": "external_id1",
  1843. "auth_provider": "auth_provider",
  1844. },
  1845. ],
  1846. },
  1847. )
  1848. self.assertEqual(200, channel.code, msg=channel.json_body)
  1849. self.assertEqual(first_user, channel.json_body["name"])
  1850. self.assertEqual(1, len(channel.json_body["external_ids"]))
  1851. self.assertEqual(
  1852. "external_id1", channel.json_body["external_ids"][0]["external_id"]
  1853. )
  1854. self.assertEqual(
  1855. "auth_provider", channel.json_body["external_ids"][0]["auth_provider"]
  1856. )
  1857. self._check_fields(channel.json_body)
  1858. # Add an external id to other user
  1859. channel = self.make_request(
  1860. "PUT",
  1861. self.url_other_user,
  1862. access_token=self.admin_user_tok,
  1863. content={
  1864. "external_ids": [
  1865. {
  1866. "external_id": "external_id2",
  1867. "auth_provider": "auth_provider",
  1868. },
  1869. ],
  1870. },
  1871. )
  1872. self.assertEqual(200, channel.code, msg=channel.json_body)
  1873. self.assertEqual("@user:test", channel.json_body["name"])
  1874. self.assertEqual(1, len(channel.json_body["external_ids"]))
  1875. self.assertEqual(
  1876. "external_id2", channel.json_body["external_ids"][0]["external_id"]
  1877. )
  1878. self.assertEqual(
  1879. "auth_provider", channel.json_body["external_ids"][0]["auth_provider"]
  1880. )
  1881. self._check_fields(channel.json_body)
  1882. # Add two new external_ids to other user
  1883. # one is used by first
  1884. channel = self.make_request(
  1885. "PUT",
  1886. self.url_other_user,
  1887. access_token=self.admin_user_tok,
  1888. content={
  1889. "external_ids": [
  1890. {
  1891. "external_id": "external_id1",
  1892. "auth_provider": "auth_provider",
  1893. },
  1894. {
  1895. "external_id": "external_id3",
  1896. "auth_provider": "auth_provider",
  1897. },
  1898. ],
  1899. },
  1900. )
  1901. # must fail
  1902. self.assertEqual(409, channel.code, msg=channel.json_body)
  1903. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1904. self.assertEqual("External id is already in use.", channel.json_body["error"])
  1905. # other user must not changed
  1906. channel = self.make_request(
  1907. "GET",
  1908. self.url_other_user,
  1909. access_token=self.admin_user_tok,
  1910. )
  1911. self.assertEqual(200, channel.code, msg=channel.json_body)
  1912. self.assertEqual("@user:test", channel.json_body["name"])
  1913. self.assertEqual(1, len(channel.json_body["external_ids"]))
  1914. self.assertEqual(
  1915. "external_id2", channel.json_body["external_ids"][0]["external_id"]
  1916. )
  1917. self.assertEqual(
  1918. "auth_provider", channel.json_body["external_ids"][0]["auth_provider"]
  1919. )
  1920. self._check_fields(channel.json_body)
  1921. # first user must not changed
  1922. channel = self.make_request(
  1923. "GET",
  1924. url_first_user,
  1925. access_token=self.admin_user_tok,
  1926. )
  1927. self.assertEqual(200, channel.code, msg=channel.json_body)
  1928. self.assertEqual(first_user, channel.json_body["name"])
  1929. self.assertEqual(1, len(channel.json_body["external_ids"]))
  1930. self.assertEqual(
  1931. "external_id1", channel.json_body["external_ids"][0]["external_id"]
  1932. )
  1933. self.assertEqual(
  1934. "auth_provider", channel.json_body["external_ids"][0]["auth_provider"]
  1935. )
  1936. self._check_fields(channel.json_body)
  1937. def test_deactivate_user(self) -> None:
  1938. """
  1939. Test deactivating another user.
  1940. """
  1941. # set attributes for user
  1942. self.get_success(
  1943. self.store.set_profile_avatar_url("user", "mxc://servername/mediaid")
  1944. )
  1945. self.get_success(
  1946. self.store.user_add_threepid("@user:test", "email", "foo@bar.com", 0, 0)
  1947. )
  1948. # Get user
  1949. channel = self.make_request(
  1950. "GET",
  1951. self.url_other_user,
  1952. access_token=self.admin_user_tok,
  1953. )
  1954. self.assertEqual(200, channel.code, msg=channel.json_body)
  1955. self.assertEqual("@user:test", channel.json_body["name"])
  1956. self.assertFalse(channel.json_body["deactivated"])
  1957. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  1958. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1959. self.assertEqual("User", channel.json_body["displayname"])
  1960. # Deactivate user
  1961. channel = self.make_request(
  1962. "PUT",
  1963. self.url_other_user,
  1964. access_token=self.admin_user_tok,
  1965. content={"deactivated": True},
  1966. )
  1967. self.assertEqual(200, channel.code, msg=channel.json_body)
  1968. self.assertEqual("@user:test", channel.json_body["name"])
  1969. self.assertTrue(channel.json_body["deactivated"])
  1970. self.assertEqual(0, len(channel.json_body["threepids"]))
  1971. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1972. self.assertEqual("User", channel.json_body["displayname"])
  1973. # This key was removed intentionally. Ensure it is not accidentally re-included.
  1974. self.assertNotIn("password_hash", channel.json_body)
  1975. # the user is deactivated, the threepid will be deleted
  1976. # Get user
  1977. channel = self.make_request(
  1978. "GET",
  1979. self.url_other_user,
  1980. access_token=self.admin_user_tok,
  1981. )
  1982. self.assertEqual(200, channel.code, msg=channel.json_body)
  1983. self.assertEqual("@user:test", channel.json_body["name"])
  1984. self.assertTrue(channel.json_body["deactivated"])
  1985. self.assertEqual(0, len(channel.json_body["threepids"]))
  1986. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1987. self.assertEqual("User", channel.json_body["displayname"])
  1988. # This key was removed intentionally. Ensure it is not accidentally re-included.
  1989. self.assertNotIn("password_hash", channel.json_body)
  1990. @override_config({"user_directory": {"enabled": True, "search_all_users": True}})
  1991. def test_change_name_deactivate_user_user_directory(self) -> None:
  1992. """
  1993. Test change profile information of a deactivated user and
  1994. check that it does not appear in user directory
  1995. """
  1996. # is in user directory
  1997. profile = self.get_success(self.store.get_user_in_directory(self.other_user))
  1998. assert profile is not None
  1999. self.assertTrue(profile["display_name"] == "User")
  2000. # Deactivate user
  2001. channel = self.make_request(
  2002. "PUT",
  2003. self.url_other_user,
  2004. access_token=self.admin_user_tok,
  2005. content={"deactivated": True},
  2006. )
  2007. self.assertEqual(200, channel.code, msg=channel.json_body)
  2008. self.assertEqual("@user:test", channel.json_body["name"])
  2009. self.assertTrue(channel.json_body["deactivated"])
  2010. # is not in user directory
  2011. profile = self.get_success(self.store.get_user_in_directory(self.other_user))
  2012. self.assertIsNone(profile)
  2013. # Set new displayname user
  2014. channel = self.make_request(
  2015. "PUT",
  2016. self.url_other_user,
  2017. access_token=self.admin_user_tok,
  2018. content={"displayname": "Foobar"},
  2019. )
  2020. self.assertEqual(200, channel.code, msg=channel.json_body)
  2021. self.assertEqual("@user:test", channel.json_body["name"])
  2022. self.assertTrue(channel.json_body["deactivated"])
  2023. self.assertEqual("Foobar", channel.json_body["displayname"])
  2024. # is not in user directory
  2025. profile = self.get_success(self.store.get_user_in_directory(self.other_user))
  2026. self.assertIsNone(profile)
  2027. def test_reactivate_user(self) -> None:
  2028. """
  2029. Test reactivating another user.
  2030. """
  2031. # Deactivate the user.
  2032. self._deactivate_user("@user:test")
  2033. # Attempt to reactivate the user (without a password).
  2034. channel = self.make_request(
  2035. "PUT",
  2036. self.url_other_user,
  2037. access_token=self.admin_user_tok,
  2038. content={"deactivated": False},
  2039. )
  2040. self.assertEqual(400, channel.code, msg=channel.json_body)
  2041. # Reactivate the user.
  2042. channel = self.make_request(
  2043. "PUT",
  2044. self.url_other_user,
  2045. access_token=self.admin_user_tok,
  2046. content={"deactivated": False, "password": "foo"},
  2047. )
  2048. self.assertEqual(200, channel.code, msg=channel.json_body)
  2049. self.assertEqual("@user:test", channel.json_body["name"])
  2050. self.assertFalse(channel.json_body["deactivated"])
  2051. self._is_erased("@user:test", False)
  2052. # This key was removed intentionally. Ensure it is not accidentally re-included.
  2053. self.assertNotIn("password_hash", channel.json_body)
  2054. @override_config({"password_config": {"localdb_enabled": False}})
  2055. def test_reactivate_user_localdb_disabled(self) -> None:
  2056. """
  2057. Test reactivating another user when using SSO.
  2058. """
  2059. # Deactivate the user.
  2060. self._deactivate_user("@user:test")
  2061. # Reactivate the user with a password
  2062. channel = self.make_request(
  2063. "PUT",
  2064. self.url_other_user,
  2065. access_token=self.admin_user_tok,
  2066. content={"deactivated": False, "password": "foo"},
  2067. )
  2068. self.assertEqual(403, channel.code, msg=channel.json_body)
  2069. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2070. # Reactivate the user without a password.
  2071. channel = self.make_request(
  2072. "PUT",
  2073. self.url_other_user,
  2074. access_token=self.admin_user_tok,
  2075. content={"deactivated": False},
  2076. )
  2077. self.assertEqual(200, channel.code, msg=channel.json_body)
  2078. self.assertEqual("@user:test", channel.json_body["name"])
  2079. self.assertFalse(channel.json_body["deactivated"])
  2080. self._is_erased("@user:test", False)
  2081. # This key was removed intentionally. Ensure it is not accidentally re-included.
  2082. self.assertNotIn("password_hash", channel.json_body)
  2083. @override_config({"password_config": {"enabled": False}})
  2084. def test_reactivate_user_password_disabled(self) -> None:
  2085. """
  2086. Test reactivating another user when using SSO.
  2087. """
  2088. # Deactivate the user.
  2089. self._deactivate_user("@user:test")
  2090. # Reactivate the user with a password
  2091. channel = self.make_request(
  2092. "PUT",
  2093. self.url_other_user,
  2094. access_token=self.admin_user_tok,
  2095. content={"deactivated": False, "password": "foo"},
  2096. )
  2097. self.assertEqual(403, channel.code, msg=channel.json_body)
  2098. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2099. # Reactivate the user without a password.
  2100. channel = self.make_request(
  2101. "PUT",
  2102. self.url_other_user,
  2103. access_token=self.admin_user_tok,
  2104. content={"deactivated": False},
  2105. )
  2106. self.assertEqual(200, channel.code, msg=channel.json_body)
  2107. self.assertEqual("@user:test", channel.json_body["name"])
  2108. self.assertFalse(channel.json_body["deactivated"])
  2109. self._is_erased("@user:test", False)
  2110. # This key was removed intentionally. Ensure it is not accidentally re-included.
  2111. self.assertNotIn("password_hash", channel.json_body)
  2112. def test_set_user_as_admin(self) -> None:
  2113. """
  2114. Test setting the admin flag on a user.
  2115. """
  2116. # Set a user as an admin
  2117. channel = self.make_request(
  2118. "PUT",
  2119. self.url_other_user,
  2120. access_token=self.admin_user_tok,
  2121. content={"admin": True},
  2122. )
  2123. self.assertEqual(200, channel.code, msg=channel.json_body)
  2124. self.assertEqual("@user:test", channel.json_body["name"])
  2125. self.assertTrue(channel.json_body["admin"])
  2126. # Get user
  2127. channel = self.make_request(
  2128. "GET",
  2129. self.url_other_user,
  2130. access_token=self.admin_user_tok,
  2131. )
  2132. self.assertEqual(200, channel.code, msg=channel.json_body)
  2133. self.assertEqual("@user:test", channel.json_body["name"])
  2134. self.assertTrue(channel.json_body["admin"])
  2135. def test_set_user_type(self) -> None:
  2136. """
  2137. Test changing user type.
  2138. """
  2139. # Set to support type
  2140. channel = self.make_request(
  2141. "PUT",
  2142. self.url_other_user,
  2143. access_token=self.admin_user_tok,
  2144. content={"user_type": UserTypes.SUPPORT},
  2145. )
  2146. self.assertEqual(200, channel.code, msg=channel.json_body)
  2147. self.assertEqual("@user:test", channel.json_body["name"])
  2148. self.assertEqual(UserTypes.SUPPORT, channel.json_body["user_type"])
  2149. # Get user
  2150. channel = self.make_request(
  2151. "GET",
  2152. self.url_other_user,
  2153. access_token=self.admin_user_tok,
  2154. )
  2155. self.assertEqual(200, channel.code, msg=channel.json_body)
  2156. self.assertEqual("@user:test", channel.json_body["name"])
  2157. self.assertEqual(UserTypes.SUPPORT, channel.json_body["user_type"])
  2158. # Change back to a regular user
  2159. channel = self.make_request(
  2160. "PUT",
  2161. self.url_other_user,
  2162. access_token=self.admin_user_tok,
  2163. content={"user_type": None},
  2164. )
  2165. self.assertEqual(200, channel.code, msg=channel.json_body)
  2166. self.assertEqual("@user:test", channel.json_body["name"])
  2167. self.assertIsNone(channel.json_body["user_type"])
  2168. # Get user
  2169. channel = self.make_request(
  2170. "GET",
  2171. self.url_other_user,
  2172. access_token=self.admin_user_tok,
  2173. )
  2174. self.assertEqual(200, channel.code, msg=channel.json_body)
  2175. self.assertEqual("@user:test", channel.json_body["name"])
  2176. self.assertIsNone(channel.json_body["user_type"])
  2177. def test_accidental_deactivation_prevention(self) -> None:
  2178. """
  2179. Ensure an account can't accidentally be deactivated by using a str value
  2180. for the deactivated body parameter
  2181. """
  2182. url = self.url_prefix % "@bob:test"
  2183. # Create user
  2184. channel = self.make_request(
  2185. "PUT",
  2186. url,
  2187. access_token=self.admin_user_tok,
  2188. content={"password": "abc123"},
  2189. )
  2190. self.assertEqual(201, channel.code, msg=channel.json_body)
  2191. self.assertEqual("@bob:test", channel.json_body["name"])
  2192. self.assertEqual("bob", channel.json_body["displayname"])
  2193. # Get user
  2194. channel = self.make_request(
  2195. "GET",
  2196. url,
  2197. access_token=self.admin_user_tok,
  2198. )
  2199. self.assertEqual(200, channel.code, msg=channel.json_body)
  2200. self.assertEqual("@bob:test", channel.json_body["name"])
  2201. self.assertEqual("bob", channel.json_body["displayname"])
  2202. self.assertEqual(0, channel.json_body["deactivated"])
  2203. # Change password (and use a str for deactivate instead of a bool)
  2204. channel = self.make_request(
  2205. "PUT",
  2206. url,
  2207. access_token=self.admin_user_tok,
  2208. content={"password": "abc123", "deactivated": "false"},
  2209. )
  2210. self.assertEqual(400, channel.code, msg=channel.json_body)
  2211. # Check user is not deactivated
  2212. channel = self.make_request(
  2213. "GET",
  2214. url,
  2215. access_token=self.admin_user_tok,
  2216. )
  2217. self.assertEqual(200, channel.code, msg=channel.json_body)
  2218. self.assertEqual("@bob:test", channel.json_body["name"])
  2219. self.assertEqual("bob", channel.json_body["displayname"])
  2220. # Ensure they're still alive
  2221. self.assertEqual(0, channel.json_body["deactivated"])
  2222. @override_config(
  2223. {
  2224. "experimental_features": {
  2225. "msc3866": {
  2226. "enabled": True,
  2227. "require_approval_for_new_accounts": True,
  2228. }
  2229. }
  2230. }
  2231. )
  2232. def test_approve_account(self) -> None:
  2233. """Tests that approving an account correctly sets the approved flag for the user."""
  2234. url = self.url_prefix % "@bob:test"
  2235. # Create the user using the client-server API since otherwise the user will be
  2236. # marked as approved automatically.
  2237. channel = self.make_request(
  2238. "POST",
  2239. "register",
  2240. {
  2241. "username": "bob",
  2242. "password": "test",
  2243. "auth": {"type": LoginType.DUMMY},
  2244. },
  2245. )
  2246. self.assertEqual(403, channel.code, channel.result)
  2247. self.assertEqual(Codes.USER_AWAITING_APPROVAL, channel.json_body["errcode"])
  2248. self.assertEqual(
  2249. ApprovalNoticeMedium.NONE, channel.json_body["approval_notice_medium"]
  2250. )
  2251. # Get user
  2252. channel = self.make_request(
  2253. "GET",
  2254. url,
  2255. access_token=self.admin_user_tok,
  2256. )
  2257. self.assertEqual(200, channel.code, msg=channel.json_body)
  2258. self.assertIs(False, channel.json_body["approved"])
  2259. # Approve user
  2260. channel = self.make_request(
  2261. "PUT",
  2262. url,
  2263. access_token=self.admin_user_tok,
  2264. content={"approved": True},
  2265. )
  2266. self.assertEqual(200, channel.code, msg=channel.json_body)
  2267. self.assertIs(True, channel.json_body["approved"])
  2268. # Check that the user is now approved
  2269. channel = self.make_request(
  2270. "GET",
  2271. url,
  2272. access_token=self.admin_user_tok,
  2273. )
  2274. self.assertEqual(200, channel.code, msg=channel.json_body)
  2275. self.assertIs(True, channel.json_body["approved"])
  2276. @override_config(
  2277. {
  2278. "experimental_features": {
  2279. "msc3866": {
  2280. "enabled": True,
  2281. "require_approval_for_new_accounts": True,
  2282. }
  2283. }
  2284. }
  2285. )
  2286. def test_register_approved(self) -> None:
  2287. url = self.url_prefix % "@bob:test"
  2288. # Create user
  2289. channel = self.make_request(
  2290. "PUT",
  2291. url,
  2292. access_token=self.admin_user_tok,
  2293. content={"password": "abc123", "approved": True},
  2294. )
  2295. self.assertEqual(201, channel.code, msg=channel.json_body)
  2296. self.assertEqual("@bob:test", channel.json_body["name"])
  2297. self.assertEqual(1, channel.json_body["approved"])
  2298. # Get user
  2299. channel = self.make_request(
  2300. "GET",
  2301. url,
  2302. access_token=self.admin_user_tok,
  2303. )
  2304. self.assertEqual(200, channel.code, msg=channel.json_body)
  2305. self.assertEqual("@bob:test", channel.json_body["name"])
  2306. self.assertEqual(1, channel.json_body["approved"])
  2307. def _is_erased(self, user_id: str, expect: bool) -> None:
  2308. """Assert that the user is erased or not"""
  2309. d = self.store.is_user_erased(user_id)
  2310. if expect:
  2311. self.assertTrue(self.get_success(d))
  2312. else:
  2313. self.assertFalse(self.get_success(d))
  2314. def _deactivate_user(self, user_id: str) -> None:
  2315. """Deactivate user and set as erased"""
  2316. # Deactivate the user.
  2317. channel = self.make_request(
  2318. "PUT",
  2319. self.url_prefix % urllib.parse.quote(user_id),
  2320. access_token=self.admin_user_tok,
  2321. content={"deactivated": True},
  2322. )
  2323. self.assertEqual(200, channel.code, msg=channel.json_body)
  2324. self.assertTrue(channel.json_body["deactivated"])
  2325. self._is_erased(user_id, False)
  2326. d = self.store.mark_user_erased(user_id)
  2327. self.assertIsNone(self.get_success(d))
  2328. self._is_erased(user_id, True)
  2329. # This key was removed intentionally. Ensure it is not accidentally re-included.
  2330. self.assertNotIn("password_hash", channel.json_body)
  2331. def _check_fields(self, content: JsonDict) -> None:
  2332. """Checks that the expected user attributes are present in content
  2333. Args:
  2334. content: Content dictionary to check
  2335. """
  2336. self.assertIn("displayname", content)
  2337. self.assertIn("threepids", content)
  2338. self.assertIn("avatar_url", content)
  2339. self.assertIn("admin", content)
  2340. self.assertIn("deactivated", content)
  2341. self.assertIn("erased", content)
  2342. self.assertIn("shadow_banned", content)
  2343. self.assertIn("creation_ts", content)
  2344. self.assertIn("appservice_id", content)
  2345. self.assertIn("consent_server_notice_sent", content)
  2346. self.assertIn("consent_version", content)
  2347. self.assertIn("consent_ts", content)
  2348. self.assertIn("external_ids", content)
  2349. # This key was removed intentionally. Ensure it is not accidentally re-included.
  2350. self.assertNotIn("password_hash", content)
  2351. class UserMembershipRestTestCase(unittest.HomeserverTestCase):
  2352. servlets = [
  2353. synapse.rest.admin.register_servlets,
  2354. login.register_servlets,
  2355. room.register_servlets,
  2356. ]
  2357. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2358. self.admin_user = self.register_user("admin", "pass", admin=True)
  2359. self.admin_user_tok = self.login("admin", "pass")
  2360. self.other_user = self.register_user("user", "pass")
  2361. self.url = "/_synapse/admin/v1/users/%s/joined_rooms" % urllib.parse.quote(
  2362. self.other_user
  2363. )
  2364. def test_no_auth(self) -> None:
  2365. """
  2366. Try to list rooms of an user without authentication.
  2367. """
  2368. channel = self.make_request("GET", self.url, b"{}")
  2369. self.assertEqual(401, channel.code, msg=channel.json_body)
  2370. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2371. def test_requester_is_no_admin(self) -> None:
  2372. """
  2373. If the user is not a server admin, an error is returned.
  2374. """
  2375. other_user_token = self.login("user", "pass")
  2376. channel = self.make_request(
  2377. "GET",
  2378. self.url,
  2379. access_token=other_user_token,
  2380. )
  2381. self.assertEqual(403, channel.code, msg=channel.json_body)
  2382. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2383. def test_user_does_not_exist(self) -> None:
  2384. """
  2385. Tests that a lookup for a user that does not exist returns an empty list
  2386. """
  2387. url = "/_synapse/admin/v1/users/@unknown_person:test/joined_rooms"
  2388. channel = self.make_request(
  2389. "GET",
  2390. url,
  2391. access_token=self.admin_user_tok,
  2392. )
  2393. self.assertEqual(200, channel.code, msg=channel.json_body)
  2394. self.assertEqual(0, channel.json_body["total"])
  2395. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  2396. def test_user_is_not_local(self) -> None:
  2397. """
  2398. Tests that a lookup for a user that is not a local and participates in no conversation returns an empty list
  2399. """
  2400. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/joined_rooms"
  2401. channel = self.make_request(
  2402. "GET",
  2403. url,
  2404. access_token=self.admin_user_tok,
  2405. )
  2406. self.assertEqual(200, channel.code, msg=channel.json_body)
  2407. self.assertEqual(0, channel.json_body["total"])
  2408. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  2409. def test_no_memberships(self) -> None:
  2410. """
  2411. Tests that a normal lookup for rooms is successfully
  2412. if user has no memberships
  2413. """
  2414. # Get rooms
  2415. channel = self.make_request(
  2416. "GET",
  2417. self.url,
  2418. access_token=self.admin_user_tok,
  2419. )
  2420. self.assertEqual(200, channel.code, msg=channel.json_body)
  2421. self.assertEqual(0, channel.json_body["total"])
  2422. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  2423. def test_get_rooms(self) -> None:
  2424. """
  2425. Tests that a normal lookup for rooms is successfully
  2426. """
  2427. # Create rooms and join
  2428. other_user_tok = self.login("user", "pass")
  2429. number_rooms = 5
  2430. for _ in range(number_rooms):
  2431. self.helper.create_room_as(self.other_user, tok=other_user_tok)
  2432. # Get rooms
  2433. channel = self.make_request(
  2434. "GET",
  2435. self.url,
  2436. access_token=self.admin_user_tok,
  2437. )
  2438. self.assertEqual(200, channel.code, msg=channel.json_body)
  2439. self.assertEqual(number_rooms, channel.json_body["total"])
  2440. self.assertEqual(number_rooms, len(channel.json_body["joined_rooms"]))
  2441. def test_get_rooms_with_nonlocal_user(self) -> None:
  2442. """
  2443. Tests that a normal lookup for rooms is successful with a non-local user
  2444. """
  2445. other_user_tok = self.login("user", "pass")
  2446. event_builder_factory = self.hs.get_event_builder_factory()
  2447. event_creation_handler = self.hs.get_event_creation_handler()
  2448. persistence = self.hs.get_storage_controllers().persistence
  2449. assert persistence is not None
  2450. # Create two rooms, one with a local user only and one with both a local
  2451. # and remote user.
  2452. self.helper.create_room_as(self.other_user, tok=other_user_tok)
  2453. local_and_remote_room_id = self.helper.create_room_as(
  2454. self.other_user, tok=other_user_tok
  2455. )
  2456. # Add a remote user to the room.
  2457. builder = event_builder_factory.for_room_version(
  2458. RoomVersions.V1,
  2459. {
  2460. "type": "m.room.member",
  2461. "sender": "@joiner:remote_hs",
  2462. "state_key": "@joiner:remote_hs",
  2463. "room_id": local_and_remote_room_id,
  2464. "content": {"membership": "join"},
  2465. },
  2466. )
  2467. event, unpersisted_context = self.get_success(
  2468. event_creation_handler.create_new_client_event(builder)
  2469. )
  2470. context = self.get_success(unpersisted_context.persist(event))
  2471. self.get_success(persistence.persist_event(event, context))
  2472. # Now get rooms
  2473. url = "/_synapse/admin/v1/users/@joiner:remote_hs/joined_rooms"
  2474. channel = self.make_request(
  2475. "GET",
  2476. url,
  2477. access_token=self.admin_user_tok,
  2478. )
  2479. self.assertEqual(200, channel.code, msg=channel.json_body)
  2480. self.assertEqual(1, channel.json_body["total"])
  2481. self.assertEqual([local_and_remote_room_id], channel.json_body["joined_rooms"])
  2482. class PushersRestTestCase(unittest.HomeserverTestCase):
  2483. servlets = [
  2484. synapse.rest.admin.register_servlets,
  2485. login.register_servlets,
  2486. ]
  2487. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2488. self.store = hs.get_datastores().main
  2489. self.admin_user = self.register_user("admin", "pass", admin=True)
  2490. self.admin_user_tok = self.login("admin", "pass")
  2491. self.other_user = self.register_user("user", "pass")
  2492. self.url = "/_synapse/admin/v1/users/%s/pushers" % urllib.parse.quote(
  2493. self.other_user
  2494. )
  2495. def test_no_auth(self) -> None:
  2496. """
  2497. Try to list pushers of an user without authentication.
  2498. """
  2499. channel = self.make_request("GET", self.url, b"{}")
  2500. self.assertEqual(401, channel.code, msg=channel.json_body)
  2501. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2502. def test_requester_is_no_admin(self) -> None:
  2503. """
  2504. If the user is not a server admin, an error is returned.
  2505. """
  2506. other_user_token = self.login("user", "pass")
  2507. channel = self.make_request(
  2508. "GET",
  2509. self.url,
  2510. access_token=other_user_token,
  2511. )
  2512. self.assertEqual(403, channel.code, msg=channel.json_body)
  2513. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2514. def test_user_does_not_exist(self) -> None:
  2515. """
  2516. Tests that a lookup for a user that does not exist returns a 404
  2517. """
  2518. url = "/_synapse/admin/v1/users/@unknown_person:test/pushers"
  2519. channel = self.make_request(
  2520. "GET",
  2521. url,
  2522. access_token=self.admin_user_tok,
  2523. )
  2524. self.assertEqual(404, channel.code, msg=channel.json_body)
  2525. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  2526. def test_user_is_not_local(self) -> None:
  2527. """
  2528. Tests that a lookup for a user that is not a local returns a 400
  2529. """
  2530. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/pushers"
  2531. channel = self.make_request(
  2532. "GET",
  2533. url,
  2534. access_token=self.admin_user_tok,
  2535. )
  2536. self.assertEqual(400, channel.code, msg=channel.json_body)
  2537. self.assertEqual("Can only look up local users", channel.json_body["error"])
  2538. def test_get_pushers(self) -> None:
  2539. """
  2540. Tests that a normal lookup for pushers is successfully
  2541. """
  2542. # Get pushers
  2543. channel = self.make_request(
  2544. "GET",
  2545. self.url,
  2546. access_token=self.admin_user_tok,
  2547. )
  2548. self.assertEqual(200, channel.code, msg=channel.json_body)
  2549. self.assertEqual(0, channel.json_body["total"])
  2550. # Register the pusher
  2551. other_user_token = self.login("user", "pass")
  2552. user_tuple = self.get_success(
  2553. self.store.get_user_by_access_token(other_user_token)
  2554. )
  2555. assert user_tuple is not None
  2556. token_id = user_tuple.token_id
  2557. self.get_success(
  2558. self.hs.get_pusherpool().add_or_update_pusher(
  2559. user_id=self.other_user,
  2560. access_token=token_id,
  2561. kind="http",
  2562. app_id="m.http",
  2563. app_display_name="HTTP Push Notifications",
  2564. device_display_name="pushy push",
  2565. pushkey="a@example.com",
  2566. lang=None,
  2567. data={"url": "https://example.com/_matrix/push/v1/notify"},
  2568. )
  2569. )
  2570. # Get pushers
  2571. channel = self.make_request(
  2572. "GET",
  2573. self.url,
  2574. access_token=self.admin_user_tok,
  2575. )
  2576. self.assertEqual(200, channel.code, msg=channel.json_body)
  2577. self.assertEqual(1, channel.json_body["total"])
  2578. for p in channel.json_body["pushers"]:
  2579. self.assertIn("pushkey", p)
  2580. self.assertIn("kind", p)
  2581. self.assertIn("app_id", p)
  2582. self.assertIn("app_display_name", p)
  2583. self.assertIn("device_display_name", p)
  2584. self.assertIn("profile_tag", p)
  2585. self.assertIn("lang", p)
  2586. self.assertIn("url", p["data"])
  2587. class UserMediaRestTestCase(unittest.HomeserverTestCase):
  2588. servlets = [
  2589. synapse.rest.admin.register_servlets,
  2590. login.register_servlets,
  2591. ]
  2592. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2593. self.store = hs.get_datastores().main
  2594. self.media_repo = hs.get_media_repository_resource()
  2595. self.filepaths = MediaFilePaths(hs.config.media.media_store_path)
  2596. self.admin_user = self.register_user("admin", "pass", admin=True)
  2597. self.admin_user_tok = self.login("admin", "pass")
  2598. self.other_user = self.register_user("user", "pass")
  2599. self.url = "/_synapse/admin/v1/users/%s/media" % urllib.parse.quote(
  2600. self.other_user
  2601. )
  2602. @parameterized.expand(["GET", "DELETE"])
  2603. def test_no_auth(self, method: str) -> None:
  2604. """Try to list media of an user without authentication."""
  2605. channel = self.make_request(method, self.url, {})
  2606. self.assertEqual(401, channel.code, msg=channel.json_body)
  2607. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2608. @parameterized.expand(["GET", "DELETE"])
  2609. def test_requester_is_no_admin(self, method: str) -> None:
  2610. """If the user is not a server admin, an error is returned."""
  2611. other_user_token = self.login("user", "pass")
  2612. channel = self.make_request(
  2613. method,
  2614. self.url,
  2615. access_token=other_user_token,
  2616. )
  2617. self.assertEqual(403, channel.code, msg=channel.json_body)
  2618. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2619. @parameterized.expand(["GET", "DELETE"])
  2620. def test_user_does_not_exist(self, method: str) -> None:
  2621. """Tests that a lookup for a user that does not exist returns a 404"""
  2622. url = "/_synapse/admin/v1/users/@unknown_person:test/media"
  2623. channel = self.make_request(
  2624. method,
  2625. url,
  2626. access_token=self.admin_user_tok,
  2627. )
  2628. self.assertEqual(404, channel.code, msg=channel.json_body)
  2629. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  2630. @parameterized.expand(["GET", "DELETE"])
  2631. def test_user_is_not_local(self, method: str) -> None:
  2632. """Tests that a lookup for a user that is not a local returns a 400"""
  2633. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/media"
  2634. channel = self.make_request(
  2635. method,
  2636. url,
  2637. access_token=self.admin_user_tok,
  2638. )
  2639. self.assertEqual(400, channel.code, msg=channel.json_body)
  2640. self.assertEqual("Can only look up local users", channel.json_body["error"])
  2641. def test_limit_GET(self) -> None:
  2642. """Testing list of media with limit"""
  2643. number_media = 20
  2644. other_user_tok = self.login("user", "pass")
  2645. self._create_media_for_user(other_user_tok, number_media)
  2646. channel = self.make_request(
  2647. "GET",
  2648. self.url + "?limit=5",
  2649. access_token=self.admin_user_tok,
  2650. )
  2651. self.assertEqual(200, channel.code, msg=channel.json_body)
  2652. self.assertEqual(channel.json_body["total"], number_media)
  2653. self.assertEqual(len(channel.json_body["media"]), 5)
  2654. self.assertEqual(channel.json_body["next_token"], 5)
  2655. self._check_fields(channel.json_body["media"])
  2656. def test_limit_DELETE(self) -> None:
  2657. """Testing delete of media with limit"""
  2658. number_media = 20
  2659. other_user_tok = self.login("user", "pass")
  2660. self._create_media_for_user(other_user_tok, number_media)
  2661. channel = self.make_request(
  2662. "DELETE",
  2663. self.url + "?limit=5",
  2664. access_token=self.admin_user_tok,
  2665. )
  2666. self.assertEqual(200, channel.code, msg=channel.json_body)
  2667. self.assertEqual(channel.json_body["total"], 5)
  2668. self.assertEqual(len(channel.json_body["deleted_media"]), 5)
  2669. def test_from_GET(self) -> None:
  2670. """Testing list of media with a defined starting point (from)"""
  2671. number_media = 20
  2672. other_user_tok = self.login("user", "pass")
  2673. self._create_media_for_user(other_user_tok, number_media)
  2674. channel = self.make_request(
  2675. "GET",
  2676. self.url + "?from=5",
  2677. access_token=self.admin_user_tok,
  2678. )
  2679. self.assertEqual(200, channel.code, msg=channel.json_body)
  2680. self.assertEqual(channel.json_body["total"], number_media)
  2681. self.assertEqual(len(channel.json_body["media"]), 15)
  2682. self.assertNotIn("next_token", channel.json_body)
  2683. self._check_fields(channel.json_body["media"])
  2684. def test_from_DELETE(self) -> None:
  2685. """Testing delete of media with a defined starting point (from)"""
  2686. number_media = 20
  2687. other_user_tok = self.login("user", "pass")
  2688. self._create_media_for_user(other_user_tok, number_media)
  2689. channel = self.make_request(
  2690. "DELETE",
  2691. self.url + "?from=5",
  2692. access_token=self.admin_user_tok,
  2693. )
  2694. self.assertEqual(200, channel.code, msg=channel.json_body)
  2695. self.assertEqual(channel.json_body["total"], 15)
  2696. self.assertEqual(len(channel.json_body["deleted_media"]), 15)
  2697. def test_limit_and_from_GET(self) -> None:
  2698. """Testing list of media with a defined starting point and limit"""
  2699. number_media = 20
  2700. other_user_tok = self.login("user", "pass")
  2701. self._create_media_for_user(other_user_tok, number_media)
  2702. channel = self.make_request(
  2703. "GET",
  2704. self.url + "?from=5&limit=10",
  2705. access_token=self.admin_user_tok,
  2706. )
  2707. self.assertEqual(200, channel.code, msg=channel.json_body)
  2708. self.assertEqual(channel.json_body["total"], number_media)
  2709. self.assertEqual(channel.json_body["next_token"], 15)
  2710. self.assertEqual(len(channel.json_body["media"]), 10)
  2711. self._check_fields(channel.json_body["media"])
  2712. def test_limit_and_from_DELETE(self) -> None:
  2713. """Testing delete of media with a defined starting point and limit"""
  2714. number_media = 20
  2715. other_user_tok = self.login("user", "pass")
  2716. self._create_media_for_user(other_user_tok, number_media)
  2717. channel = self.make_request(
  2718. "DELETE",
  2719. self.url + "?from=5&limit=10",
  2720. access_token=self.admin_user_tok,
  2721. )
  2722. self.assertEqual(200, channel.code, msg=channel.json_body)
  2723. self.assertEqual(channel.json_body["total"], 10)
  2724. self.assertEqual(len(channel.json_body["deleted_media"]), 10)
  2725. @parameterized.expand(["GET", "DELETE"])
  2726. def test_invalid_parameter(self, method: str) -> None:
  2727. """If parameters are invalid, an error is returned."""
  2728. # unkown order_by
  2729. channel = self.make_request(
  2730. method,
  2731. self.url + "?order_by=bar",
  2732. access_token=self.admin_user_tok,
  2733. )
  2734. self.assertEqual(400, channel.code, msg=channel.json_body)
  2735. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2736. # invalid search order
  2737. channel = self.make_request(
  2738. method,
  2739. self.url + "?dir=bar",
  2740. access_token=self.admin_user_tok,
  2741. )
  2742. self.assertEqual(400, channel.code, msg=channel.json_body)
  2743. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2744. # negative limit
  2745. channel = self.make_request(
  2746. method,
  2747. self.url + "?limit=-5",
  2748. access_token=self.admin_user_tok,
  2749. )
  2750. self.assertEqual(400, channel.code, msg=channel.json_body)
  2751. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2752. # negative from
  2753. channel = self.make_request(
  2754. method,
  2755. self.url + "?from=-5",
  2756. access_token=self.admin_user_tok,
  2757. )
  2758. self.assertEqual(400, channel.code, msg=channel.json_body)
  2759. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2760. def test_next_token(self) -> None:
  2761. """
  2762. Testing that `next_token` appears at the right place
  2763. For deleting media `next_token` is not useful, because
  2764. after deleting media the media has a new order.
  2765. """
  2766. number_media = 20
  2767. other_user_tok = self.login("user", "pass")
  2768. self._create_media_for_user(other_user_tok, number_media)
  2769. # `next_token` does not appear
  2770. # Number of results is the number of entries
  2771. channel = self.make_request(
  2772. "GET",
  2773. self.url + "?limit=20",
  2774. access_token=self.admin_user_tok,
  2775. )
  2776. self.assertEqual(200, channel.code, msg=channel.json_body)
  2777. self.assertEqual(channel.json_body["total"], number_media)
  2778. self.assertEqual(len(channel.json_body["media"]), number_media)
  2779. self.assertNotIn("next_token", channel.json_body)
  2780. # `next_token` does not appear
  2781. # Number of max results is larger than the number of entries
  2782. channel = self.make_request(
  2783. "GET",
  2784. self.url + "?limit=21",
  2785. access_token=self.admin_user_tok,
  2786. )
  2787. self.assertEqual(200, channel.code, msg=channel.json_body)
  2788. self.assertEqual(channel.json_body["total"], number_media)
  2789. self.assertEqual(len(channel.json_body["media"]), number_media)
  2790. self.assertNotIn("next_token", channel.json_body)
  2791. # `next_token` does appear
  2792. # Number of max results is smaller than the number of entries
  2793. channel = self.make_request(
  2794. "GET",
  2795. self.url + "?limit=19",
  2796. access_token=self.admin_user_tok,
  2797. )
  2798. self.assertEqual(200, channel.code, msg=channel.json_body)
  2799. self.assertEqual(channel.json_body["total"], number_media)
  2800. self.assertEqual(len(channel.json_body["media"]), 19)
  2801. self.assertEqual(channel.json_body["next_token"], 19)
  2802. # Check
  2803. # Set `from` to value of `next_token` for request remaining entries
  2804. # `next_token` does not appear
  2805. channel = self.make_request(
  2806. "GET",
  2807. self.url + "?from=19",
  2808. access_token=self.admin_user_tok,
  2809. )
  2810. self.assertEqual(200, channel.code, msg=channel.json_body)
  2811. self.assertEqual(channel.json_body["total"], number_media)
  2812. self.assertEqual(len(channel.json_body["media"]), 1)
  2813. self.assertNotIn("next_token", channel.json_body)
  2814. def test_user_has_no_media_GET(self) -> None:
  2815. """
  2816. Tests that a normal lookup for media is successfully
  2817. if user has no media created
  2818. """
  2819. channel = self.make_request(
  2820. "GET",
  2821. self.url,
  2822. access_token=self.admin_user_tok,
  2823. )
  2824. self.assertEqual(200, channel.code, msg=channel.json_body)
  2825. self.assertEqual(0, channel.json_body["total"])
  2826. self.assertEqual(0, len(channel.json_body["media"]))
  2827. def test_user_has_no_media_DELETE(self) -> None:
  2828. """
  2829. Tests that a delete is successful if user has no media
  2830. """
  2831. channel = self.make_request(
  2832. "DELETE",
  2833. self.url,
  2834. access_token=self.admin_user_tok,
  2835. )
  2836. self.assertEqual(200, channel.code, msg=channel.json_body)
  2837. self.assertEqual(0, channel.json_body["total"])
  2838. self.assertEqual(0, len(channel.json_body["deleted_media"]))
  2839. def test_get_media(self) -> None:
  2840. """Tests that a normal lookup for media is successful"""
  2841. number_media = 5
  2842. other_user_tok = self.login("user", "pass")
  2843. self._create_media_for_user(other_user_tok, number_media)
  2844. channel = self.make_request(
  2845. "GET",
  2846. self.url,
  2847. access_token=self.admin_user_tok,
  2848. )
  2849. self.assertEqual(200, channel.code, msg=channel.json_body)
  2850. self.assertEqual(number_media, channel.json_body["total"])
  2851. self.assertEqual(number_media, len(channel.json_body["media"]))
  2852. self.assertNotIn("next_token", channel.json_body)
  2853. self._check_fields(channel.json_body["media"])
  2854. def test_delete_media(self) -> None:
  2855. """Tests that a normal delete of media is successful"""
  2856. number_media = 5
  2857. other_user_tok = self.login("user", "pass")
  2858. media_ids = self._create_media_for_user(other_user_tok, number_media)
  2859. # Test if the file exists
  2860. local_paths = []
  2861. for media_id in media_ids:
  2862. local_path = self.filepaths.local_media_filepath(media_id)
  2863. self.assertTrue(os.path.exists(local_path))
  2864. local_paths.append(local_path)
  2865. channel = self.make_request(
  2866. "DELETE",
  2867. self.url,
  2868. access_token=self.admin_user_tok,
  2869. )
  2870. self.assertEqual(200, channel.code, msg=channel.json_body)
  2871. self.assertEqual(number_media, channel.json_body["total"])
  2872. self.assertEqual(number_media, len(channel.json_body["deleted_media"]))
  2873. self.assertCountEqual(channel.json_body["deleted_media"], media_ids)
  2874. # Test if the file is deleted
  2875. for local_path in local_paths:
  2876. self.assertFalse(os.path.exists(local_path))
  2877. def test_order_by(self) -> None:
  2878. """
  2879. Testing order list with parameter `order_by`
  2880. """
  2881. other_user_tok = self.login("user", "pass")
  2882. # Resolution: 1×1, MIME type: image/png, Extension: png, Size: 67 B
  2883. image_data1 = SMALL_PNG
  2884. # Resolution: 1×1, MIME type: image/gif, Extension: gif, Size: 35 B
  2885. image_data2 = unhexlify(
  2886. b"47494638376101000100800100000000"
  2887. b"ffffff2c00000000010001000002024c"
  2888. b"01003b"
  2889. )
  2890. # Resolution: 1×1, MIME type: image/bmp, Extension: bmp, Size: 54 B
  2891. image_data3 = unhexlify(
  2892. b"424d3a0000000000000036000000280000000100000001000000"
  2893. b"0100180000000000040000000000000000000000000000000000"
  2894. b"0000"
  2895. )
  2896. # create media and make sure they do not have the same timestamp
  2897. media1 = self._create_media_and_access(other_user_tok, image_data1, "image.png")
  2898. self.pump(1.0)
  2899. media2 = self._create_media_and_access(other_user_tok, image_data2, "image.gif")
  2900. self.pump(1.0)
  2901. media3 = self._create_media_and_access(other_user_tok, image_data3, "image.bmp")
  2902. self.pump(1.0)
  2903. # Mark one media as safe from quarantine.
  2904. self.get_success(self.store.mark_local_media_as_safe(media2))
  2905. # Quarantine one media
  2906. self.get_success(
  2907. self.store.quarantine_media_by_id("test", media3, self.admin_user)
  2908. )
  2909. # order by default ("created_ts")
  2910. # default is backwards
  2911. self._order_test([media3, media2, media1], None)
  2912. self._order_test([media1, media2, media3], None, "f")
  2913. self._order_test([media3, media2, media1], None, "b")
  2914. # sort by media_id
  2915. sorted_media = sorted([media1, media2, media3], reverse=False)
  2916. sorted_media_reverse = sorted(sorted_media, reverse=True)
  2917. # order by media_id
  2918. self._order_test(sorted_media, "media_id")
  2919. self._order_test(sorted_media, "media_id", "f")
  2920. self._order_test(sorted_media_reverse, "media_id", "b")
  2921. # order by upload_name
  2922. self._order_test([media3, media2, media1], "upload_name")
  2923. self._order_test([media3, media2, media1], "upload_name", "f")
  2924. self._order_test([media1, media2, media3], "upload_name", "b")
  2925. # order by media_type
  2926. # result is ordered by media_id
  2927. # because of uploaded media_type is always 'application/json'
  2928. self._order_test(sorted_media, "media_type")
  2929. self._order_test(sorted_media, "media_type", "f")
  2930. self._order_test(sorted_media, "media_type", "b")
  2931. # order by media_length
  2932. self._order_test([media2, media3, media1], "media_length")
  2933. self._order_test([media2, media3, media1], "media_length", "f")
  2934. self._order_test([media1, media3, media2], "media_length", "b")
  2935. # order by created_ts
  2936. self._order_test([media1, media2, media3], "created_ts")
  2937. self._order_test([media1, media2, media3], "created_ts", "f")
  2938. self._order_test([media3, media2, media1], "created_ts", "b")
  2939. # order by last_access_ts
  2940. self._order_test([media1, media2, media3], "last_access_ts")
  2941. self._order_test([media1, media2, media3], "last_access_ts", "f")
  2942. self._order_test([media3, media2, media1], "last_access_ts", "b")
  2943. # order by quarantined_by
  2944. # one media is in quarantine, others are ordered by media_ids
  2945. # Different sort order of SQlite and PostreSQL
  2946. # If a media is not in quarantine `quarantined_by` is NULL
  2947. # SQLite considers NULL to be smaller than any other value.
  2948. # PostreSQL considers NULL to be larger than any other value.
  2949. # self._order_test(sorted([media1, media2]) + [media3], "quarantined_by")
  2950. # self._order_test(sorted([media1, media2]) + [media3], "quarantined_by", "f")
  2951. # self._order_test([media3] + sorted([media1, media2]), "quarantined_by", "b")
  2952. # order by safe_from_quarantine
  2953. # one media is safe from quarantine, others are ordered by media_ids
  2954. self._order_test(sorted([media1, media3]) + [media2], "safe_from_quarantine")
  2955. self._order_test(
  2956. sorted([media1, media3]) + [media2], "safe_from_quarantine", "f"
  2957. )
  2958. self._order_test(
  2959. [media2] + sorted([media1, media3]), "safe_from_quarantine", "b"
  2960. )
  2961. def _create_media_for_user(self, user_token: str, number_media: int) -> List[str]:
  2962. """
  2963. Create a number of media for a specific user
  2964. Args:
  2965. user_token: Access token of the user
  2966. number_media: Number of media to be created for the user
  2967. Returns:
  2968. List of created media ID
  2969. """
  2970. media_ids = []
  2971. for _ in range(number_media):
  2972. media_ids.append(self._create_media_and_access(user_token, SMALL_PNG))
  2973. return media_ids
  2974. def _create_media_and_access(
  2975. self,
  2976. user_token: str,
  2977. image_data: bytes,
  2978. filename: str = "image1.png",
  2979. ) -> str:
  2980. """
  2981. Create one media for a specific user, access and returns `media_id`
  2982. Args:
  2983. user_token: Access token of the user
  2984. image_data: binary data of image
  2985. filename: The filename of the media to be uploaded
  2986. Returns:
  2987. The ID of the newly created media.
  2988. """
  2989. upload_resource = self.media_repo.children[b"upload"]
  2990. download_resource = self.media_repo.children[b"download"]
  2991. # Upload some media into the room
  2992. response = self.helper.upload_media(
  2993. upload_resource, image_data, user_token, filename, expect_code=200
  2994. )
  2995. # Extract media ID from the response
  2996. server_and_media_id = response["content_uri"][6:] # Cut off 'mxc://'
  2997. media_id = server_and_media_id.split("/")[1]
  2998. # Try to access a media and to create `last_access_ts`
  2999. channel = make_request(
  3000. self.reactor,
  3001. FakeSite(download_resource, self.reactor),
  3002. "GET",
  3003. server_and_media_id,
  3004. shorthand=False,
  3005. access_token=user_token,
  3006. )
  3007. self.assertEqual(
  3008. 200,
  3009. channel.code,
  3010. msg=(
  3011. f"Expected to receive a 200 on accessing media: {server_and_media_id}"
  3012. ),
  3013. )
  3014. return media_id
  3015. def _check_fields(self, content: List[JsonDict]) -> None:
  3016. """Checks that the expected user attributes are present in content
  3017. Args:
  3018. content: List that is checked for content
  3019. """
  3020. for m in content:
  3021. self.assertIn("media_id", m)
  3022. self.assertIn("media_type", m)
  3023. self.assertIn("media_length", m)
  3024. self.assertIn("upload_name", m)
  3025. self.assertIn("created_ts", m)
  3026. self.assertIn("last_access_ts", m)
  3027. self.assertIn("quarantined_by", m)
  3028. self.assertIn("safe_from_quarantine", m)
  3029. def _order_test(
  3030. self,
  3031. expected_media_list: List[str],
  3032. order_by: Optional[str],
  3033. dir: Optional[str] = None,
  3034. ) -> None:
  3035. """Request the list of media in a certain order. Assert that order is what
  3036. we expect
  3037. Args:
  3038. expected_media_list: The list of media_ids in the order we expect to get
  3039. back from the server
  3040. order_by: The type of ordering to give the server
  3041. dir: The direction of ordering to give the server
  3042. """
  3043. url = self.url + "?"
  3044. if order_by is not None:
  3045. url += f"order_by={order_by}&"
  3046. if dir is not None and dir in ("b", "f"):
  3047. url += f"dir={dir}"
  3048. channel = self.make_request(
  3049. "GET",
  3050. url,
  3051. access_token=self.admin_user_tok,
  3052. )
  3053. self.assertEqual(200, channel.code, msg=channel.json_body)
  3054. self.assertEqual(channel.json_body["total"], len(expected_media_list))
  3055. returned_order = [row["media_id"] for row in channel.json_body["media"]]
  3056. self.assertEqual(expected_media_list, returned_order)
  3057. self._check_fields(channel.json_body["media"])
  3058. class UserTokenRestTestCase(unittest.HomeserverTestCase):
  3059. """Test for /_synapse/admin/v1/users/<user>/login"""
  3060. servlets = [
  3061. synapse.rest.admin.register_servlets,
  3062. login.register_servlets,
  3063. sync.register_servlets,
  3064. room.register_servlets,
  3065. devices.register_servlets,
  3066. logout.register_servlets,
  3067. ]
  3068. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3069. self.store = hs.get_datastores().main
  3070. self.admin_user = self.register_user("admin", "pass", admin=True)
  3071. self.admin_user_tok = self.login("admin", "pass")
  3072. self.other_user = self.register_user("user", "pass")
  3073. self.other_user_tok = self.login("user", "pass")
  3074. self.url = "/_synapse/admin/v1/users/%s/login" % urllib.parse.quote(
  3075. self.other_user
  3076. )
  3077. def _get_token(self) -> str:
  3078. channel = self.make_request(
  3079. "POST", self.url, b"{}", access_token=self.admin_user_tok
  3080. )
  3081. self.assertEqual(200, channel.code, msg=channel.json_body)
  3082. return channel.json_body["access_token"]
  3083. def test_no_auth(self) -> None:
  3084. """Try to login as a user without authentication."""
  3085. channel = self.make_request("POST", self.url, b"{}")
  3086. self.assertEqual(401, channel.code, msg=channel.json_body)
  3087. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3088. def test_not_admin(self) -> None:
  3089. """Try to login as a user as a non-admin user."""
  3090. channel = self.make_request(
  3091. "POST", self.url, b"{}", access_token=self.other_user_tok
  3092. )
  3093. self.assertEqual(403, channel.code, msg=channel.json_body)
  3094. def test_send_event(self) -> None:
  3095. """Test that sending event as a user works."""
  3096. # Create a room.
  3097. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  3098. # Login in as the user
  3099. puppet_token = self._get_token()
  3100. # Test that sending works, and generates the event as the right user.
  3101. resp = self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  3102. event_id = resp["event_id"]
  3103. event = self.get_success(self.store.get_event(event_id))
  3104. self.assertEqual(event.sender, self.other_user)
  3105. def test_devices(self) -> None:
  3106. """Tests that logging in as a user doesn't create a new device for them."""
  3107. # Login in as the user
  3108. self._get_token()
  3109. # Check that we don't see a new device in our devices list
  3110. channel = self.make_request(
  3111. "GET", "devices", b"{}", access_token=self.other_user_tok
  3112. )
  3113. self.assertEqual(200, channel.code, msg=channel.json_body)
  3114. # We should only see the one device (from the login in `prepare`)
  3115. self.assertEqual(len(channel.json_body["devices"]), 1)
  3116. def test_logout(self) -> None:
  3117. """Test that calling `/logout` with the token works."""
  3118. # Login in as the user
  3119. puppet_token = self._get_token()
  3120. # Test that we can successfully make a request
  3121. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3122. self.assertEqual(200, channel.code, msg=channel.json_body)
  3123. # Logout with the puppet token
  3124. channel = self.make_request("POST", "logout", b"{}", access_token=puppet_token)
  3125. self.assertEqual(200, channel.code, msg=channel.json_body)
  3126. # The puppet token should no longer work
  3127. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3128. self.assertEqual(401, channel.code, msg=channel.json_body)
  3129. # .. but the real user's tokens should still work
  3130. channel = self.make_request(
  3131. "GET", "devices", b"{}", access_token=self.other_user_tok
  3132. )
  3133. self.assertEqual(200, channel.code, msg=channel.json_body)
  3134. def test_user_logout_all(self) -> None:
  3135. """Tests that the target user calling `/logout/all` does *not* expire
  3136. the token.
  3137. """
  3138. # Login in as the user
  3139. puppet_token = self._get_token()
  3140. # Test that we can successfully make a request
  3141. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3142. self.assertEqual(200, channel.code, msg=channel.json_body)
  3143. # Logout all with the real user token
  3144. channel = self.make_request(
  3145. "POST", "logout/all", b"{}", access_token=self.other_user_tok
  3146. )
  3147. self.assertEqual(200, channel.code, msg=channel.json_body)
  3148. # The puppet token should still work
  3149. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3150. self.assertEqual(200, channel.code, msg=channel.json_body)
  3151. # .. but the real user's tokens shouldn't
  3152. channel = self.make_request(
  3153. "GET", "devices", b"{}", access_token=self.other_user_tok
  3154. )
  3155. self.assertEqual(401, channel.code, msg=channel.json_body)
  3156. def test_admin_logout_all(self) -> None:
  3157. """Tests that the admin user calling `/logout/all` does expire the
  3158. token.
  3159. """
  3160. # Login in as the user
  3161. puppet_token = self._get_token()
  3162. # Test that we can successfully make a request
  3163. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3164. self.assertEqual(200, channel.code, msg=channel.json_body)
  3165. # Logout all with the admin user token
  3166. channel = self.make_request(
  3167. "POST", "logout/all", b"{}", access_token=self.admin_user_tok
  3168. )
  3169. self.assertEqual(200, channel.code, msg=channel.json_body)
  3170. # The puppet token should no longer work
  3171. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3172. self.assertEqual(401, channel.code, msg=channel.json_body)
  3173. # .. but the real user's tokens should still work
  3174. channel = self.make_request(
  3175. "GET", "devices", b"{}", access_token=self.other_user_tok
  3176. )
  3177. self.assertEqual(200, channel.code, msg=channel.json_body)
  3178. @unittest.override_config(
  3179. {
  3180. "public_baseurl": "https://example.org/",
  3181. "user_consent": {
  3182. "version": "1.0",
  3183. "policy_name": "My Cool Privacy Policy",
  3184. "template_dir": "/",
  3185. "require_at_registration": True,
  3186. "block_events_error": "You should accept the policy",
  3187. },
  3188. "form_secret": "123secret",
  3189. }
  3190. )
  3191. def test_consent(self) -> None:
  3192. """Test that sending a message is not subject to the privacy policies."""
  3193. # Have the admin user accept the terms.
  3194. self.get_success(self.store.user_set_consent_version(self.admin_user, "1.0"))
  3195. # First, cheekily accept the terms and create a room
  3196. self.get_success(self.store.user_set_consent_version(self.other_user, "1.0"))
  3197. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  3198. self.helper.send_event(room_id, "com.example.test", tok=self.other_user_tok)
  3199. # Now unaccept it and check that we can't send an event
  3200. self.get_success(self.store.user_set_consent_version(self.other_user, "0.0"))
  3201. self.helper.send_event(
  3202. room_id,
  3203. "com.example.test",
  3204. tok=self.other_user_tok,
  3205. expect_code=403,
  3206. )
  3207. # Login in as the user
  3208. puppet_token = self._get_token()
  3209. # Sending an event on their behalf should work fine
  3210. self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  3211. @override_config(
  3212. {"limit_usage_by_mau": True, "max_mau_value": 1, "mau_trial_days": 0}
  3213. )
  3214. def test_mau_limit(self) -> None:
  3215. # Create a room as the admin user. This will bump the monthly active users to 1.
  3216. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  3217. # Trying to join as the other user should fail due to reaching MAU limit.
  3218. self.helper.join(
  3219. room_id,
  3220. user=self.other_user,
  3221. tok=self.other_user_tok,
  3222. expect_code=403,
  3223. )
  3224. # Logging in as the other user and joining a room should work, even
  3225. # though the MAU limit would stop the user doing so.
  3226. puppet_token = self._get_token()
  3227. self.helper.join(room_id, user=self.other_user, tok=puppet_token)
  3228. @parameterized_class(
  3229. ("url_prefix",),
  3230. [
  3231. ("/_synapse/admin/v1/whois/%s",),
  3232. ("/_matrix/client/r0/admin/whois/%s",),
  3233. ],
  3234. )
  3235. class WhoisRestTestCase(unittest.HomeserverTestCase):
  3236. servlets = [
  3237. synapse.rest.admin.register_servlets,
  3238. login.register_servlets,
  3239. ]
  3240. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3241. self.admin_user = self.register_user("admin", "pass", admin=True)
  3242. self.admin_user_tok = self.login("admin", "pass")
  3243. self.other_user = self.register_user("user", "pass")
  3244. self.url = self.url_prefix % self.other_user # type: ignore[attr-defined]
  3245. def test_no_auth(self) -> None:
  3246. """
  3247. Try to get information of an user without authentication.
  3248. """
  3249. channel = self.make_request("GET", self.url, b"{}")
  3250. self.assertEqual(401, channel.code, msg=channel.json_body)
  3251. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3252. def test_requester_is_not_admin(self) -> None:
  3253. """
  3254. If the user is not a server admin, an error is returned.
  3255. """
  3256. self.register_user("user2", "pass")
  3257. other_user2_token = self.login("user2", "pass")
  3258. channel = self.make_request(
  3259. "GET",
  3260. self.url,
  3261. access_token=other_user2_token,
  3262. )
  3263. self.assertEqual(403, channel.code, msg=channel.json_body)
  3264. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  3265. def test_user_is_not_local(self) -> None:
  3266. """
  3267. Tests that a lookup for a user that is not a local returns a 400
  3268. """
  3269. url = self.url_prefix % "@unknown_person:unknown_domain" # type: ignore[attr-defined]
  3270. channel = self.make_request(
  3271. "GET",
  3272. url,
  3273. access_token=self.admin_user_tok,
  3274. )
  3275. self.assertEqual(400, channel.code, msg=channel.json_body)
  3276. self.assertEqual("Can only whois a local user", channel.json_body["error"])
  3277. def test_get_whois_admin(self) -> None:
  3278. """
  3279. The lookup should succeed for an admin.
  3280. """
  3281. channel = self.make_request(
  3282. "GET",
  3283. self.url,
  3284. access_token=self.admin_user_tok,
  3285. )
  3286. self.assertEqual(200, channel.code, msg=channel.json_body)
  3287. self.assertEqual(self.other_user, channel.json_body["user_id"])
  3288. self.assertIn("devices", channel.json_body)
  3289. def test_get_whois_user(self) -> None:
  3290. """
  3291. The lookup should succeed for a normal user looking up their own information.
  3292. """
  3293. other_user_token = self.login("user", "pass")
  3294. channel = self.make_request(
  3295. "GET",
  3296. self.url,
  3297. access_token=other_user_token,
  3298. )
  3299. self.assertEqual(200, channel.code, msg=channel.json_body)
  3300. self.assertEqual(self.other_user, channel.json_body["user_id"])
  3301. self.assertIn("devices", channel.json_body)
  3302. class ShadowBanRestTestCase(unittest.HomeserverTestCase):
  3303. servlets = [
  3304. synapse.rest.admin.register_servlets,
  3305. login.register_servlets,
  3306. ]
  3307. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3308. self.store = hs.get_datastores().main
  3309. self.admin_user = self.register_user("admin", "pass", admin=True)
  3310. self.admin_user_tok = self.login("admin", "pass")
  3311. self.other_user = self.register_user("user", "pass")
  3312. self.url = "/_synapse/admin/v1/users/%s/shadow_ban" % urllib.parse.quote(
  3313. self.other_user
  3314. )
  3315. @parameterized.expand(["POST", "DELETE"])
  3316. def test_no_auth(self, method: str) -> None:
  3317. """
  3318. Try to get information of an user without authentication.
  3319. """
  3320. channel = self.make_request(method, self.url)
  3321. self.assertEqual(401, channel.code, msg=channel.json_body)
  3322. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3323. @parameterized.expand(["POST", "DELETE"])
  3324. def test_requester_is_not_admin(self, method: str) -> None:
  3325. """
  3326. If the user is not a server admin, an error is returned.
  3327. """
  3328. other_user_token = self.login("user", "pass")
  3329. channel = self.make_request(method, self.url, access_token=other_user_token)
  3330. self.assertEqual(403, channel.code, msg=channel.json_body)
  3331. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  3332. @parameterized.expand(["POST", "DELETE"])
  3333. def test_user_is_not_local(self, method: str) -> None:
  3334. """
  3335. Tests that shadow-banning for a user that is not a local returns a 400
  3336. """
  3337. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/shadow_ban"
  3338. channel = self.make_request(method, url, access_token=self.admin_user_tok)
  3339. self.assertEqual(400, channel.code, msg=channel.json_body)
  3340. def test_success(self) -> None:
  3341. """
  3342. Shadow-banning should succeed for an admin.
  3343. """
  3344. # The user starts off as not shadow-banned.
  3345. other_user_token = self.login("user", "pass")
  3346. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  3347. assert result is not None
  3348. self.assertFalse(result.shadow_banned)
  3349. channel = self.make_request("POST", self.url, access_token=self.admin_user_tok)
  3350. self.assertEqual(200, channel.code, msg=channel.json_body)
  3351. self.assertEqual({}, channel.json_body)
  3352. # Ensure the user is shadow-banned (and the cache was cleared).
  3353. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  3354. assert result is not None
  3355. self.assertTrue(result.shadow_banned)
  3356. # Un-shadow-ban the user.
  3357. channel = self.make_request(
  3358. "DELETE", self.url, access_token=self.admin_user_tok
  3359. )
  3360. self.assertEqual(200, channel.code, msg=channel.json_body)
  3361. self.assertEqual({}, channel.json_body)
  3362. # Ensure the user is no longer shadow-banned (and the cache was cleared).
  3363. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  3364. assert result is not None
  3365. self.assertFalse(result.shadow_banned)
  3366. class RateLimitTestCase(unittest.HomeserverTestCase):
  3367. servlets = [
  3368. synapse.rest.admin.register_servlets,
  3369. login.register_servlets,
  3370. ]
  3371. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3372. self.store = hs.get_datastores().main
  3373. self.admin_user = self.register_user("admin", "pass", admin=True)
  3374. self.admin_user_tok = self.login("admin", "pass")
  3375. self.other_user = self.register_user("user", "pass")
  3376. self.url = (
  3377. "/_synapse/admin/v1/users/%s/override_ratelimit"
  3378. % urllib.parse.quote(self.other_user)
  3379. )
  3380. @parameterized.expand(["GET", "POST", "DELETE"])
  3381. def test_no_auth(self, method: str) -> None:
  3382. """
  3383. Try to get information of a user without authentication.
  3384. """
  3385. channel = self.make_request(method, self.url, b"{}")
  3386. self.assertEqual(401, channel.code, msg=channel.json_body)
  3387. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3388. @parameterized.expand(["GET", "POST", "DELETE"])
  3389. def test_requester_is_no_admin(self, method: str) -> None:
  3390. """
  3391. If the user is not a server admin, an error is returned.
  3392. """
  3393. other_user_token = self.login("user", "pass")
  3394. channel = self.make_request(
  3395. method,
  3396. self.url,
  3397. access_token=other_user_token,
  3398. )
  3399. self.assertEqual(403, channel.code, msg=channel.json_body)
  3400. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  3401. @parameterized.expand(["GET", "POST", "DELETE"])
  3402. def test_user_does_not_exist(self, method: str) -> None:
  3403. """
  3404. Tests that a lookup for a user that does not exist returns a 404
  3405. """
  3406. url = "/_synapse/admin/v1/users/@unknown_person:test/override_ratelimit"
  3407. channel = self.make_request(
  3408. method,
  3409. url,
  3410. access_token=self.admin_user_tok,
  3411. )
  3412. self.assertEqual(404, channel.code, msg=channel.json_body)
  3413. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3414. @parameterized.expand(
  3415. [
  3416. ("GET", "Can only look up local users"),
  3417. ("POST", "Only local users can be ratelimited"),
  3418. ("DELETE", "Only local users can be ratelimited"),
  3419. ]
  3420. )
  3421. def test_user_is_not_local(self, method: str, error_msg: str) -> None:
  3422. """
  3423. Tests that a lookup for a user that is not a local returns a 400
  3424. """
  3425. url = (
  3426. "/_synapse/admin/v1/users/@unknown_person:unknown_domain/override_ratelimit"
  3427. )
  3428. channel = self.make_request(
  3429. method,
  3430. url,
  3431. access_token=self.admin_user_tok,
  3432. )
  3433. self.assertEqual(400, channel.code, msg=channel.json_body)
  3434. self.assertEqual(error_msg, channel.json_body["error"])
  3435. def test_invalid_parameter(self) -> None:
  3436. """
  3437. If parameters are invalid, an error is returned.
  3438. """
  3439. # messages_per_second is a string
  3440. channel = self.make_request(
  3441. "POST",
  3442. self.url,
  3443. access_token=self.admin_user_tok,
  3444. content={"messages_per_second": "string"},
  3445. )
  3446. self.assertEqual(400, channel.code, msg=channel.json_body)
  3447. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3448. # messages_per_second is negative
  3449. channel = self.make_request(
  3450. "POST",
  3451. self.url,
  3452. access_token=self.admin_user_tok,
  3453. content={"messages_per_second": -1},
  3454. )
  3455. self.assertEqual(400, channel.code, msg=channel.json_body)
  3456. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3457. # burst_count is a string
  3458. channel = self.make_request(
  3459. "POST",
  3460. self.url,
  3461. access_token=self.admin_user_tok,
  3462. content={"burst_count": "string"},
  3463. )
  3464. self.assertEqual(400, channel.code, msg=channel.json_body)
  3465. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3466. # burst_count is negative
  3467. channel = self.make_request(
  3468. "POST",
  3469. self.url,
  3470. access_token=self.admin_user_tok,
  3471. content={"burst_count": -1},
  3472. )
  3473. self.assertEqual(400, channel.code, msg=channel.json_body)
  3474. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3475. def test_return_zero_when_null(self) -> None:
  3476. """
  3477. If values in database are `null` API should return an int `0`
  3478. """
  3479. self.get_success(
  3480. self.store.db_pool.simple_upsert(
  3481. table="ratelimit_override",
  3482. keyvalues={"user_id": self.other_user},
  3483. values={
  3484. "messages_per_second": None,
  3485. "burst_count": None,
  3486. },
  3487. )
  3488. )
  3489. # request status
  3490. channel = self.make_request(
  3491. "GET",
  3492. self.url,
  3493. access_token=self.admin_user_tok,
  3494. )
  3495. self.assertEqual(200, channel.code, msg=channel.json_body)
  3496. self.assertEqual(0, channel.json_body["messages_per_second"])
  3497. self.assertEqual(0, channel.json_body["burst_count"])
  3498. def test_success(self) -> None:
  3499. """
  3500. Rate-limiting (set/update/delete) should succeed for an admin.
  3501. """
  3502. # request status
  3503. channel = self.make_request(
  3504. "GET",
  3505. self.url,
  3506. access_token=self.admin_user_tok,
  3507. )
  3508. self.assertEqual(200, channel.code, msg=channel.json_body)
  3509. self.assertNotIn("messages_per_second", channel.json_body)
  3510. self.assertNotIn("burst_count", channel.json_body)
  3511. # set ratelimit
  3512. channel = self.make_request(
  3513. "POST",
  3514. self.url,
  3515. access_token=self.admin_user_tok,
  3516. content={"messages_per_second": 10, "burst_count": 11},
  3517. )
  3518. self.assertEqual(200, channel.code, msg=channel.json_body)
  3519. self.assertEqual(10, channel.json_body["messages_per_second"])
  3520. self.assertEqual(11, channel.json_body["burst_count"])
  3521. # update ratelimit
  3522. channel = self.make_request(
  3523. "POST",
  3524. self.url,
  3525. access_token=self.admin_user_tok,
  3526. content={"messages_per_second": 20, "burst_count": 21},
  3527. )
  3528. self.assertEqual(200, channel.code, msg=channel.json_body)
  3529. self.assertEqual(20, channel.json_body["messages_per_second"])
  3530. self.assertEqual(21, channel.json_body["burst_count"])
  3531. # request status
  3532. channel = self.make_request(
  3533. "GET",
  3534. self.url,
  3535. access_token=self.admin_user_tok,
  3536. )
  3537. self.assertEqual(200, channel.code, msg=channel.json_body)
  3538. self.assertEqual(20, channel.json_body["messages_per_second"])
  3539. self.assertEqual(21, channel.json_body["burst_count"])
  3540. # delete ratelimit
  3541. channel = self.make_request(
  3542. "DELETE",
  3543. self.url,
  3544. access_token=self.admin_user_tok,
  3545. )
  3546. self.assertEqual(200, channel.code, msg=channel.json_body)
  3547. self.assertNotIn("messages_per_second", channel.json_body)
  3548. self.assertNotIn("burst_count", channel.json_body)
  3549. # request status
  3550. channel = self.make_request(
  3551. "GET",
  3552. self.url,
  3553. access_token=self.admin_user_tok,
  3554. )
  3555. self.assertEqual(200, channel.code, msg=channel.json_body)
  3556. self.assertNotIn("messages_per_second", channel.json_body)
  3557. self.assertNotIn("burst_count", channel.json_body)
  3558. class AccountDataTestCase(unittest.HomeserverTestCase):
  3559. servlets = [
  3560. synapse.rest.admin.register_servlets,
  3561. login.register_servlets,
  3562. ]
  3563. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3564. self.store = hs.get_datastores().main
  3565. self.admin_user = self.register_user("admin", "pass", admin=True)
  3566. self.admin_user_tok = self.login("admin", "pass")
  3567. self.other_user = self.register_user("user", "pass")
  3568. self.url = f"/_synapse/admin/v1/users/{self.other_user}/accountdata"
  3569. def test_no_auth(self) -> None:
  3570. """Try to get information of a user without authentication."""
  3571. channel = self.make_request("GET", self.url, {})
  3572. self.assertEqual(401, channel.code, msg=channel.json_body)
  3573. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3574. def test_requester_is_no_admin(self) -> None:
  3575. """If the user is not a server admin, an error is returned."""
  3576. other_user_token = self.login("user", "pass")
  3577. channel = self.make_request(
  3578. "GET",
  3579. self.url,
  3580. access_token=other_user_token,
  3581. )
  3582. self.assertEqual(403, channel.code, msg=channel.json_body)
  3583. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  3584. def test_user_does_not_exist(self) -> None:
  3585. """Tests that a lookup for a user that does not exist returns a 404"""
  3586. url = "/_synapse/admin/v1/users/@unknown_person:test/override_ratelimit"
  3587. channel = self.make_request(
  3588. "GET",
  3589. url,
  3590. access_token=self.admin_user_tok,
  3591. )
  3592. self.assertEqual(404, channel.code, msg=channel.json_body)
  3593. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3594. def test_user_is_not_local(self) -> None:
  3595. """Tests that a lookup for a user that is not a local returns a 400"""
  3596. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/accountdata"
  3597. channel = self.make_request(
  3598. "GET",
  3599. url,
  3600. access_token=self.admin_user_tok,
  3601. )
  3602. self.assertEqual(400, channel.code, msg=channel.json_body)
  3603. self.assertEqual("Can only look up local users", channel.json_body["error"])
  3604. def test_success(self) -> None:
  3605. """Request account data should succeed for an admin."""
  3606. # add account data
  3607. self.get_success(
  3608. self.store.add_account_data_for_user(self.other_user, "m.global", {"a": 1})
  3609. )
  3610. self.get_success(
  3611. self.store.add_account_data_to_room(
  3612. self.other_user, "test_room", "m.per_room", {"b": 2}
  3613. )
  3614. )
  3615. channel = self.make_request(
  3616. "GET",
  3617. self.url,
  3618. access_token=self.admin_user_tok,
  3619. )
  3620. self.assertEqual(200, channel.code, msg=channel.json_body)
  3621. self.assertEqual(
  3622. {"a": 1}, channel.json_body["account_data"]["global"]["m.global"]
  3623. )
  3624. self.assertEqual(
  3625. {"b": 2},
  3626. channel.json_body["account_data"]["rooms"]["test_room"]["m.per_room"],
  3627. )
  3628. class UsersByExternalIdTestCase(unittest.HomeserverTestCase):
  3629. servlets = [
  3630. synapse.rest.admin.register_servlets,
  3631. login.register_servlets,
  3632. ]
  3633. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3634. self.store = hs.get_datastores().main
  3635. self.admin_user = self.register_user("admin", "pass", admin=True)
  3636. self.admin_user_tok = self.login("admin", "pass")
  3637. self.other_user = self.register_user("user", "pass")
  3638. self.get_success(
  3639. self.store.record_user_external_id(
  3640. "the-auth-provider", "the-external-id", self.other_user
  3641. )
  3642. )
  3643. self.get_success(
  3644. self.store.record_user_external_id(
  3645. "another-auth-provider", "a:complex@external/id", self.other_user
  3646. )
  3647. )
  3648. def test_no_auth(self) -> None:
  3649. """Try to lookup a user without authentication."""
  3650. url = (
  3651. "/_synapse/admin/v1/auth_providers/the-auth-provider/users/the-external-id"
  3652. )
  3653. channel = self.make_request(
  3654. "GET",
  3655. url,
  3656. )
  3657. self.assertEqual(401, channel.code, msg=channel.json_body)
  3658. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3659. def test_binding_does_not_exist(self) -> None:
  3660. """Tests that a lookup for an external ID that does not exist returns a 404"""
  3661. url = "/_synapse/admin/v1/auth_providers/the-auth-provider/users/unknown-id"
  3662. channel = self.make_request(
  3663. "GET",
  3664. url,
  3665. access_token=self.admin_user_tok,
  3666. )
  3667. self.assertEqual(404, channel.code, msg=channel.json_body)
  3668. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3669. def test_success(self) -> None:
  3670. """Tests a successful external ID lookup"""
  3671. url = (
  3672. "/_synapse/admin/v1/auth_providers/the-auth-provider/users/the-external-id"
  3673. )
  3674. channel = self.make_request(
  3675. "GET",
  3676. url,
  3677. access_token=self.admin_user_tok,
  3678. )
  3679. self.assertEqual(200, channel.code, msg=channel.json_body)
  3680. self.assertEqual(
  3681. {"user_id": self.other_user},
  3682. channel.json_body,
  3683. )
  3684. def test_success_urlencoded(self) -> None:
  3685. """Tests a successful external ID lookup with an url-encoded ID"""
  3686. url = "/_synapse/admin/v1/auth_providers/another-auth-provider/users/a%3Acomplex%40external%2Fid"
  3687. channel = self.make_request(
  3688. "GET",
  3689. url,
  3690. access_token=self.admin_user_tok,
  3691. )
  3692. self.assertEqual(200, channel.code, msg=channel.json_body)
  3693. self.assertEqual(
  3694. {"user_id": self.other_user},
  3695. channel.json_body,
  3696. )
  3697. class UsersByThreePidTestCase(unittest.HomeserverTestCase):
  3698. servlets = [
  3699. synapse.rest.admin.register_servlets,
  3700. login.register_servlets,
  3701. ]
  3702. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3703. self.store = hs.get_datastores().main
  3704. self.admin_user = self.register_user("admin", "pass", admin=True)
  3705. self.admin_user_tok = self.login("admin", "pass")
  3706. self.other_user = self.register_user("user", "pass")
  3707. self.get_success(
  3708. self.store.user_add_threepid(
  3709. self.other_user, "email", "user@email.com", 1, 1
  3710. )
  3711. )
  3712. self.get_success(
  3713. self.store.user_add_threepid(self.other_user, "msidn", "+1-12345678", 1, 1)
  3714. )
  3715. def test_no_auth(self) -> None:
  3716. """Try to look up a user without authentication."""
  3717. url = "/_synapse/admin/v1/threepid/email/users/user%40email.com"
  3718. channel = self.make_request(
  3719. "GET",
  3720. url,
  3721. )
  3722. self.assertEqual(401, channel.code, msg=channel.json_body)
  3723. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3724. def test_medium_does_not_exist(self) -> None:
  3725. """Tests that both a lookup for a medium that does not exist and a user that
  3726. doesn't exist with that third party ID returns a 404"""
  3727. # test for unknown medium
  3728. url = "/_synapse/admin/v1/threepid/publickey/users/unknown-key"
  3729. channel = self.make_request(
  3730. "GET",
  3731. url,
  3732. access_token=self.admin_user_tok,
  3733. )
  3734. self.assertEqual(404, channel.code, msg=channel.json_body)
  3735. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3736. # test for unknown user with a known medium
  3737. url = "/_synapse/admin/v1/threepid/email/users/unknown"
  3738. channel = self.make_request(
  3739. "GET",
  3740. url,
  3741. access_token=self.admin_user_tok,
  3742. )
  3743. self.assertEqual(404, channel.code, msg=channel.json_body)
  3744. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3745. def test_success(self) -> None:
  3746. """Tests a successful medium + address lookup"""
  3747. # test for email medium with encoded value of user@email.com
  3748. url = "/_synapse/admin/v1/threepid/email/users/user%40email.com"
  3749. channel = self.make_request(
  3750. "GET",
  3751. url,
  3752. access_token=self.admin_user_tok,
  3753. )
  3754. self.assertEqual(200, channel.code, msg=channel.json_body)
  3755. self.assertEqual(
  3756. {"user_id": self.other_user},
  3757. channel.json_body,
  3758. )
  3759. # test for msidn medium with encoded value of +1-12345678
  3760. url = "/_synapse/admin/v1/threepid/msidn/users/%2B1-12345678"
  3761. channel = self.make_request(
  3762. "GET",
  3763. url,
  3764. access_token=self.admin_user_tok,
  3765. )
  3766. self.assertEqual(200, channel.code, msg=channel.json_body)
  3767. self.assertEqual(
  3768. {"user_id": self.other_user},
  3769. channel.json_body,
  3770. )