test_user.py 161 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525
  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.rest.client import devices, login, logout, profile, register, room, sync
  28. from synapse.rest.media.v1.filepath import MediaFilePaths
  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. storage_controllers = self.hs.get_storage_controllers()
  2449. # Create two rooms, one with a local user only and one with both a local
  2450. # and remote user.
  2451. self.helper.create_room_as(self.other_user, tok=other_user_tok)
  2452. local_and_remote_room_id = self.helper.create_room_as(
  2453. self.other_user, tok=other_user_tok
  2454. )
  2455. # Add a remote user to the room.
  2456. builder = event_builder_factory.for_room_version(
  2457. RoomVersions.V1,
  2458. {
  2459. "type": "m.room.member",
  2460. "sender": "@joiner:remote_hs",
  2461. "state_key": "@joiner:remote_hs",
  2462. "room_id": local_and_remote_room_id,
  2463. "content": {"membership": "join"},
  2464. },
  2465. )
  2466. event, context = self.get_success(
  2467. event_creation_handler.create_new_client_event(builder)
  2468. )
  2469. self.get_success(storage_controllers.persistence.persist_event(event, context))
  2470. # Now get rooms
  2471. url = "/_synapse/admin/v1/users/@joiner:remote_hs/joined_rooms"
  2472. channel = self.make_request(
  2473. "GET",
  2474. url,
  2475. access_token=self.admin_user_tok,
  2476. )
  2477. self.assertEqual(200, channel.code, msg=channel.json_body)
  2478. self.assertEqual(1, channel.json_body["total"])
  2479. self.assertEqual([local_and_remote_room_id], channel.json_body["joined_rooms"])
  2480. class PushersRestTestCase(unittest.HomeserverTestCase):
  2481. servlets = [
  2482. synapse.rest.admin.register_servlets,
  2483. login.register_servlets,
  2484. ]
  2485. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2486. self.store = hs.get_datastores().main
  2487. self.admin_user = self.register_user("admin", "pass", admin=True)
  2488. self.admin_user_tok = self.login("admin", "pass")
  2489. self.other_user = self.register_user("user", "pass")
  2490. self.url = "/_synapse/admin/v1/users/%s/pushers" % urllib.parse.quote(
  2491. self.other_user
  2492. )
  2493. def test_no_auth(self) -> None:
  2494. """
  2495. Try to list pushers of an user without authentication.
  2496. """
  2497. channel = self.make_request("GET", self.url, b"{}")
  2498. self.assertEqual(401, channel.code, msg=channel.json_body)
  2499. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2500. def test_requester_is_no_admin(self) -> None:
  2501. """
  2502. If the user is not a server admin, an error is returned.
  2503. """
  2504. other_user_token = self.login("user", "pass")
  2505. channel = self.make_request(
  2506. "GET",
  2507. self.url,
  2508. access_token=other_user_token,
  2509. )
  2510. self.assertEqual(403, channel.code, msg=channel.json_body)
  2511. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2512. def test_user_does_not_exist(self) -> None:
  2513. """
  2514. Tests that a lookup for a user that does not exist returns a 404
  2515. """
  2516. url = "/_synapse/admin/v1/users/@unknown_person:test/pushers"
  2517. channel = self.make_request(
  2518. "GET",
  2519. url,
  2520. access_token=self.admin_user_tok,
  2521. )
  2522. self.assertEqual(404, channel.code, msg=channel.json_body)
  2523. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  2524. def test_user_is_not_local(self) -> None:
  2525. """
  2526. Tests that a lookup for a user that is not a local returns a 400
  2527. """
  2528. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/pushers"
  2529. channel = self.make_request(
  2530. "GET",
  2531. url,
  2532. access_token=self.admin_user_tok,
  2533. )
  2534. self.assertEqual(400, channel.code, msg=channel.json_body)
  2535. self.assertEqual("Can only look up local users", channel.json_body["error"])
  2536. def test_get_pushers(self) -> None:
  2537. """
  2538. Tests that a normal lookup for pushers is successfully
  2539. """
  2540. # Get pushers
  2541. channel = self.make_request(
  2542. "GET",
  2543. self.url,
  2544. access_token=self.admin_user_tok,
  2545. )
  2546. self.assertEqual(200, channel.code, msg=channel.json_body)
  2547. self.assertEqual(0, channel.json_body["total"])
  2548. # Register the pusher
  2549. other_user_token = self.login("user", "pass")
  2550. user_tuple = self.get_success(
  2551. self.store.get_user_by_access_token(other_user_token)
  2552. )
  2553. assert user_tuple is not None
  2554. token_id = user_tuple.token_id
  2555. self.get_success(
  2556. self.hs.get_pusherpool().add_or_update_pusher(
  2557. user_id=self.other_user,
  2558. access_token=token_id,
  2559. kind="http",
  2560. app_id="m.http",
  2561. app_display_name="HTTP Push Notifications",
  2562. device_display_name="pushy push",
  2563. pushkey="a@example.com",
  2564. lang=None,
  2565. data={"url": "https://example.com/_matrix/push/v1/notify"},
  2566. )
  2567. )
  2568. # Get pushers
  2569. channel = self.make_request(
  2570. "GET",
  2571. self.url,
  2572. access_token=self.admin_user_tok,
  2573. )
  2574. self.assertEqual(200, channel.code, msg=channel.json_body)
  2575. self.assertEqual(1, channel.json_body["total"])
  2576. for p in channel.json_body["pushers"]:
  2577. self.assertIn("pushkey", p)
  2578. self.assertIn("kind", p)
  2579. self.assertIn("app_id", p)
  2580. self.assertIn("app_display_name", p)
  2581. self.assertIn("device_display_name", p)
  2582. self.assertIn("profile_tag", p)
  2583. self.assertIn("lang", p)
  2584. self.assertIn("url", p["data"])
  2585. class UserMediaRestTestCase(unittest.HomeserverTestCase):
  2586. servlets = [
  2587. synapse.rest.admin.register_servlets,
  2588. login.register_servlets,
  2589. ]
  2590. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2591. self.store = hs.get_datastores().main
  2592. self.media_repo = hs.get_media_repository_resource()
  2593. self.filepaths = MediaFilePaths(hs.config.media.media_store_path)
  2594. self.admin_user = self.register_user("admin", "pass", admin=True)
  2595. self.admin_user_tok = self.login("admin", "pass")
  2596. self.other_user = self.register_user("user", "pass")
  2597. self.url = "/_synapse/admin/v1/users/%s/media" % urllib.parse.quote(
  2598. self.other_user
  2599. )
  2600. @parameterized.expand(["GET", "DELETE"])
  2601. def test_no_auth(self, method: str) -> None:
  2602. """Try to list media of an user without authentication."""
  2603. channel = self.make_request(method, self.url, {})
  2604. self.assertEqual(401, channel.code, msg=channel.json_body)
  2605. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2606. @parameterized.expand(["GET", "DELETE"])
  2607. def test_requester_is_no_admin(self, method: str) -> None:
  2608. """If the user is not a server admin, an error is returned."""
  2609. other_user_token = self.login("user", "pass")
  2610. channel = self.make_request(
  2611. method,
  2612. self.url,
  2613. access_token=other_user_token,
  2614. )
  2615. self.assertEqual(403, channel.code, msg=channel.json_body)
  2616. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2617. @parameterized.expand(["GET", "DELETE"])
  2618. def test_user_does_not_exist(self, method: str) -> None:
  2619. """Tests that a lookup for a user that does not exist returns a 404"""
  2620. url = "/_synapse/admin/v1/users/@unknown_person:test/media"
  2621. channel = self.make_request(
  2622. method,
  2623. url,
  2624. access_token=self.admin_user_tok,
  2625. )
  2626. self.assertEqual(404, channel.code, msg=channel.json_body)
  2627. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  2628. @parameterized.expand(["GET", "DELETE"])
  2629. def test_user_is_not_local(self, method: str) -> None:
  2630. """Tests that a lookup for a user that is not a local returns a 400"""
  2631. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/media"
  2632. channel = self.make_request(
  2633. method,
  2634. url,
  2635. access_token=self.admin_user_tok,
  2636. )
  2637. self.assertEqual(400, channel.code, msg=channel.json_body)
  2638. self.assertEqual("Can only look up local users", channel.json_body["error"])
  2639. def test_limit_GET(self) -> None:
  2640. """Testing list of media with limit"""
  2641. number_media = 20
  2642. other_user_tok = self.login("user", "pass")
  2643. self._create_media_for_user(other_user_tok, number_media)
  2644. channel = self.make_request(
  2645. "GET",
  2646. self.url + "?limit=5",
  2647. access_token=self.admin_user_tok,
  2648. )
  2649. self.assertEqual(200, channel.code, msg=channel.json_body)
  2650. self.assertEqual(channel.json_body["total"], number_media)
  2651. self.assertEqual(len(channel.json_body["media"]), 5)
  2652. self.assertEqual(channel.json_body["next_token"], 5)
  2653. self._check_fields(channel.json_body["media"])
  2654. def test_limit_DELETE(self) -> None:
  2655. """Testing delete of media with limit"""
  2656. number_media = 20
  2657. other_user_tok = self.login("user", "pass")
  2658. self._create_media_for_user(other_user_tok, number_media)
  2659. channel = self.make_request(
  2660. "DELETE",
  2661. self.url + "?limit=5",
  2662. access_token=self.admin_user_tok,
  2663. )
  2664. self.assertEqual(200, channel.code, msg=channel.json_body)
  2665. self.assertEqual(channel.json_body["total"], 5)
  2666. self.assertEqual(len(channel.json_body["deleted_media"]), 5)
  2667. def test_from_GET(self) -> None:
  2668. """Testing list of media with a defined starting point (from)"""
  2669. number_media = 20
  2670. other_user_tok = self.login("user", "pass")
  2671. self._create_media_for_user(other_user_tok, number_media)
  2672. channel = self.make_request(
  2673. "GET",
  2674. self.url + "?from=5",
  2675. access_token=self.admin_user_tok,
  2676. )
  2677. self.assertEqual(200, channel.code, msg=channel.json_body)
  2678. self.assertEqual(channel.json_body["total"], number_media)
  2679. self.assertEqual(len(channel.json_body["media"]), 15)
  2680. self.assertNotIn("next_token", channel.json_body)
  2681. self._check_fields(channel.json_body["media"])
  2682. def test_from_DELETE(self) -> None:
  2683. """Testing delete of media with a defined starting point (from)"""
  2684. number_media = 20
  2685. other_user_tok = self.login("user", "pass")
  2686. self._create_media_for_user(other_user_tok, number_media)
  2687. channel = self.make_request(
  2688. "DELETE",
  2689. self.url + "?from=5",
  2690. access_token=self.admin_user_tok,
  2691. )
  2692. self.assertEqual(200, channel.code, msg=channel.json_body)
  2693. self.assertEqual(channel.json_body["total"], 15)
  2694. self.assertEqual(len(channel.json_body["deleted_media"]), 15)
  2695. def test_limit_and_from_GET(self) -> None:
  2696. """Testing list of media with a defined starting point and limit"""
  2697. number_media = 20
  2698. other_user_tok = self.login("user", "pass")
  2699. self._create_media_for_user(other_user_tok, number_media)
  2700. channel = self.make_request(
  2701. "GET",
  2702. self.url + "?from=5&limit=10",
  2703. access_token=self.admin_user_tok,
  2704. )
  2705. self.assertEqual(200, channel.code, msg=channel.json_body)
  2706. self.assertEqual(channel.json_body["total"], number_media)
  2707. self.assertEqual(channel.json_body["next_token"], 15)
  2708. self.assertEqual(len(channel.json_body["media"]), 10)
  2709. self._check_fields(channel.json_body["media"])
  2710. def test_limit_and_from_DELETE(self) -> None:
  2711. """Testing delete of media with a defined starting point and limit"""
  2712. number_media = 20
  2713. other_user_tok = self.login("user", "pass")
  2714. self._create_media_for_user(other_user_tok, number_media)
  2715. channel = self.make_request(
  2716. "DELETE",
  2717. self.url + "?from=5&limit=10",
  2718. access_token=self.admin_user_tok,
  2719. )
  2720. self.assertEqual(200, channel.code, msg=channel.json_body)
  2721. self.assertEqual(channel.json_body["total"], 10)
  2722. self.assertEqual(len(channel.json_body["deleted_media"]), 10)
  2723. @parameterized.expand(["GET", "DELETE"])
  2724. def test_invalid_parameter(self, method: str) -> None:
  2725. """If parameters are invalid, an error is returned."""
  2726. # unkown order_by
  2727. channel = self.make_request(
  2728. method,
  2729. self.url + "?order_by=bar",
  2730. access_token=self.admin_user_tok,
  2731. )
  2732. self.assertEqual(400, channel.code, msg=channel.json_body)
  2733. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2734. # invalid search order
  2735. channel = self.make_request(
  2736. method,
  2737. self.url + "?dir=bar",
  2738. access_token=self.admin_user_tok,
  2739. )
  2740. self.assertEqual(400, channel.code, msg=channel.json_body)
  2741. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2742. # negative limit
  2743. channel = self.make_request(
  2744. method,
  2745. self.url + "?limit=-5",
  2746. access_token=self.admin_user_tok,
  2747. )
  2748. self.assertEqual(400, channel.code, msg=channel.json_body)
  2749. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2750. # negative from
  2751. channel = self.make_request(
  2752. method,
  2753. self.url + "?from=-5",
  2754. access_token=self.admin_user_tok,
  2755. )
  2756. self.assertEqual(400, channel.code, msg=channel.json_body)
  2757. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2758. def test_next_token(self) -> None:
  2759. """
  2760. Testing that `next_token` appears at the right place
  2761. For deleting media `next_token` is not useful, because
  2762. after deleting media the media has a new order.
  2763. """
  2764. number_media = 20
  2765. other_user_tok = self.login("user", "pass")
  2766. self._create_media_for_user(other_user_tok, number_media)
  2767. # `next_token` does not appear
  2768. # Number of results is the number of entries
  2769. channel = self.make_request(
  2770. "GET",
  2771. self.url + "?limit=20",
  2772. access_token=self.admin_user_tok,
  2773. )
  2774. self.assertEqual(200, channel.code, msg=channel.json_body)
  2775. self.assertEqual(channel.json_body["total"], number_media)
  2776. self.assertEqual(len(channel.json_body["media"]), number_media)
  2777. self.assertNotIn("next_token", channel.json_body)
  2778. # `next_token` does not appear
  2779. # Number of max results is larger than the number of entries
  2780. channel = self.make_request(
  2781. "GET",
  2782. self.url + "?limit=21",
  2783. access_token=self.admin_user_tok,
  2784. )
  2785. self.assertEqual(200, channel.code, msg=channel.json_body)
  2786. self.assertEqual(channel.json_body["total"], number_media)
  2787. self.assertEqual(len(channel.json_body["media"]), number_media)
  2788. self.assertNotIn("next_token", channel.json_body)
  2789. # `next_token` does appear
  2790. # Number of max results is smaller than the number of entries
  2791. channel = self.make_request(
  2792. "GET",
  2793. self.url + "?limit=19",
  2794. access_token=self.admin_user_tok,
  2795. )
  2796. self.assertEqual(200, channel.code, msg=channel.json_body)
  2797. self.assertEqual(channel.json_body["total"], number_media)
  2798. self.assertEqual(len(channel.json_body["media"]), 19)
  2799. self.assertEqual(channel.json_body["next_token"], 19)
  2800. # Check
  2801. # Set `from` to value of `next_token` for request remaining entries
  2802. # `next_token` does not appear
  2803. channel = self.make_request(
  2804. "GET",
  2805. self.url + "?from=19",
  2806. access_token=self.admin_user_tok,
  2807. )
  2808. self.assertEqual(200, channel.code, msg=channel.json_body)
  2809. self.assertEqual(channel.json_body["total"], number_media)
  2810. self.assertEqual(len(channel.json_body["media"]), 1)
  2811. self.assertNotIn("next_token", channel.json_body)
  2812. def test_user_has_no_media_GET(self) -> None:
  2813. """
  2814. Tests that a normal lookup for media is successfully
  2815. if user has no media created
  2816. """
  2817. channel = self.make_request(
  2818. "GET",
  2819. self.url,
  2820. access_token=self.admin_user_tok,
  2821. )
  2822. self.assertEqual(200, channel.code, msg=channel.json_body)
  2823. self.assertEqual(0, channel.json_body["total"])
  2824. self.assertEqual(0, len(channel.json_body["media"]))
  2825. def test_user_has_no_media_DELETE(self) -> None:
  2826. """
  2827. Tests that a delete is successful if user has no media
  2828. """
  2829. channel = self.make_request(
  2830. "DELETE",
  2831. self.url,
  2832. access_token=self.admin_user_tok,
  2833. )
  2834. self.assertEqual(200, channel.code, msg=channel.json_body)
  2835. self.assertEqual(0, channel.json_body["total"])
  2836. self.assertEqual(0, len(channel.json_body["deleted_media"]))
  2837. def test_get_media(self) -> None:
  2838. """Tests that a normal lookup for media is successful"""
  2839. number_media = 5
  2840. other_user_tok = self.login("user", "pass")
  2841. self._create_media_for_user(other_user_tok, number_media)
  2842. channel = self.make_request(
  2843. "GET",
  2844. self.url,
  2845. access_token=self.admin_user_tok,
  2846. )
  2847. self.assertEqual(200, channel.code, msg=channel.json_body)
  2848. self.assertEqual(number_media, channel.json_body["total"])
  2849. self.assertEqual(number_media, len(channel.json_body["media"]))
  2850. self.assertNotIn("next_token", channel.json_body)
  2851. self._check_fields(channel.json_body["media"])
  2852. def test_delete_media(self) -> None:
  2853. """Tests that a normal delete of media is successful"""
  2854. number_media = 5
  2855. other_user_tok = self.login("user", "pass")
  2856. media_ids = self._create_media_for_user(other_user_tok, number_media)
  2857. # Test if the file exists
  2858. local_paths = []
  2859. for media_id in media_ids:
  2860. local_path = self.filepaths.local_media_filepath(media_id)
  2861. self.assertTrue(os.path.exists(local_path))
  2862. local_paths.append(local_path)
  2863. channel = self.make_request(
  2864. "DELETE",
  2865. self.url,
  2866. access_token=self.admin_user_tok,
  2867. )
  2868. self.assertEqual(200, channel.code, msg=channel.json_body)
  2869. self.assertEqual(number_media, channel.json_body["total"])
  2870. self.assertEqual(number_media, len(channel.json_body["deleted_media"]))
  2871. self.assertCountEqual(channel.json_body["deleted_media"], media_ids)
  2872. # Test if the file is deleted
  2873. for local_path in local_paths:
  2874. self.assertFalse(os.path.exists(local_path))
  2875. def test_order_by(self) -> None:
  2876. """
  2877. Testing order list with parameter `order_by`
  2878. """
  2879. other_user_tok = self.login("user", "pass")
  2880. # Resolution: 1×1, MIME type: image/png, Extension: png, Size: 67 B
  2881. image_data1 = SMALL_PNG
  2882. # Resolution: 1×1, MIME type: image/gif, Extension: gif, Size: 35 B
  2883. image_data2 = unhexlify(
  2884. b"47494638376101000100800100000000"
  2885. b"ffffff2c00000000010001000002024c"
  2886. b"01003b"
  2887. )
  2888. # Resolution: 1×1, MIME type: image/bmp, Extension: bmp, Size: 54 B
  2889. image_data3 = unhexlify(
  2890. b"424d3a0000000000000036000000280000000100000001000000"
  2891. b"0100180000000000040000000000000000000000000000000000"
  2892. b"0000"
  2893. )
  2894. # create media and make sure they do not have the same timestamp
  2895. media1 = self._create_media_and_access(other_user_tok, image_data1, "image.png")
  2896. self.pump(1.0)
  2897. media2 = self._create_media_and_access(other_user_tok, image_data2, "image.gif")
  2898. self.pump(1.0)
  2899. media3 = self._create_media_and_access(other_user_tok, image_data3, "image.bmp")
  2900. self.pump(1.0)
  2901. # Mark one media as safe from quarantine.
  2902. self.get_success(self.store.mark_local_media_as_safe(media2))
  2903. # Quarantine one media
  2904. self.get_success(
  2905. self.store.quarantine_media_by_id("test", media3, self.admin_user)
  2906. )
  2907. # order by default ("created_ts")
  2908. # default is backwards
  2909. self._order_test([media3, media2, media1], None)
  2910. self._order_test([media1, media2, media3], None, "f")
  2911. self._order_test([media3, media2, media1], None, "b")
  2912. # sort by media_id
  2913. sorted_media = sorted([media1, media2, media3], reverse=False)
  2914. sorted_media_reverse = sorted(sorted_media, reverse=True)
  2915. # order by media_id
  2916. self._order_test(sorted_media, "media_id")
  2917. self._order_test(sorted_media, "media_id", "f")
  2918. self._order_test(sorted_media_reverse, "media_id", "b")
  2919. # order by upload_name
  2920. self._order_test([media3, media2, media1], "upload_name")
  2921. self._order_test([media3, media2, media1], "upload_name", "f")
  2922. self._order_test([media1, media2, media3], "upload_name", "b")
  2923. # order by media_type
  2924. # result is ordered by media_id
  2925. # because of uploaded media_type is always 'application/json'
  2926. self._order_test(sorted_media, "media_type")
  2927. self._order_test(sorted_media, "media_type", "f")
  2928. self._order_test(sorted_media, "media_type", "b")
  2929. # order by media_length
  2930. self._order_test([media2, media3, media1], "media_length")
  2931. self._order_test([media2, media3, media1], "media_length", "f")
  2932. self._order_test([media1, media3, media2], "media_length", "b")
  2933. # order by created_ts
  2934. self._order_test([media1, media2, media3], "created_ts")
  2935. self._order_test([media1, media2, media3], "created_ts", "f")
  2936. self._order_test([media3, media2, media1], "created_ts", "b")
  2937. # order by last_access_ts
  2938. self._order_test([media1, media2, media3], "last_access_ts")
  2939. self._order_test([media1, media2, media3], "last_access_ts", "f")
  2940. self._order_test([media3, media2, media1], "last_access_ts", "b")
  2941. # order by quarantined_by
  2942. # one media is in quarantine, others are ordered by media_ids
  2943. # Different sort order of SQlite and PostreSQL
  2944. # If a media is not in quarantine `quarantined_by` is NULL
  2945. # SQLite considers NULL to be smaller than any other value.
  2946. # PostreSQL considers NULL to be larger than any other value.
  2947. # self._order_test(sorted([media1, media2]) + [media3], "quarantined_by")
  2948. # self._order_test(sorted([media1, media2]) + [media3], "quarantined_by", "f")
  2949. # self._order_test([media3] + sorted([media1, media2]), "quarantined_by", "b")
  2950. # order by safe_from_quarantine
  2951. # one media is safe from quarantine, others are ordered by media_ids
  2952. self._order_test(sorted([media1, media3]) + [media2], "safe_from_quarantine")
  2953. self._order_test(
  2954. sorted([media1, media3]) + [media2], "safe_from_quarantine", "f"
  2955. )
  2956. self._order_test(
  2957. [media2] + sorted([media1, media3]), "safe_from_quarantine", "b"
  2958. )
  2959. def _create_media_for_user(self, user_token: str, number_media: int) -> List[str]:
  2960. """
  2961. Create a number of media for a specific user
  2962. Args:
  2963. user_token: Access token of the user
  2964. number_media: Number of media to be created for the user
  2965. Returns:
  2966. List of created media ID
  2967. """
  2968. media_ids = []
  2969. for _ in range(number_media):
  2970. media_ids.append(self._create_media_and_access(user_token, SMALL_PNG))
  2971. return media_ids
  2972. def _create_media_and_access(
  2973. self,
  2974. user_token: str,
  2975. image_data: bytes,
  2976. filename: str = "image1.png",
  2977. ) -> str:
  2978. """
  2979. Create one media for a specific user, access and returns `media_id`
  2980. Args:
  2981. user_token: Access token of the user
  2982. image_data: binary data of image
  2983. filename: The filename of the media to be uploaded
  2984. Returns:
  2985. The ID of the newly created media.
  2986. """
  2987. upload_resource = self.media_repo.children[b"upload"]
  2988. download_resource = self.media_repo.children[b"download"]
  2989. # Upload some media into the room
  2990. response = self.helper.upload_media(
  2991. upload_resource, image_data, user_token, filename, expect_code=200
  2992. )
  2993. # Extract media ID from the response
  2994. server_and_media_id = response["content_uri"][6:] # Cut off 'mxc://'
  2995. media_id = server_and_media_id.split("/")[1]
  2996. # Try to access a media and to create `last_access_ts`
  2997. channel = make_request(
  2998. self.reactor,
  2999. FakeSite(download_resource, self.reactor),
  3000. "GET",
  3001. server_and_media_id,
  3002. shorthand=False,
  3003. access_token=user_token,
  3004. )
  3005. self.assertEqual(
  3006. 200,
  3007. channel.code,
  3008. msg=(
  3009. f"Expected to receive a 200 on accessing media: {server_and_media_id}"
  3010. ),
  3011. )
  3012. return media_id
  3013. def _check_fields(self, content: List[JsonDict]) -> None:
  3014. """Checks that the expected user attributes are present in content
  3015. Args:
  3016. content: List that is checked for content
  3017. """
  3018. for m in content:
  3019. self.assertIn("media_id", m)
  3020. self.assertIn("media_type", m)
  3021. self.assertIn("media_length", m)
  3022. self.assertIn("upload_name", m)
  3023. self.assertIn("created_ts", m)
  3024. self.assertIn("last_access_ts", m)
  3025. self.assertIn("quarantined_by", m)
  3026. self.assertIn("safe_from_quarantine", m)
  3027. def _order_test(
  3028. self,
  3029. expected_media_list: List[str],
  3030. order_by: Optional[str],
  3031. dir: Optional[str] = None,
  3032. ) -> None:
  3033. """Request the list of media in a certain order. Assert that order is what
  3034. we expect
  3035. Args:
  3036. expected_media_list: The list of media_ids in the order we expect to get
  3037. back from the server
  3038. order_by: The type of ordering to give the server
  3039. dir: The direction of ordering to give the server
  3040. """
  3041. url = self.url + "?"
  3042. if order_by is not None:
  3043. url += f"order_by={order_by}&"
  3044. if dir is not None and dir in ("b", "f"):
  3045. url += f"dir={dir}"
  3046. channel = self.make_request(
  3047. "GET",
  3048. url,
  3049. access_token=self.admin_user_tok,
  3050. )
  3051. self.assertEqual(200, channel.code, msg=channel.json_body)
  3052. self.assertEqual(channel.json_body["total"], len(expected_media_list))
  3053. returned_order = [row["media_id"] for row in channel.json_body["media"]]
  3054. self.assertEqual(expected_media_list, returned_order)
  3055. self._check_fields(channel.json_body["media"])
  3056. class UserTokenRestTestCase(unittest.HomeserverTestCase):
  3057. """Test for /_synapse/admin/v1/users/<user>/login"""
  3058. servlets = [
  3059. synapse.rest.admin.register_servlets,
  3060. login.register_servlets,
  3061. sync.register_servlets,
  3062. room.register_servlets,
  3063. devices.register_servlets,
  3064. logout.register_servlets,
  3065. ]
  3066. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3067. self.store = hs.get_datastores().main
  3068. self.admin_user = self.register_user("admin", "pass", admin=True)
  3069. self.admin_user_tok = self.login("admin", "pass")
  3070. self.other_user = self.register_user("user", "pass")
  3071. self.other_user_tok = self.login("user", "pass")
  3072. self.url = "/_synapse/admin/v1/users/%s/login" % urllib.parse.quote(
  3073. self.other_user
  3074. )
  3075. def _get_token(self) -> str:
  3076. channel = self.make_request(
  3077. "POST", self.url, b"{}", access_token=self.admin_user_tok
  3078. )
  3079. self.assertEqual(200, channel.code, msg=channel.json_body)
  3080. return channel.json_body["access_token"]
  3081. def test_no_auth(self) -> None:
  3082. """Try to login as a user without authentication."""
  3083. channel = self.make_request("POST", self.url, b"{}")
  3084. self.assertEqual(401, channel.code, msg=channel.json_body)
  3085. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3086. def test_not_admin(self) -> None:
  3087. """Try to login as a user as a non-admin user."""
  3088. channel = self.make_request(
  3089. "POST", self.url, b"{}", access_token=self.other_user_tok
  3090. )
  3091. self.assertEqual(403, channel.code, msg=channel.json_body)
  3092. def test_send_event(self) -> None:
  3093. """Test that sending event as a user works."""
  3094. # Create a room.
  3095. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  3096. # Login in as the user
  3097. puppet_token = self._get_token()
  3098. # Test that sending works, and generates the event as the right user.
  3099. resp = self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  3100. event_id = resp["event_id"]
  3101. event = self.get_success(self.store.get_event(event_id))
  3102. self.assertEqual(event.sender, self.other_user)
  3103. def test_devices(self) -> None:
  3104. """Tests that logging in as a user doesn't create a new device for them."""
  3105. # Login in as the user
  3106. self._get_token()
  3107. # Check that we don't see a new device in our devices list
  3108. channel = self.make_request(
  3109. "GET", "devices", b"{}", access_token=self.other_user_tok
  3110. )
  3111. self.assertEqual(200, channel.code, msg=channel.json_body)
  3112. # We should only see the one device (from the login in `prepare`)
  3113. self.assertEqual(len(channel.json_body["devices"]), 1)
  3114. def test_logout(self) -> None:
  3115. """Test that calling `/logout` with the token works."""
  3116. # Login in as the user
  3117. puppet_token = self._get_token()
  3118. # Test that we can successfully make a request
  3119. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3120. self.assertEqual(200, channel.code, msg=channel.json_body)
  3121. # Logout with the puppet token
  3122. channel = self.make_request("POST", "logout", b"{}", access_token=puppet_token)
  3123. self.assertEqual(200, channel.code, msg=channel.json_body)
  3124. # The puppet token should no longer work
  3125. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3126. self.assertEqual(401, channel.code, msg=channel.json_body)
  3127. # .. but the real user's tokens should still work
  3128. channel = self.make_request(
  3129. "GET", "devices", b"{}", access_token=self.other_user_tok
  3130. )
  3131. self.assertEqual(200, channel.code, msg=channel.json_body)
  3132. def test_user_logout_all(self) -> None:
  3133. """Tests that the target user calling `/logout/all` does *not* expire
  3134. the token.
  3135. """
  3136. # Login in as the user
  3137. puppet_token = self._get_token()
  3138. # Test that we can successfully make a request
  3139. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3140. self.assertEqual(200, channel.code, msg=channel.json_body)
  3141. # Logout all with the real user token
  3142. channel = self.make_request(
  3143. "POST", "logout/all", b"{}", access_token=self.other_user_tok
  3144. )
  3145. self.assertEqual(200, channel.code, msg=channel.json_body)
  3146. # The puppet token should still work
  3147. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3148. self.assertEqual(200, channel.code, msg=channel.json_body)
  3149. # .. but the real user's tokens shouldn't
  3150. channel = self.make_request(
  3151. "GET", "devices", b"{}", access_token=self.other_user_tok
  3152. )
  3153. self.assertEqual(401, channel.code, msg=channel.json_body)
  3154. def test_admin_logout_all(self) -> None:
  3155. """Tests that the admin user calling `/logout/all` does expire the
  3156. token.
  3157. """
  3158. # Login in as the user
  3159. puppet_token = self._get_token()
  3160. # Test that we can successfully make a request
  3161. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3162. self.assertEqual(200, channel.code, msg=channel.json_body)
  3163. # Logout all with the admin user token
  3164. channel = self.make_request(
  3165. "POST", "logout/all", b"{}", access_token=self.admin_user_tok
  3166. )
  3167. self.assertEqual(200, channel.code, msg=channel.json_body)
  3168. # The puppet token should no longer work
  3169. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3170. self.assertEqual(401, channel.code, msg=channel.json_body)
  3171. # .. but the real user's tokens should still work
  3172. channel = self.make_request(
  3173. "GET", "devices", b"{}", access_token=self.other_user_tok
  3174. )
  3175. self.assertEqual(200, channel.code, msg=channel.json_body)
  3176. @unittest.override_config(
  3177. {
  3178. "public_baseurl": "https://example.org/",
  3179. "user_consent": {
  3180. "version": "1.0",
  3181. "policy_name": "My Cool Privacy Policy",
  3182. "template_dir": "/",
  3183. "require_at_registration": True,
  3184. "block_events_error": "You should accept the policy",
  3185. },
  3186. "form_secret": "123secret",
  3187. }
  3188. )
  3189. def test_consent(self) -> None:
  3190. """Test that sending a message is not subject to the privacy policies."""
  3191. # Have the admin user accept the terms.
  3192. self.get_success(self.store.user_set_consent_version(self.admin_user, "1.0"))
  3193. # First, cheekily accept the terms and create a room
  3194. self.get_success(self.store.user_set_consent_version(self.other_user, "1.0"))
  3195. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  3196. self.helper.send_event(room_id, "com.example.test", tok=self.other_user_tok)
  3197. # Now unaccept it and check that we can't send an event
  3198. self.get_success(self.store.user_set_consent_version(self.other_user, "0.0"))
  3199. self.helper.send_event(
  3200. room_id,
  3201. "com.example.test",
  3202. tok=self.other_user_tok,
  3203. expect_code=403,
  3204. )
  3205. # Login in as the user
  3206. puppet_token = self._get_token()
  3207. # Sending an event on their behalf should work fine
  3208. self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  3209. @override_config(
  3210. {"limit_usage_by_mau": True, "max_mau_value": 1, "mau_trial_days": 0}
  3211. )
  3212. def test_mau_limit(self) -> None:
  3213. # Create a room as the admin user. This will bump the monthly active users to 1.
  3214. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  3215. # Trying to join as the other user should fail due to reaching MAU limit.
  3216. self.helper.join(
  3217. room_id,
  3218. user=self.other_user,
  3219. tok=self.other_user_tok,
  3220. expect_code=403,
  3221. )
  3222. # Logging in as the other user and joining a room should work, even
  3223. # though the MAU limit would stop the user doing so.
  3224. puppet_token = self._get_token()
  3225. self.helper.join(room_id, user=self.other_user, tok=puppet_token)
  3226. @parameterized_class(
  3227. ("url_prefix",),
  3228. [
  3229. ("/_synapse/admin/v1/whois/%s",),
  3230. ("/_matrix/client/r0/admin/whois/%s",),
  3231. ],
  3232. )
  3233. class WhoisRestTestCase(unittest.HomeserverTestCase):
  3234. servlets = [
  3235. synapse.rest.admin.register_servlets,
  3236. login.register_servlets,
  3237. ]
  3238. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3239. self.admin_user = self.register_user("admin", "pass", admin=True)
  3240. self.admin_user_tok = self.login("admin", "pass")
  3241. self.other_user = self.register_user("user", "pass")
  3242. self.url = self.url_prefix % self.other_user # type: ignore[attr-defined]
  3243. def test_no_auth(self) -> None:
  3244. """
  3245. Try to get information of an user without authentication.
  3246. """
  3247. channel = self.make_request("GET", self.url, b"{}")
  3248. self.assertEqual(401, channel.code, msg=channel.json_body)
  3249. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3250. def test_requester_is_not_admin(self) -> None:
  3251. """
  3252. If the user is not a server admin, an error is returned.
  3253. """
  3254. self.register_user("user2", "pass")
  3255. other_user2_token = self.login("user2", "pass")
  3256. channel = self.make_request(
  3257. "GET",
  3258. self.url,
  3259. access_token=other_user2_token,
  3260. )
  3261. self.assertEqual(403, channel.code, msg=channel.json_body)
  3262. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  3263. def test_user_is_not_local(self) -> None:
  3264. """
  3265. Tests that a lookup for a user that is not a local returns a 400
  3266. """
  3267. url = self.url_prefix % "@unknown_person:unknown_domain" # type: ignore[attr-defined]
  3268. channel = self.make_request(
  3269. "GET",
  3270. url,
  3271. access_token=self.admin_user_tok,
  3272. )
  3273. self.assertEqual(400, channel.code, msg=channel.json_body)
  3274. self.assertEqual("Can only whois a local user", channel.json_body["error"])
  3275. def test_get_whois_admin(self) -> None:
  3276. """
  3277. The lookup should succeed for an admin.
  3278. """
  3279. channel = self.make_request(
  3280. "GET",
  3281. self.url,
  3282. access_token=self.admin_user_tok,
  3283. )
  3284. self.assertEqual(200, channel.code, msg=channel.json_body)
  3285. self.assertEqual(self.other_user, channel.json_body["user_id"])
  3286. self.assertIn("devices", channel.json_body)
  3287. def test_get_whois_user(self) -> None:
  3288. """
  3289. The lookup should succeed for a normal user looking up their own information.
  3290. """
  3291. other_user_token = self.login("user", "pass")
  3292. channel = self.make_request(
  3293. "GET",
  3294. self.url,
  3295. access_token=other_user_token,
  3296. )
  3297. self.assertEqual(200, channel.code, msg=channel.json_body)
  3298. self.assertEqual(self.other_user, channel.json_body["user_id"])
  3299. self.assertIn("devices", channel.json_body)
  3300. class ShadowBanRestTestCase(unittest.HomeserverTestCase):
  3301. servlets = [
  3302. synapse.rest.admin.register_servlets,
  3303. login.register_servlets,
  3304. ]
  3305. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3306. self.store = hs.get_datastores().main
  3307. self.admin_user = self.register_user("admin", "pass", admin=True)
  3308. self.admin_user_tok = self.login("admin", "pass")
  3309. self.other_user = self.register_user("user", "pass")
  3310. self.url = "/_synapse/admin/v1/users/%s/shadow_ban" % urllib.parse.quote(
  3311. self.other_user
  3312. )
  3313. @parameterized.expand(["POST", "DELETE"])
  3314. def test_no_auth(self, method: str) -> None:
  3315. """
  3316. Try to get information of an user without authentication.
  3317. """
  3318. channel = self.make_request(method, self.url)
  3319. self.assertEqual(401, channel.code, msg=channel.json_body)
  3320. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3321. @parameterized.expand(["POST", "DELETE"])
  3322. def test_requester_is_not_admin(self, method: str) -> None:
  3323. """
  3324. If the user is not a server admin, an error is returned.
  3325. """
  3326. other_user_token = self.login("user", "pass")
  3327. channel = self.make_request(method, self.url, access_token=other_user_token)
  3328. self.assertEqual(403, channel.code, msg=channel.json_body)
  3329. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  3330. @parameterized.expand(["POST", "DELETE"])
  3331. def test_user_is_not_local(self, method: str) -> None:
  3332. """
  3333. Tests that shadow-banning for a user that is not a local returns a 400
  3334. """
  3335. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/shadow_ban"
  3336. channel = self.make_request(method, url, access_token=self.admin_user_tok)
  3337. self.assertEqual(400, channel.code, msg=channel.json_body)
  3338. def test_success(self) -> None:
  3339. """
  3340. Shadow-banning should succeed for an admin.
  3341. """
  3342. # The user starts off as not shadow-banned.
  3343. other_user_token = self.login("user", "pass")
  3344. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  3345. assert result is not None
  3346. self.assertFalse(result.shadow_banned)
  3347. channel = self.make_request("POST", self.url, access_token=self.admin_user_tok)
  3348. self.assertEqual(200, channel.code, msg=channel.json_body)
  3349. self.assertEqual({}, channel.json_body)
  3350. # Ensure the user is shadow-banned (and the cache was cleared).
  3351. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  3352. assert result is not None
  3353. self.assertTrue(result.shadow_banned)
  3354. # Un-shadow-ban the user.
  3355. channel = self.make_request(
  3356. "DELETE", self.url, access_token=self.admin_user_tok
  3357. )
  3358. self.assertEqual(200, channel.code, msg=channel.json_body)
  3359. self.assertEqual({}, channel.json_body)
  3360. # Ensure the user is no longer shadow-banned (and the cache was cleared).
  3361. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  3362. assert result is not None
  3363. self.assertFalse(result.shadow_banned)
  3364. class RateLimitTestCase(unittest.HomeserverTestCase):
  3365. servlets = [
  3366. synapse.rest.admin.register_servlets,
  3367. login.register_servlets,
  3368. ]
  3369. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3370. self.store = hs.get_datastores().main
  3371. self.admin_user = self.register_user("admin", "pass", admin=True)
  3372. self.admin_user_tok = self.login("admin", "pass")
  3373. self.other_user = self.register_user("user", "pass")
  3374. self.url = (
  3375. "/_synapse/admin/v1/users/%s/override_ratelimit"
  3376. % urllib.parse.quote(self.other_user)
  3377. )
  3378. @parameterized.expand(["GET", "POST", "DELETE"])
  3379. def test_no_auth(self, method: str) -> None:
  3380. """
  3381. Try to get information of a user without authentication.
  3382. """
  3383. channel = self.make_request(method, self.url, b"{}")
  3384. self.assertEqual(401, channel.code, msg=channel.json_body)
  3385. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3386. @parameterized.expand(["GET", "POST", "DELETE"])
  3387. def test_requester_is_no_admin(self, method: str) -> None:
  3388. """
  3389. If the user is not a server admin, an error is returned.
  3390. """
  3391. other_user_token = self.login("user", "pass")
  3392. channel = self.make_request(
  3393. method,
  3394. self.url,
  3395. access_token=other_user_token,
  3396. )
  3397. self.assertEqual(403, channel.code, msg=channel.json_body)
  3398. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  3399. @parameterized.expand(["GET", "POST", "DELETE"])
  3400. def test_user_does_not_exist(self, method: str) -> None:
  3401. """
  3402. Tests that a lookup for a user that does not exist returns a 404
  3403. """
  3404. url = "/_synapse/admin/v1/users/@unknown_person:test/override_ratelimit"
  3405. channel = self.make_request(
  3406. method,
  3407. url,
  3408. access_token=self.admin_user_tok,
  3409. )
  3410. self.assertEqual(404, channel.code, msg=channel.json_body)
  3411. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3412. @parameterized.expand(
  3413. [
  3414. ("GET", "Can only look up local users"),
  3415. ("POST", "Only local users can be ratelimited"),
  3416. ("DELETE", "Only local users can be ratelimited"),
  3417. ]
  3418. )
  3419. def test_user_is_not_local(self, method: str, error_msg: str) -> None:
  3420. """
  3421. Tests that a lookup for a user that is not a local returns a 400
  3422. """
  3423. url = (
  3424. "/_synapse/admin/v1/users/@unknown_person:unknown_domain/override_ratelimit"
  3425. )
  3426. channel = self.make_request(
  3427. method,
  3428. url,
  3429. access_token=self.admin_user_tok,
  3430. )
  3431. self.assertEqual(400, channel.code, msg=channel.json_body)
  3432. self.assertEqual(error_msg, channel.json_body["error"])
  3433. def test_invalid_parameter(self) -> None:
  3434. """
  3435. If parameters are invalid, an error is returned.
  3436. """
  3437. # messages_per_second is a string
  3438. channel = self.make_request(
  3439. "POST",
  3440. self.url,
  3441. access_token=self.admin_user_tok,
  3442. content={"messages_per_second": "string"},
  3443. )
  3444. self.assertEqual(400, channel.code, msg=channel.json_body)
  3445. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3446. # messages_per_second is negative
  3447. channel = self.make_request(
  3448. "POST",
  3449. self.url,
  3450. access_token=self.admin_user_tok,
  3451. content={"messages_per_second": -1},
  3452. )
  3453. self.assertEqual(400, channel.code, msg=channel.json_body)
  3454. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3455. # burst_count is a string
  3456. channel = self.make_request(
  3457. "POST",
  3458. self.url,
  3459. access_token=self.admin_user_tok,
  3460. content={"burst_count": "string"},
  3461. )
  3462. self.assertEqual(400, channel.code, msg=channel.json_body)
  3463. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3464. # burst_count is negative
  3465. channel = self.make_request(
  3466. "POST",
  3467. self.url,
  3468. access_token=self.admin_user_tok,
  3469. content={"burst_count": -1},
  3470. )
  3471. self.assertEqual(400, channel.code, msg=channel.json_body)
  3472. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3473. def test_return_zero_when_null(self) -> None:
  3474. """
  3475. If values in database are `null` API should return an int `0`
  3476. """
  3477. self.get_success(
  3478. self.store.db_pool.simple_upsert(
  3479. table="ratelimit_override",
  3480. keyvalues={"user_id": self.other_user},
  3481. values={
  3482. "messages_per_second": None,
  3483. "burst_count": None,
  3484. },
  3485. )
  3486. )
  3487. # request status
  3488. channel = self.make_request(
  3489. "GET",
  3490. self.url,
  3491. access_token=self.admin_user_tok,
  3492. )
  3493. self.assertEqual(200, channel.code, msg=channel.json_body)
  3494. self.assertEqual(0, channel.json_body["messages_per_second"])
  3495. self.assertEqual(0, channel.json_body["burst_count"])
  3496. def test_success(self) -> None:
  3497. """
  3498. Rate-limiting (set/update/delete) should succeed for an admin.
  3499. """
  3500. # request status
  3501. channel = self.make_request(
  3502. "GET",
  3503. self.url,
  3504. access_token=self.admin_user_tok,
  3505. )
  3506. self.assertEqual(200, channel.code, msg=channel.json_body)
  3507. self.assertNotIn("messages_per_second", channel.json_body)
  3508. self.assertNotIn("burst_count", channel.json_body)
  3509. # set ratelimit
  3510. channel = self.make_request(
  3511. "POST",
  3512. self.url,
  3513. access_token=self.admin_user_tok,
  3514. content={"messages_per_second": 10, "burst_count": 11},
  3515. )
  3516. self.assertEqual(200, channel.code, msg=channel.json_body)
  3517. self.assertEqual(10, channel.json_body["messages_per_second"])
  3518. self.assertEqual(11, channel.json_body["burst_count"])
  3519. # update ratelimit
  3520. channel = self.make_request(
  3521. "POST",
  3522. self.url,
  3523. access_token=self.admin_user_tok,
  3524. content={"messages_per_second": 20, "burst_count": 21},
  3525. )
  3526. self.assertEqual(200, channel.code, msg=channel.json_body)
  3527. self.assertEqual(20, channel.json_body["messages_per_second"])
  3528. self.assertEqual(21, channel.json_body["burst_count"])
  3529. # request status
  3530. channel = self.make_request(
  3531. "GET",
  3532. self.url,
  3533. access_token=self.admin_user_tok,
  3534. )
  3535. self.assertEqual(200, channel.code, msg=channel.json_body)
  3536. self.assertEqual(20, channel.json_body["messages_per_second"])
  3537. self.assertEqual(21, channel.json_body["burst_count"])
  3538. # delete ratelimit
  3539. channel = self.make_request(
  3540. "DELETE",
  3541. self.url,
  3542. access_token=self.admin_user_tok,
  3543. )
  3544. self.assertEqual(200, channel.code, msg=channel.json_body)
  3545. self.assertNotIn("messages_per_second", channel.json_body)
  3546. self.assertNotIn("burst_count", channel.json_body)
  3547. # request status
  3548. channel = self.make_request(
  3549. "GET",
  3550. self.url,
  3551. access_token=self.admin_user_tok,
  3552. )
  3553. self.assertEqual(200, channel.code, msg=channel.json_body)
  3554. self.assertNotIn("messages_per_second", channel.json_body)
  3555. self.assertNotIn("burst_count", channel.json_body)
  3556. class AccountDataTestCase(unittest.HomeserverTestCase):
  3557. servlets = [
  3558. synapse.rest.admin.register_servlets,
  3559. login.register_servlets,
  3560. ]
  3561. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3562. self.store = hs.get_datastores().main
  3563. self.admin_user = self.register_user("admin", "pass", admin=True)
  3564. self.admin_user_tok = self.login("admin", "pass")
  3565. self.other_user = self.register_user("user", "pass")
  3566. self.url = f"/_synapse/admin/v1/users/{self.other_user}/accountdata"
  3567. def test_no_auth(self) -> None:
  3568. """Try to get information of a user without authentication."""
  3569. channel = self.make_request("GET", self.url, {})
  3570. self.assertEqual(401, channel.code, msg=channel.json_body)
  3571. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3572. def test_requester_is_no_admin(self) -> None:
  3573. """If the user is not a server admin, an error is returned."""
  3574. other_user_token = self.login("user", "pass")
  3575. channel = self.make_request(
  3576. "GET",
  3577. self.url,
  3578. access_token=other_user_token,
  3579. )
  3580. self.assertEqual(403, channel.code, msg=channel.json_body)
  3581. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  3582. def test_user_does_not_exist(self) -> None:
  3583. """Tests that a lookup for a user that does not exist returns a 404"""
  3584. url = "/_synapse/admin/v1/users/@unknown_person:test/override_ratelimit"
  3585. channel = self.make_request(
  3586. "GET",
  3587. url,
  3588. access_token=self.admin_user_tok,
  3589. )
  3590. self.assertEqual(404, channel.code, msg=channel.json_body)
  3591. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3592. def test_user_is_not_local(self) -> None:
  3593. """Tests that a lookup for a user that is not a local returns a 400"""
  3594. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/accountdata"
  3595. channel = self.make_request(
  3596. "GET",
  3597. url,
  3598. access_token=self.admin_user_tok,
  3599. )
  3600. self.assertEqual(400, channel.code, msg=channel.json_body)
  3601. self.assertEqual("Can only look up local users", channel.json_body["error"])
  3602. def test_success(self) -> None:
  3603. """Request account data should succeed for an admin."""
  3604. # add account data
  3605. self.get_success(
  3606. self.store.add_account_data_for_user(self.other_user, "m.global", {"a": 1})
  3607. )
  3608. self.get_success(
  3609. self.store.add_account_data_to_room(
  3610. self.other_user, "test_room", "m.per_room", {"b": 2}
  3611. )
  3612. )
  3613. channel = self.make_request(
  3614. "GET",
  3615. self.url,
  3616. access_token=self.admin_user_tok,
  3617. )
  3618. self.assertEqual(200, channel.code, msg=channel.json_body)
  3619. self.assertEqual(
  3620. {"a": 1}, channel.json_body["account_data"]["global"]["m.global"]
  3621. )
  3622. self.assertEqual(
  3623. {"b": 2},
  3624. channel.json_body["account_data"]["rooms"]["test_room"]["m.per_room"],
  3625. )
  3626. class UsersByExternalIdTestCase(unittest.HomeserverTestCase):
  3627. servlets = [
  3628. synapse.rest.admin.register_servlets,
  3629. login.register_servlets,
  3630. ]
  3631. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3632. self.store = hs.get_datastores().main
  3633. self.admin_user = self.register_user("admin", "pass", admin=True)
  3634. self.admin_user_tok = self.login("admin", "pass")
  3635. self.other_user = self.register_user("user", "pass")
  3636. self.get_success(
  3637. self.store.record_user_external_id(
  3638. "the-auth-provider", "the-external-id", self.other_user
  3639. )
  3640. )
  3641. self.get_success(
  3642. self.store.record_user_external_id(
  3643. "another-auth-provider", "a:complex@external/id", self.other_user
  3644. )
  3645. )
  3646. def test_no_auth(self) -> None:
  3647. """Try to lookup a user without authentication."""
  3648. url = (
  3649. "/_synapse/admin/v1/auth_providers/the-auth-provider/users/the-external-id"
  3650. )
  3651. channel = self.make_request(
  3652. "GET",
  3653. url,
  3654. )
  3655. self.assertEqual(401, channel.code, msg=channel.json_body)
  3656. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3657. def test_binding_does_not_exist(self) -> None:
  3658. """Tests that a lookup for an external ID that does not exist returns a 404"""
  3659. url = "/_synapse/admin/v1/auth_providers/the-auth-provider/users/unknown-id"
  3660. channel = self.make_request(
  3661. "GET",
  3662. url,
  3663. access_token=self.admin_user_tok,
  3664. )
  3665. self.assertEqual(404, channel.code, msg=channel.json_body)
  3666. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3667. def test_success(self) -> None:
  3668. """Tests a successful external ID lookup"""
  3669. url = (
  3670. "/_synapse/admin/v1/auth_providers/the-auth-provider/users/the-external-id"
  3671. )
  3672. channel = self.make_request(
  3673. "GET",
  3674. url,
  3675. access_token=self.admin_user_tok,
  3676. )
  3677. self.assertEqual(200, channel.code, msg=channel.json_body)
  3678. self.assertEqual(
  3679. {"user_id": self.other_user},
  3680. channel.json_body,
  3681. )
  3682. def test_success_urlencoded(self) -> None:
  3683. """Tests a successful external ID lookup with an url-encoded ID"""
  3684. url = "/_synapse/admin/v1/auth_providers/another-auth-provider/users/a%3Acomplex%40external%2Fid"
  3685. channel = self.make_request(
  3686. "GET",
  3687. url,
  3688. access_token=self.admin_user_tok,
  3689. )
  3690. self.assertEqual(200, channel.code, msg=channel.json_body)
  3691. self.assertEqual(
  3692. {"user_id": self.other_user},
  3693. channel.json_body,
  3694. )
  3695. class UsersByThreePidTestCase(unittest.HomeserverTestCase):
  3696. servlets = [
  3697. synapse.rest.admin.register_servlets,
  3698. login.register_servlets,
  3699. ]
  3700. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3701. self.store = hs.get_datastores().main
  3702. self.admin_user = self.register_user("admin", "pass", admin=True)
  3703. self.admin_user_tok = self.login("admin", "pass")
  3704. self.other_user = self.register_user("user", "pass")
  3705. self.get_success(
  3706. self.store.user_add_threepid(
  3707. self.other_user, "email", "user@email.com", 1, 1
  3708. )
  3709. )
  3710. self.get_success(
  3711. self.store.user_add_threepid(self.other_user, "msidn", "+1-12345678", 1, 1)
  3712. )
  3713. def test_no_auth(self) -> None:
  3714. """Try to look up a user without authentication."""
  3715. url = "/_synapse/admin/v1/threepid/email/users/user%40email.com"
  3716. channel = self.make_request(
  3717. "GET",
  3718. url,
  3719. )
  3720. self.assertEqual(401, channel.code, msg=channel.json_body)
  3721. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3722. def test_medium_does_not_exist(self) -> None:
  3723. """Tests that both a lookup for a medium that does not exist and a user that
  3724. doesn't exist with that third party ID returns a 404"""
  3725. # test for unknown medium
  3726. url = "/_synapse/admin/v1/threepid/publickey/users/unknown-key"
  3727. channel = self.make_request(
  3728. "GET",
  3729. url,
  3730. access_token=self.admin_user_tok,
  3731. )
  3732. self.assertEqual(404, channel.code, msg=channel.json_body)
  3733. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3734. # test for unknown user with a known medium
  3735. url = "/_synapse/admin/v1/threepid/email/users/unknown"
  3736. channel = self.make_request(
  3737. "GET",
  3738. url,
  3739. access_token=self.admin_user_tok,
  3740. )
  3741. self.assertEqual(404, channel.code, msg=channel.json_body)
  3742. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3743. def test_success(self) -> None:
  3744. """Tests a successful medium + address lookup"""
  3745. # test for email medium with encoded value of user@email.com
  3746. url = "/_synapse/admin/v1/threepid/email/users/user%40email.com"
  3747. channel = self.make_request(
  3748. "GET",
  3749. url,
  3750. access_token=self.admin_user_tok,
  3751. )
  3752. self.assertEqual(200, channel.code, msg=channel.json_body)
  3753. self.assertEqual(
  3754. {"user_id": self.other_user},
  3755. channel.json_body,
  3756. )
  3757. # test for msidn medium with encoded value of +1-12345678
  3758. url = "/_synapse/admin/v1/threepid/msidn/users/%2B1-12345678"
  3759. channel = self.make_request(
  3760. "GET",
  3761. url,
  3762. access_token=self.admin_user_tok,
  3763. )
  3764. self.assertEqual(200, channel.code, msg=channel.json_body)
  3765. self.assertEqual(
  3766. {"user_id": self.other_user},
  3767. channel.json_body,
  3768. )