test_user.py 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296
  1. # Copyright 2018 New Vector Ltd
  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 json
  17. import urllib.parse
  18. from binascii import unhexlify
  19. from typing import List, Optional
  20. from unittest.mock import Mock
  21. import synapse.rest.admin
  22. from synapse.api.constants import UserTypes
  23. from synapse.api.errors import Codes, HttpResponseException, ResourceLimitError
  24. from synapse.api.room_versions import RoomVersions
  25. from synapse.rest.client.v1 import login, logout, profile, room
  26. from synapse.rest.client.v2_alpha import devices, sync
  27. from synapse.types import JsonDict, UserID
  28. from tests import unittest
  29. from tests.server import FakeSite, make_request
  30. from tests.test_utils import make_awaitable
  31. from tests.unittest import override_config
  32. class UserRegisterTestCase(unittest.HomeserverTestCase):
  33. servlets = [
  34. synapse.rest.admin.register_servlets_for_client_rest_resource,
  35. profile.register_servlets,
  36. ]
  37. def make_homeserver(self, reactor, clock):
  38. self.url = "/_synapse/admin/v1/register"
  39. self.registration_handler = Mock()
  40. self.identity_handler = Mock()
  41. self.login_handler = Mock()
  42. self.device_handler = Mock()
  43. self.device_handler.check_device_registered = Mock(return_value="FAKE")
  44. self.datastore = Mock(return_value=Mock())
  45. self.datastore.get_current_state_deltas = Mock(return_value=(0, []))
  46. self.secrets = Mock()
  47. self.hs = self.setup_test_homeserver()
  48. self.hs.config.registration_shared_secret = "shared"
  49. self.hs.get_media_repository = Mock()
  50. self.hs.get_deactivate_account_handler = Mock()
  51. return self.hs
  52. def test_disabled(self):
  53. """
  54. If there is no shared secret, registration through this method will be
  55. prevented.
  56. """
  57. self.hs.config.registration_shared_secret = None
  58. channel = self.make_request("POST", self.url, b"{}")
  59. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  60. self.assertEqual(
  61. "Shared secret registration is not enabled", channel.json_body["error"]
  62. )
  63. def test_get_nonce(self):
  64. """
  65. Calling GET on the endpoint will return a randomised nonce, using the
  66. homeserver's secrets provider.
  67. """
  68. secrets = Mock()
  69. secrets.token_hex = Mock(return_value="abcd")
  70. self.hs.get_secrets = Mock(return_value=secrets)
  71. channel = self.make_request("GET", self.url)
  72. self.assertEqual(channel.json_body, {"nonce": "abcd"})
  73. def test_expired_nonce(self):
  74. """
  75. Calling GET on the endpoint will return a randomised nonce, which will
  76. only last for SALT_TIMEOUT (60s).
  77. """
  78. channel = self.make_request("GET", self.url)
  79. nonce = channel.json_body["nonce"]
  80. # 59 seconds
  81. self.reactor.advance(59)
  82. body = json.dumps({"nonce": nonce})
  83. channel = self.make_request("POST", self.url, body.encode("utf8"))
  84. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  85. self.assertEqual("username must be specified", channel.json_body["error"])
  86. # 61 seconds
  87. self.reactor.advance(2)
  88. channel = self.make_request("POST", self.url, body.encode("utf8"))
  89. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  90. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  91. def test_register_incorrect_nonce(self):
  92. """
  93. Only the provided nonce can be used, as it's checked in the MAC.
  94. """
  95. channel = self.make_request("GET", self.url)
  96. nonce = channel.json_body["nonce"]
  97. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  98. want_mac.update(b"notthenonce\x00bob\x00abc123\x00admin")
  99. want_mac = want_mac.hexdigest()
  100. body = json.dumps(
  101. {
  102. "nonce": nonce,
  103. "username": "bob",
  104. "password": "abc123",
  105. "admin": True,
  106. "mac": want_mac,
  107. }
  108. )
  109. channel = self.make_request("POST", self.url, body.encode("utf8"))
  110. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  111. self.assertEqual("HMAC incorrect", channel.json_body["error"])
  112. def test_register_correct_nonce(self):
  113. """
  114. When the correct nonce is provided, and the right key is provided, the
  115. user is registered.
  116. """
  117. channel = self.make_request("GET", self.url)
  118. nonce = channel.json_body["nonce"]
  119. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  120. want_mac.update(
  121. nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin\x00support"
  122. )
  123. want_mac = want_mac.hexdigest()
  124. body = json.dumps(
  125. {
  126. "nonce": nonce,
  127. "username": "bob",
  128. "password": "abc123",
  129. "admin": True,
  130. "user_type": UserTypes.SUPPORT,
  131. "mac": want_mac,
  132. }
  133. )
  134. channel = self.make_request("POST", self.url, body.encode("utf8"))
  135. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  136. self.assertEqual("@bob:test", channel.json_body["user_id"])
  137. def test_nonce_reuse(self):
  138. """
  139. A valid unrecognised nonce.
  140. """
  141. channel = self.make_request("GET", self.url)
  142. nonce = channel.json_body["nonce"]
  143. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  144. want_mac.update(nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin")
  145. want_mac = want_mac.hexdigest()
  146. body = json.dumps(
  147. {
  148. "nonce": nonce,
  149. "username": "bob",
  150. "password": "abc123",
  151. "admin": True,
  152. "mac": want_mac,
  153. }
  154. )
  155. channel = self.make_request("POST", self.url, body.encode("utf8"))
  156. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  157. self.assertEqual("@bob:test", channel.json_body["user_id"])
  158. # Now, try and reuse it
  159. channel = self.make_request("POST", self.url, body.encode("utf8"))
  160. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  161. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  162. def test_missing_parts(self):
  163. """
  164. Synapse will complain if you don't give nonce, username, password, and
  165. mac. Admin and user_types are optional. Additional checks are done for length
  166. and type.
  167. """
  168. def nonce():
  169. channel = self.make_request("GET", self.url)
  170. return channel.json_body["nonce"]
  171. #
  172. # Nonce check
  173. #
  174. # Must be present
  175. body = json.dumps({})
  176. channel = self.make_request("POST", self.url, body.encode("utf8"))
  177. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  178. self.assertEqual("nonce must be specified", channel.json_body["error"])
  179. #
  180. # Username checks
  181. #
  182. # Must be present
  183. body = json.dumps({"nonce": nonce()})
  184. channel = self.make_request("POST", self.url, body.encode("utf8"))
  185. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  186. self.assertEqual("username must be specified", channel.json_body["error"])
  187. # Must be a string
  188. body = json.dumps({"nonce": nonce(), "username": 1234})
  189. channel = self.make_request("POST", self.url, body.encode("utf8"))
  190. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  191. self.assertEqual("Invalid username", channel.json_body["error"])
  192. # Must not have null bytes
  193. body = json.dumps({"nonce": nonce(), "username": "abcd\u0000"})
  194. channel = self.make_request("POST", self.url, body.encode("utf8"))
  195. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  196. self.assertEqual("Invalid username", channel.json_body["error"])
  197. # Must not have null bytes
  198. body = json.dumps({"nonce": nonce(), "username": "a" * 1000})
  199. channel = self.make_request("POST", self.url, body.encode("utf8"))
  200. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  201. self.assertEqual("Invalid username", channel.json_body["error"])
  202. #
  203. # Password checks
  204. #
  205. # Must be present
  206. body = json.dumps({"nonce": nonce(), "username": "a"})
  207. channel = self.make_request("POST", self.url, body.encode("utf8"))
  208. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  209. self.assertEqual("password must be specified", channel.json_body["error"])
  210. # Must be a string
  211. body = json.dumps({"nonce": nonce(), "username": "a", "password": 1234})
  212. channel = self.make_request("POST", self.url, body.encode("utf8"))
  213. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  214. self.assertEqual("Invalid password", channel.json_body["error"])
  215. # Must not have null bytes
  216. body = json.dumps({"nonce": nonce(), "username": "a", "password": "abcd\u0000"})
  217. channel = self.make_request("POST", self.url, body.encode("utf8"))
  218. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  219. self.assertEqual("Invalid password", channel.json_body["error"])
  220. # Super long
  221. body = json.dumps({"nonce": nonce(), "username": "a", "password": "A" * 1000})
  222. channel = self.make_request("POST", self.url, body.encode("utf8"))
  223. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  224. self.assertEqual("Invalid password", channel.json_body["error"])
  225. #
  226. # user_type check
  227. #
  228. # Invalid user_type
  229. body = json.dumps(
  230. {
  231. "nonce": nonce(),
  232. "username": "a",
  233. "password": "1234",
  234. "user_type": "invalid",
  235. }
  236. )
  237. channel = self.make_request("POST", self.url, body.encode("utf8"))
  238. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  239. self.assertEqual("Invalid user type", channel.json_body["error"])
  240. def test_displayname(self):
  241. """
  242. Test that displayname of new user is set
  243. """
  244. # set no displayname
  245. channel = self.make_request("GET", self.url)
  246. nonce = channel.json_body["nonce"]
  247. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  248. want_mac.update(nonce.encode("ascii") + b"\x00bob1\x00abc123\x00notadmin")
  249. want_mac = want_mac.hexdigest()
  250. body = json.dumps(
  251. {"nonce": nonce, "username": "bob1", "password": "abc123", "mac": want_mac}
  252. )
  253. channel = self.make_request("POST", self.url, body.encode("utf8"))
  254. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  255. self.assertEqual("@bob1:test", channel.json_body["user_id"])
  256. channel = self.make_request("GET", "/profile/@bob1:test/displayname")
  257. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  258. self.assertEqual("bob1", channel.json_body["displayname"])
  259. # displayname is None
  260. channel = self.make_request("GET", self.url)
  261. nonce = channel.json_body["nonce"]
  262. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  263. want_mac.update(nonce.encode("ascii") + b"\x00bob2\x00abc123\x00notadmin")
  264. want_mac = want_mac.hexdigest()
  265. body = json.dumps(
  266. {
  267. "nonce": nonce,
  268. "username": "bob2",
  269. "displayname": None,
  270. "password": "abc123",
  271. "mac": want_mac,
  272. }
  273. )
  274. channel = self.make_request("POST", self.url, body.encode("utf8"))
  275. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  276. self.assertEqual("@bob2:test", channel.json_body["user_id"])
  277. channel = self.make_request("GET", "/profile/@bob2:test/displayname")
  278. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  279. self.assertEqual("bob2", channel.json_body["displayname"])
  280. # displayname is empty
  281. channel = self.make_request("GET", self.url)
  282. nonce = channel.json_body["nonce"]
  283. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  284. want_mac.update(nonce.encode("ascii") + b"\x00bob3\x00abc123\x00notadmin")
  285. want_mac = want_mac.hexdigest()
  286. body = json.dumps(
  287. {
  288. "nonce": nonce,
  289. "username": "bob3",
  290. "displayname": "",
  291. "password": "abc123",
  292. "mac": want_mac,
  293. }
  294. )
  295. channel = self.make_request("POST", self.url, body.encode("utf8"))
  296. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  297. self.assertEqual("@bob3:test", channel.json_body["user_id"])
  298. channel = self.make_request("GET", "/profile/@bob3:test/displayname")
  299. self.assertEqual(404, int(channel.result["code"]), msg=channel.result["body"])
  300. # set displayname
  301. channel = self.make_request("GET", self.url)
  302. nonce = channel.json_body["nonce"]
  303. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  304. want_mac.update(nonce.encode("ascii") + b"\x00bob4\x00abc123\x00notadmin")
  305. want_mac = want_mac.hexdigest()
  306. body = json.dumps(
  307. {
  308. "nonce": nonce,
  309. "username": "bob4",
  310. "displayname": "Bob's Name",
  311. "password": "abc123",
  312. "mac": want_mac,
  313. }
  314. )
  315. channel = self.make_request("POST", self.url, body.encode("utf8"))
  316. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  317. self.assertEqual("@bob4:test", channel.json_body["user_id"])
  318. channel = self.make_request("GET", "/profile/@bob4:test/displayname")
  319. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  320. self.assertEqual("Bob's Name", channel.json_body["displayname"])
  321. @override_config(
  322. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  323. )
  324. def test_register_mau_limit_reached(self):
  325. """
  326. Check we can register a user via the shared secret registration API
  327. even if the MAU limit is reached.
  328. """
  329. handler = self.hs.get_registration_handler()
  330. store = self.hs.get_datastore()
  331. # Set monthly active users to the limit
  332. store.get_monthly_active_count = Mock(
  333. return_value=make_awaitable(self.hs.config.max_mau_value)
  334. )
  335. # Check that the blocking of monthly active users is working as expected
  336. # The registration of a new user fails due to the limit
  337. self.get_failure(
  338. handler.register_user(localpart="local_part"), ResourceLimitError
  339. )
  340. # Register new user with admin API
  341. channel = self.make_request("GET", self.url)
  342. nonce = channel.json_body["nonce"]
  343. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  344. want_mac.update(
  345. nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin\x00support"
  346. )
  347. want_mac = want_mac.hexdigest()
  348. body = json.dumps(
  349. {
  350. "nonce": nonce,
  351. "username": "bob",
  352. "password": "abc123",
  353. "admin": True,
  354. "user_type": UserTypes.SUPPORT,
  355. "mac": want_mac,
  356. }
  357. )
  358. channel = self.make_request("POST", self.url, body.encode("utf8"))
  359. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  360. self.assertEqual("@bob:test", channel.json_body["user_id"])
  361. class UsersListTestCase(unittest.HomeserverTestCase):
  362. servlets = [
  363. synapse.rest.admin.register_servlets,
  364. login.register_servlets,
  365. ]
  366. url = "/_synapse/admin/v2/users"
  367. def prepare(self, reactor, clock, hs):
  368. self.store = hs.get_datastore()
  369. self.admin_user = self.register_user("admin", "pass", admin=True)
  370. self.admin_user_tok = self.login("admin", "pass")
  371. def test_no_auth(self):
  372. """
  373. Try to list users without authentication.
  374. """
  375. channel = self.make_request("GET", self.url, b"{}")
  376. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  377. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  378. def test_requester_is_no_admin(self):
  379. """
  380. If the user is not a server admin, an error is returned.
  381. """
  382. self._create_users(1)
  383. other_user_token = self.login("user1", "pass1")
  384. channel = self.make_request("GET", self.url, access_token=other_user_token)
  385. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  386. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  387. def test_all_users(self):
  388. """
  389. List all users, including deactivated users.
  390. """
  391. self._create_users(2)
  392. channel = self.make_request(
  393. "GET",
  394. self.url + "?deactivated=true",
  395. b"{}",
  396. access_token=self.admin_user_tok,
  397. )
  398. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  399. self.assertEqual(3, len(channel.json_body["users"]))
  400. self.assertEqual(3, channel.json_body["total"])
  401. # Check that all fields are available
  402. self._check_fields(channel.json_body["users"])
  403. def test_search_term(self):
  404. """Test that searching for a users works correctly"""
  405. def _search_test(
  406. expected_user_id: Optional[str],
  407. search_term: str,
  408. search_field: Optional[str] = "name",
  409. expected_http_code: Optional[int] = 200,
  410. ):
  411. """Search for a user and check that the returned user's id is a match
  412. Args:
  413. expected_user_id: The user_id expected to be returned by the API. Set
  414. to None to expect zero results for the search
  415. search_term: The term to search for user names with
  416. search_field: Field which is to request: `name` or `user_id`
  417. expected_http_code: The expected http code for the request
  418. """
  419. url = self.url + "?%s=%s" % (
  420. search_field,
  421. search_term,
  422. )
  423. channel = self.make_request(
  424. "GET",
  425. url.encode("ascii"),
  426. access_token=self.admin_user_tok,
  427. )
  428. self.assertEqual(expected_http_code, channel.code, msg=channel.json_body)
  429. if expected_http_code != 200:
  430. return
  431. # Check that users were returned
  432. self.assertTrue("users" in channel.json_body)
  433. self._check_fields(channel.json_body["users"])
  434. users = channel.json_body["users"]
  435. # Check that the expected number of users were returned
  436. expected_user_count = 1 if expected_user_id else 0
  437. self.assertEqual(len(users), expected_user_count)
  438. self.assertEqual(channel.json_body["total"], expected_user_count)
  439. if expected_user_id:
  440. # Check that the first returned user id is correct
  441. u = users[0]
  442. self.assertEqual(expected_user_id, u["name"])
  443. self._create_users(2)
  444. user1 = "@user1:test"
  445. user2 = "@user2:test"
  446. # Perform search tests
  447. _search_test(user1, "er1")
  448. _search_test(user1, "me 1")
  449. _search_test(user2, "er2")
  450. _search_test(user2, "me 2")
  451. _search_test(user1, "er1", "user_id")
  452. _search_test(user2, "er2", "user_id")
  453. # Test case insensitive
  454. _search_test(user1, "ER1")
  455. _search_test(user1, "NAME 1")
  456. _search_test(user2, "ER2")
  457. _search_test(user2, "NAME 2")
  458. _search_test(user1, "ER1", "user_id")
  459. _search_test(user2, "ER2", "user_id")
  460. _search_test(None, "foo")
  461. _search_test(None, "bar")
  462. _search_test(None, "foo", "user_id")
  463. _search_test(None, "bar", "user_id")
  464. def test_invalid_parameter(self):
  465. """
  466. If parameters are invalid, an error is returned.
  467. """
  468. # negative limit
  469. channel = self.make_request(
  470. "GET",
  471. self.url + "?limit=-5",
  472. access_token=self.admin_user_tok,
  473. )
  474. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  475. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  476. # negative from
  477. channel = self.make_request(
  478. "GET",
  479. self.url + "?from=-5",
  480. access_token=self.admin_user_tok,
  481. )
  482. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  483. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  484. # invalid guests
  485. channel = self.make_request(
  486. "GET",
  487. self.url + "?guests=not_bool",
  488. access_token=self.admin_user_tok,
  489. )
  490. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  491. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  492. # invalid deactivated
  493. channel = self.make_request(
  494. "GET",
  495. self.url + "?deactivated=not_bool",
  496. access_token=self.admin_user_tok,
  497. )
  498. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  499. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  500. # unkown order_by
  501. channel = self.make_request(
  502. "GET",
  503. self.url + "?order_by=bar",
  504. access_token=self.admin_user_tok,
  505. )
  506. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  507. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  508. # invalid search order
  509. channel = self.make_request(
  510. "GET",
  511. self.url + "?dir=bar",
  512. access_token=self.admin_user_tok,
  513. )
  514. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  515. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  516. def test_limit(self):
  517. """
  518. Testing list of users with limit
  519. """
  520. number_users = 20
  521. # Create one less user (since there's already an admin user).
  522. self._create_users(number_users - 1)
  523. channel = self.make_request(
  524. "GET",
  525. self.url + "?limit=5",
  526. access_token=self.admin_user_tok,
  527. )
  528. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  529. self.assertEqual(channel.json_body["total"], number_users)
  530. self.assertEqual(len(channel.json_body["users"]), 5)
  531. self.assertEqual(channel.json_body["next_token"], "5")
  532. self._check_fields(channel.json_body["users"])
  533. def test_from(self):
  534. """
  535. Testing list of users with a defined starting point (from)
  536. """
  537. number_users = 20
  538. # Create one less user (since there's already an admin user).
  539. self._create_users(number_users - 1)
  540. channel = self.make_request(
  541. "GET",
  542. self.url + "?from=5",
  543. access_token=self.admin_user_tok,
  544. )
  545. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  546. self.assertEqual(channel.json_body["total"], number_users)
  547. self.assertEqual(len(channel.json_body["users"]), 15)
  548. self.assertNotIn("next_token", channel.json_body)
  549. self._check_fields(channel.json_body["users"])
  550. def test_limit_and_from(self):
  551. """
  552. Testing list of users with a defined starting point and limit
  553. """
  554. number_users = 20
  555. # Create one less user (since there's already an admin user).
  556. self._create_users(number_users - 1)
  557. channel = self.make_request(
  558. "GET",
  559. self.url + "?from=5&limit=10",
  560. access_token=self.admin_user_tok,
  561. )
  562. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  563. self.assertEqual(channel.json_body["total"], number_users)
  564. self.assertEqual(channel.json_body["next_token"], "15")
  565. self.assertEqual(len(channel.json_body["users"]), 10)
  566. self._check_fields(channel.json_body["users"])
  567. def test_next_token(self):
  568. """
  569. Testing that `next_token` appears at the right place
  570. """
  571. number_users = 20
  572. # Create one less user (since there's already an admin user).
  573. self._create_users(number_users - 1)
  574. # `next_token` does not appear
  575. # Number of results is the number of entries
  576. channel = self.make_request(
  577. "GET",
  578. self.url + "?limit=20",
  579. access_token=self.admin_user_tok,
  580. )
  581. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  582. self.assertEqual(channel.json_body["total"], number_users)
  583. self.assertEqual(len(channel.json_body["users"]), number_users)
  584. self.assertNotIn("next_token", channel.json_body)
  585. # `next_token` does not appear
  586. # Number of max results is larger than the number of entries
  587. channel = self.make_request(
  588. "GET",
  589. self.url + "?limit=21",
  590. access_token=self.admin_user_tok,
  591. )
  592. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  593. self.assertEqual(channel.json_body["total"], number_users)
  594. self.assertEqual(len(channel.json_body["users"]), number_users)
  595. self.assertNotIn("next_token", channel.json_body)
  596. # `next_token` does appear
  597. # Number of max results is smaller than the number of entries
  598. channel = self.make_request(
  599. "GET",
  600. self.url + "?limit=19",
  601. access_token=self.admin_user_tok,
  602. )
  603. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  604. self.assertEqual(channel.json_body["total"], number_users)
  605. self.assertEqual(len(channel.json_body["users"]), 19)
  606. self.assertEqual(channel.json_body["next_token"], "19")
  607. # Check
  608. # Set `from` to value of `next_token` for request remaining entries
  609. # `next_token` does not appear
  610. channel = self.make_request(
  611. "GET",
  612. self.url + "?from=19",
  613. access_token=self.admin_user_tok,
  614. )
  615. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  616. self.assertEqual(channel.json_body["total"], number_users)
  617. self.assertEqual(len(channel.json_body["users"]), 1)
  618. self.assertNotIn("next_token", channel.json_body)
  619. def test_order_by(self):
  620. """
  621. Testing order list with parameter `order_by`
  622. """
  623. user1 = self.register_user("user1", "pass1", admin=False, displayname="Name Z")
  624. user2 = self.register_user("user2", "pass2", admin=False, displayname="Name Y")
  625. # Modify user
  626. self.get_success(self.store.set_user_deactivated_status(user1, True))
  627. self.get_success(self.store.set_shadow_banned(UserID.from_string(user1), True))
  628. # Set avatar URL to all users, that no user has a NULL value to avoid
  629. # different sort order between SQlite and PostreSQL
  630. self.get_success(self.store.set_profile_avatar_url("user1", "mxc://url3"))
  631. self.get_success(self.store.set_profile_avatar_url("user2", "mxc://url2"))
  632. self.get_success(self.store.set_profile_avatar_url("admin", "mxc://url1"))
  633. # order by default (name)
  634. self._order_test([self.admin_user, user1, user2], None)
  635. self._order_test([self.admin_user, user1, user2], None, "f")
  636. self._order_test([user2, user1, self.admin_user], None, "b")
  637. # order by name
  638. self._order_test([self.admin_user, user1, user2], "name")
  639. self._order_test([self.admin_user, user1, user2], "name", "f")
  640. self._order_test([user2, user1, self.admin_user], "name", "b")
  641. # order by displayname
  642. self._order_test([user2, user1, self.admin_user], "displayname")
  643. self._order_test([user2, user1, self.admin_user], "displayname", "f")
  644. self._order_test([self.admin_user, user1, user2], "displayname", "b")
  645. # order by is_guest
  646. # like sort by ascending name, as no guest user here
  647. self._order_test([self.admin_user, user1, user2], "is_guest")
  648. self._order_test([self.admin_user, user1, user2], "is_guest", "f")
  649. self._order_test([self.admin_user, user1, user2], "is_guest", "b")
  650. # order by admin
  651. self._order_test([user1, user2, self.admin_user], "admin")
  652. self._order_test([user1, user2, self.admin_user], "admin", "f")
  653. self._order_test([self.admin_user, user1, user2], "admin", "b")
  654. # order by deactivated
  655. self._order_test([self.admin_user, user2, user1], "deactivated")
  656. self._order_test([self.admin_user, user2, user1], "deactivated", "f")
  657. self._order_test([user1, self.admin_user, user2], "deactivated", "b")
  658. # order by user_type
  659. # like sort by ascending name, as no special user type here
  660. self._order_test([self.admin_user, user1, user2], "user_type")
  661. self._order_test([self.admin_user, user1, user2], "user_type", "f")
  662. self._order_test([self.admin_user, user1, user2], "is_guest", "b")
  663. # order by shadow_banned
  664. self._order_test([self.admin_user, user2, user1], "shadow_banned")
  665. self._order_test([self.admin_user, user2, user1], "shadow_banned", "f")
  666. self._order_test([user1, self.admin_user, user2], "shadow_banned", "b")
  667. # order by avatar_url
  668. self._order_test([self.admin_user, user2, user1], "avatar_url")
  669. self._order_test([self.admin_user, user2, user1], "avatar_url", "f")
  670. self._order_test([user1, user2, self.admin_user], "avatar_url", "b")
  671. def _order_test(
  672. self,
  673. expected_user_list: List[str],
  674. order_by: Optional[str],
  675. dir: Optional[str] = None,
  676. ):
  677. """Request the list of users in a certain order. Assert that order is what
  678. we expect
  679. Args:
  680. expected_user_list: The list of user_id in the order we expect to get
  681. back from the server
  682. order_by: The type of ordering to give the server
  683. dir: The direction of ordering to give the server
  684. """
  685. url = self.url + "?deactivated=true&"
  686. if order_by is not None:
  687. url += "order_by=%s&" % (order_by,)
  688. if dir is not None and dir in ("b", "f"):
  689. url += "dir=%s" % (dir,)
  690. channel = self.make_request(
  691. "GET",
  692. url.encode("ascii"),
  693. access_token=self.admin_user_tok,
  694. )
  695. self.assertEqual(200, channel.code, msg=channel.json_body)
  696. self.assertEqual(channel.json_body["total"], len(expected_user_list))
  697. returned_order = [row["name"] for row in channel.json_body["users"]]
  698. self.assertEqual(expected_user_list, returned_order)
  699. self._check_fields(channel.json_body["users"])
  700. def _check_fields(self, content: JsonDict):
  701. """Checks that the expected user attributes are present in content
  702. Args:
  703. content: List that is checked for content
  704. """
  705. for u in content:
  706. self.assertIn("name", u)
  707. self.assertIn("is_guest", u)
  708. self.assertIn("admin", u)
  709. self.assertIn("user_type", u)
  710. self.assertIn("deactivated", u)
  711. self.assertIn("shadow_banned", u)
  712. self.assertIn("displayname", u)
  713. self.assertIn("avatar_url", u)
  714. def _create_users(self, number_users: int):
  715. """
  716. Create a number of users
  717. Args:
  718. number_users: Number of users to be created
  719. """
  720. for i in range(1, number_users + 1):
  721. self.register_user(
  722. "user%d" % i,
  723. "pass%d" % i,
  724. admin=False,
  725. displayname="Name %d" % i,
  726. )
  727. class DeactivateAccountTestCase(unittest.HomeserverTestCase):
  728. servlets = [
  729. synapse.rest.admin.register_servlets,
  730. login.register_servlets,
  731. ]
  732. def prepare(self, reactor, clock, hs):
  733. self.store = hs.get_datastore()
  734. self.admin_user = self.register_user("admin", "pass", admin=True)
  735. self.admin_user_tok = self.login("admin", "pass")
  736. self.other_user = self.register_user("user", "pass", displayname="User1")
  737. self.other_user_token = self.login("user", "pass")
  738. self.url_other_user = "/_synapse/admin/v2/users/%s" % urllib.parse.quote(
  739. self.other_user
  740. )
  741. self.url = "/_synapse/admin/v1/deactivate/%s" % urllib.parse.quote(
  742. self.other_user
  743. )
  744. # set attributes for user
  745. self.get_success(
  746. self.store.set_profile_avatar_url("user", "mxc://servername/mediaid")
  747. )
  748. self.get_success(
  749. self.store.user_add_threepid("@user:test", "email", "foo@bar.com", 0, 0)
  750. )
  751. def test_no_auth(self):
  752. """
  753. Try to deactivate users without authentication.
  754. """
  755. channel = self.make_request("POST", self.url, b"{}")
  756. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  757. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  758. def test_requester_is_not_admin(self):
  759. """
  760. If the user is not a server admin, an error is returned.
  761. """
  762. url = "/_synapse/admin/v1/deactivate/@bob:test"
  763. channel = self.make_request("POST", url, access_token=self.other_user_token)
  764. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  765. self.assertEqual("You are not a server admin", channel.json_body["error"])
  766. channel = self.make_request(
  767. "POST",
  768. url,
  769. access_token=self.other_user_token,
  770. content=b"{}",
  771. )
  772. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  773. self.assertEqual("You are not a server admin", channel.json_body["error"])
  774. def test_user_does_not_exist(self):
  775. """
  776. Tests that deactivation for a user that does not exist returns a 404
  777. """
  778. channel = self.make_request(
  779. "POST",
  780. "/_synapse/admin/v1/deactivate/@unknown_person:test",
  781. access_token=self.admin_user_tok,
  782. )
  783. self.assertEqual(404, channel.code, msg=channel.json_body)
  784. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  785. def test_erase_is_not_bool(self):
  786. """
  787. If parameter `erase` is not boolean, return an error
  788. """
  789. body = json.dumps({"erase": "False"})
  790. channel = self.make_request(
  791. "POST",
  792. self.url,
  793. content=body.encode(encoding="utf_8"),
  794. access_token=self.admin_user_tok,
  795. )
  796. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  797. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  798. def test_user_is_not_local(self):
  799. """
  800. Tests that deactivation for a user that is not a local returns a 400
  801. """
  802. url = "/_synapse/admin/v1/deactivate/@unknown_person:unknown_domain"
  803. channel = self.make_request("POST", url, access_token=self.admin_user_tok)
  804. self.assertEqual(400, channel.code, msg=channel.json_body)
  805. self.assertEqual("Can only deactivate local users", channel.json_body["error"])
  806. def test_deactivate_user_erase_true(self):
  807. """
  808. Test deactivating an user and set `erase` to `true`
  809. """
  810. # Get user
  811. channel = self.make_request(
  812. "GET",
  813. self.url_other_user,
  814. access_token=self.admin_user_tok,
  815. )
  816. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  817. self.assertEqual("@user:test", channel.json_body["name"])
  818. self.assertEqual(False, channel.json_body["deactivated"])
  819. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  820. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  821. self.assertEqual("User1", channel.json_body["displayname"])
  822. # Deactivate user
  823. body = json.dumps({"erase": True})
  824. channel = self.make_request(
  825. "POST",
  826. self.url,
  827. access_token=self.admin_user_tok,
  828. content=body.encode(encoding="utf_8"),
  829. )
  830. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  831. # Get user
  832. channel = self.make_request(
  833. "GET",
  834. self.url_other_user,
  835. access_token=self.admin_user_tok,
  836. )
  837. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  838. self.assertEqual("@user:test", channel.json_body["name"])
  839. self.assertEqual(True, channel.json_body["deactivated"])
  840. self.assertEqual(0, len(channel.json_body["threepids"]))
  841. self.assertIsNone(channel.json_body["avatar_url"])
  842. self.assertIsNone(channel.json_body["displayname"])
  843. self._is_erased("@user:test", True)
  844. def test_deactivate_user_erase_false(self):
  845. """
  846. Test deactivating an user and set `erase` to `false`
  847. """
  848. # Get user
  849. channel = self.make_request(
  850. "GET",
  851. self.url_other_user,
  852. access_token=self.admin_user_tok,
  853. )
  854. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  855. self.assertEqual("@user:test", channel.json_body["name"])
  856. self.assertEqual(False, channel.json_body["deactivated"])
  857. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  858. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  859. self.assertEqual("User1", channel.json_body["displayname"])
  860. # Deactivate user
  861. body = json.dumps({"erase": False})
  862. channel = self.make_request(
  863. "POST",
  864. self.url,
  865. access_token=self.admin_user_tok,
  866. content=body.encode(encoding="utf_8"),
  867. )
  868. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  869. # Get user
  870. channel = self.make_request(
  871. "GET",
  872. self.url_other_user,
  873. access_token=self.admin_user_tok,
  874. )
  875. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  876. self.assertEqual("@user:test", channel.json_body["name"])
  877. self.assertEqual(True, channel.json_body["deactivated"])
  878. self.assertEqual(0, len(channel.json_body["threepids"]))
  879. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  880. self.assertEqual("User1", channel.json_body["displayname"])
  881. self._is_erased("@user:test", False)
  882. def _is_erased(self, user_id: str, expect: bool) -> None:
  883. """Assert that the user is erased or not"""
  884. d = self.store.is_user_erased(user_id)
  885. if expect:
  886. self.assertTrue(self.get_success(d))
  887. else:
  888. self.assertFalse(self.get_success(d))
  889. class UserRestTestCase(unittest.HomeserverTestCase):
  890. servlets = [
  891. synapse.rest.admin.register_servlets,
  892. login.register_servlets,
  893. sync.register_servlets,
  894. ]
  895. def prepare(self, reactor, clock, hs):
  896. self.store = hs.get_datastore()
  897. self.auth_handler = hs.get_auth_handler()
  898. # create users and get access tokens
  899. # regardless of whether password login or SSO is allowed
  900. self.admin_user = self.register_user("admin", "pass", admin=True)
  901. self.admin_user_tok = self.get_success(
  902. self.auth_handler.get_access_token_for_user_id(
  903. self.admin_user, device_id=None, valid_until_ms=None
  904. )
  905. )
  906. self.other_user = self.register_user("user", "pass", displayname="User")
  907. self.other_user_token = self.get_success(
  908. self.auth_handler.get_access_token_for_user_id(
  909. self.other_user, device_id=None, valid_until_ms=None
  910. )
  911. )
  912. self.url_other_user = "/_synapse/admin/v2/users/%s" % urllib.parse.quote(
  913. self.other_user
  914. )
  915. def test_requester_is_no_admin(self):
  916. """
  917. If the user is not a server admin, an error is returned.
  918. """
  919. url = "/_synapse/admin/v2/users/@bob:test"
  920. channel = self.make_request(
  921. "GET",
  922. url,
  923. access_token=self.other_user_token,
  924. )
  925. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  926. self.assertEqual("You are not a server admin", channel.json_body["error"])
  927. channel = self.make_request(
  928. "PUT",
  929. url,
  930. access_token=self.other_user_token,
  931. content=b"{}",
  932. )
  933. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  934. self.assertEqual("You are not a server admin", channel.json_body["error"])
  935. def test_user_does_not_exist(self):
  936. """
  937. Tests that a lookup for a user that does not exist returns a 404
  938. """
  939. channel = self.make_request(
  940. "GET",
  941. "/_synapse/admin/v2/users/@unknown_person:test",
  942. access_token=self.admin_user_tok,
  943. )
  944. self.assertEqual(404, channel.code, msg=channel.json_body)
  945. self.assertEqual("M_NOT_FOUND", channel.json_body["errcode"])
  946. def test_create_server_admin(self):
  947. """
  948. Check that a new admin user is created successfully.
  949. """
  950. url = "/_synapse/admin/v2/users/@bob:test"
  951. # Create user (server admin)
  952. body = json.dumps(
  953. {
  954. "password": "abc123",
  955. "admin": True,
  956. "displayname": "Bob's name",
  957. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  958. "avatar_url": "mxc://fibble/wibble",
  959. }
  960. )
  961. channel = self.make_request(
  962. "PUT",
  963. url,
  964. access_token=self.admin_user_tok,
  965. content=body.encode(encoding="utf_8"),
  966. )
  967. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  968. self.assertEqual("@bob:test", channel.json_body["name"])
  969. self.assertEqual("Bob's name", channel.json_body["displayname"])
  970. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  971. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  972. self.assertTrue(channel.json_body["admin"])
  973. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  974. # Get user
  975. channel = self.make_request(
  976. "GET",
  977. url,
  978. access_token=self.admin_user_tok,
  979. )
  980. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  981. self.assertEqual("@bob:test", channel.json_body["name"])
  982. self.assertEqual("Bob's name", channel.json_body["displayname"])
  983. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  984. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  985. self.assertTrue(channel.json_body["admin"])
  986. self.assertFalse(channel.json_body["is_guest"])
  987. self.assertFalse(channel.json_body["deactivated"])
  988. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  989. def test_create_user(self):
  990. """
  991. Check that a new regular user is created successfully.
  992. """
  993. url = "/_synapse/admin/v2/users/@bob:test"
  994. # Create user
  995. body = json.dumps(
  996. {
  997. "password": "abc123",
  998. "admin": False,
  999. "displayname": "Bob's name",
  1000. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1001. "avatar_url": "mxc://fibble/wibble",
  1002. }
  1003. )
  1004. channel = self.make_request(
  1005. "PUT",
  1006. url,
  1007. access_token=self.admin_user_tok,
  1008. content=body.encode(encoding="utf_8"),
  1009. )
  1010. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  1011. self.assertEqual("@bob:test", channel.json_body["name"])
  1012. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1013. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1014. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1015. self.assertFalse(channel.json_body["admin"])
  1016. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1017. # Get user
  1018. channel = self.make_request(
  1019. "GET",
  1020. url,
  1021. access_token=self.admin_user_tok,
  1022. )
  1023. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1024. self.assertEqual("@bob:test", channel.json_body["name"])
  1025. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1026. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1027. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1028. self.assertFalse(channel.json_body["admin"])
  1029. self.assertFalse(channel.json_body["is_guest"])
  1030. self.assertFalse(channel.json_body["deactivated"])
  1031. self.assertFalse(channel.json_body["shadow_banned"])
  1032. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1033. @override_config(
  1034. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  1035. )
  1036. def test_create_user_mau_limit_reached_active_admin(self):
  1037. """
  1038. Check that an admin can register a new user via the admin API
  1039. even if the MAU limit is reached.
  1040. Admin user was active before creating user.
  1041. """
  1042. handler = self.hs.get_registration_handler()
  1043. # Sync to set admin user to active
  1044. # before limit of monthly active users is reached
  1045. channel = self.make_request("GET", "/sync", access_token=self.admin_user_tok)
  1046. if channel.code != 200:
  1047. raise HttpResponseException(
  1048. channel.code, channel.result["reason"], channel.result["body"]
  1049. )
  1050. # Set monthly active users to the limit
  1051. self.store.get_monthly_active_count = Mock(
  1052. return_value=make_awaitable(self.hs.config.max_mau_value)
  1053. )
  1054. # Check that the blocking of monthly active users is working as expected
  1055. # The registration of a new user fails due to the limit
  1056. self.get_failure(
  1057. handler.register_user(localpart="local_part"), ResourceLimitError
  1058. )
  1059. # Register new user with admin API
  1060. url = "/_synapse/admin/v2/users/@bob:test"
  1061. # Create user
  1062. body = json.dumps({"password": "abc123", "admin": False})
  1063. channel = self.make_request(
  1064. "PUT",
  1065. url,
  1066. access_token=self.admin_user_tok,
  1067. content=body.encode(encoding="utf_8"),
  1068. )
  1069. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  1070. self.assertEqual("@bob:test", channel.json_body["name"])
  1071. self.assertFalse(channel.json_body["admin"])
  1072. @override_config(
  1073. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  1074. )
  1075. def test_create_user_mau_limit_reached_passive_admin(self):
  1076. """
  1077. Check that an admin can register a new user via the admin API
  1078. even if the MAU limit is reached.
  1079. Admin user was not active before creating user.
  1080. """
  1081. handler = self.hs.get_registration_handler()
  1082. # Set monthly active users to the limit
  1083. self.store.get_monthly_active_count = Mock(
  1084. return_value=make_awaitable(self.hs.config.max_mau_value)
  1085. )
  1086. # Check that the blocking of monthly active users is working as expected
  1087. # The registration of a new user fails due to the limit
  1088. self.get_failure(
  1089. handler.register_user(localpart="local_part"), ResourceLimitError
  1090. )
  1091. # Register new user with admin API
  1092. url = "/_synapse/admin/v2/users/@bob:test"
  1093. # Create user
  1094. body = json.dumps({"password": "abc123", "admin": False})
  1095. channel = self.make_request(
  1096. "PUT",
  1097. url,
  1098. access_token=self.admin_user_tok,
  1099. content=body.encode(encoding="utf_8"),
  1100. )
  1101. # Admin user is not blocked by mau anymore
  1102. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  1103. self.assertEqual("@bob:test", channel.json_body["name"])
  1104. self.assertFalse(channel.json_body["admin"])
  1105. @override_config(
  1106. {
  1107. "email": {
  1108. "enable_notifs": True,
  1109. "notif_for_new_users": True,
  1110. "notif_from": "test@example.com",
  1111. },
  1112. "public_baseurl": "https://example.com",
  1113. }
  1114. )
  1115. def test_create_user_email_notif_for_new_users(self):
  1116. """
  1117. Check that a new regular user is created successfully and
  1118. got an email pusher.
  1119. """
  1120. url = "/_synapse/admin/v2/users/@bob:test"
  1121. # Create user
  1122. body = json.dumps(
  1123. {
  1124. "password": "abc123",
  1125. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1126. }
  1127. )
  1128. channel = self.make_request(
  1129. "PUT",
  1130. url,
  1131. access_token=self.admin_user_tok,
  1132. content=body.encode(encoding="utf_8"),
  1133. )
  1134. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  1135. self.assertEqual("@bob:test", channel.json_body["name"])
  1136. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1137. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1138. pushers = self.get_success(
  1139. self.store.get_pushers_by({"user_name": "@bob:test"})
  1140. )
  1141. pushers = list(pushers)
  1142. self.assertEqual(len(pushers), 1)
  1143. self.assertEqual("@bob:test", pushers[0].user_name)
  1144. @override_config(
  1145. {
  1146. "email": {
  1147. "enable_notifs": False,
  1148. "notif_for_new_users": False,
  1149. "notif_from": "test@example.com",
  1150. },
  1151. "public_baseurl": "https://example.com",
  1152. }
  1153. )
  1154. def test_create_user_email_no_notif_for_new_users(self):
  1155. """
  1156. Check that a new regular user is created successfully and
  1157. got not an email pusher.
  1158. """
  1159. url = "/_synapse/admin/v2/users/@bob:test"
  1160. # Create user
  1161. body = json.dumps(
  1162. {
  1163. "password": "abc123",
  1164. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1165. }
  1166. )
  1167. channel = self.make_request(
  1168. "PUT",
  1169. url,
  1170. access_token=self.admin_user_tok,
  1171. content=body.encode(encoding="utf_8"),
  1172. )
  1173. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  1174. self.assertEqual("@bob:test", channel.json_body["name"])
  1175. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1176. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1177. pushers = self.get_success(
  1178. self.store.get_pushers_by({"user_name": "@bob:test"})
  1179. )
  1180. pushers = list(pushers)
  1181. self.assertEqual(len(pushers), 0)
  1182. def test_set_password(self):
  1183. """
  1184. Test setting a new password for another user.
  1185. """
  1186. # Change password
  1187. body = json.dumps({"password": "hahaha"})
  1188. channel = self.make_request(
  1189. "PUT",
  1190. self.url_other_user,
  1191. access_token=self.admin_user_tok,
  1192. content=body.encode(encoding="utf_8"),
  1193. )
  1194. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1195. def test_set_displayname(self):
  1196. """
  1197. Test setting the displayname of another user.
  1198. """
  1199. # Modify user
  1200. body = json.dumps({"displayname": "foobar"})
  1201. channel = self.make_request(
  1202. "PUT",
  1203. self.url_other_user,
  1204. access_token=self.admin_user_tok,
  1205. content=body.encode(encoding="utf_8"),
  1206. )
  1207. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1208. self.assertEqual("@user:test", channel.json_body["name"])
  1209. self.assertEqual("foobar", channel.json_body["displayname"])
  1210. # Get user
  1211. channel = self.make_request(
  1212. "GET",
  1213. self.url_other_user,
  1214. access_token=self.admin_user_tok,
  1215. )
  1216. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1217. self.assertEqual("@user:test", channel.json_body["name"])
  1218. self.assertEqual("foobar", channel.json_body["displayname"])
  1219. def test_set_threepid(self):
  1220. """
  1221. Test setting threepid for an other user.
  1222. """
  1223. # Delete old and add new threepid to user
  1224. body = json.dumps(
  1225. {"threepids": [{"medium": "email", "address": "bob3@bob.bob"}]}
  1226. )
  1227. channel = self.make_request(
  1228. "PUT",
  1229. self.url_other_user,
  1230. access_token=self.admin_user_tok,
  1231. content=body.encode(encoding="utf_8"),
  1232. )
  1233. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1234. self.assertEqual("@user:test", channel.json_body["name"])
  1235. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1236. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][0]["address"])
  1237. # Get user
  1238. channel = self.make_request(
  1239. "GET",
  1240. self.url_other_user,
  1241. access_token=self.admin_user_tok,
  1242. )
  1243. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1244. self.assertEqual("@user:test", channel.json_body["name"])
  1245. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1246. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][0]["address"])
  1247. def test_deactivate_user(self):
  1248. """
  1249. Test deactivating another user.
  1250. """
  1251. # set attributes for user
  1252. self.get_success(
  1253. self.store.set_profile_avatar_url("user", "mxc://servername/mediaid")
  1254. )
  1255. self.get_success(
  1256. self.store.user_add_threepid("@user:test", "email", "foo@bar.com", 0, 0)
  1257. )
  1258. # Get user
  1259. channel = self.make_request(
  1260. "GET",
  1261. self.url_other_user,
  1262. access_token=self.admin_user_tok,
  1263. )
  1264. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1265. self.assertEqual("@user:test", channel.json_body["name"])
  1266. self.assertFalse(channel.json_body["deactivated"])
  1267. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  1268. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1269. self.assertEqual("User", channel.json_body["displayname"])
  1270. # Deactivate user
  1271. channel = self.make_request(
  1272. "PUT",
  1273. self.url_other_user,
  1274. access_token=self.admin_user_tok,
  1275. content={"deactivated": True},
  1276. )
  1277. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1278. self.assertEqual("@user:test", channel.json_body["name"])
  1279. self.assertTrue(channel.json_body["deactivated"])
  1280. self.assertIsNone(channel.json_body["password_hash"])
  1281. self.assertEqual(0, len(channel.json_body["threepids"]))
  1282. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1283. self.assertEqual("User", channel.json_body["displayname"])
  1284. # the user is deactivated, the threepid will be deleted
  1285. # Get user
  1286. channel = self.make_request(
  1287. "GET",
  1288. self.url_other_user,
  1289. access_token=self.admin_user_tok,
  1290. )
  1291. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1292. self.assertEqual("@user:test", channel.json_body["name"])
  1293. self.assertTrue(channel.json_body["deactivated"])
  1294. self.assertIsNone(channel.json_body["password_hash"])
  1295. self.assertEqual(0, len(channel.json_body["threepids"]))
  1296. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1297. self.assertEqual("User", channel.json_body["displayname"])
  1298. @override_config({"user_directory": {"enabled": True, "search_all_users": True}})
  1299. def test_change_name_deactivate_user_user_directory(self):
  1300. """
  1301. Test change profile information of a deactivated user and
  1302. check that it does not appear in user directory
  1303. """
  1304. # is in user directory
  1305. profile = self.get_success(self.store.get_user_in_directory(self.other_user))
  1306. self.assertTrue(profile["display_name"] == "User")
  1307. # Deactivate user
  1308. channel = self.make_request(
  1309. "PUT",
  1310. self.url_other_user,
  1311. access_token=self.admin_user_tok,
  1312. content={"deactivated": True},
  1313. )
  1314. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1315. self.assertEqual("@user:test", channel.json_body["name"])
  1316. self.assertTrue(channel.json_body["deactivated"])
  1317. # is not in user directory
  1318. profile = self.get_success(self.store.get_user_in_directory(self.other_user))
  1319. self.assertIsNone(profile)
  1320. # Set new displayname user
  1321. channel = self.make_request(
  1322. "PUT",
  1323. self.url_other_user,
  1324. access_token=self.admin_user_tok,
  1325. content={"displayname": "Foobar"},
  1326. )
  1327. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1328. self.assertEqual("@user:test", channel.json_body["name"])
  1329. self.assertTrue(channel.json_body["deactivated"])
  1330. self.assertEqual("Foobar", channel.json_body["displayname"])
  1331. # is not in user directory
  1332. profile = self.get_success(self.store.get_user_in_directory(self.other_user))
  1333. self.assertIsNone(profile)
  1334. def test_reactivate_user(self):
  1335. """
  1336. Test reactivating another user.
  1337. """
  1338. # Deactivate the user.
  1339. self._deactivate_user("@user:test")
  1340. # Attempt to reactivate the user (without a password).
  1341. channel = self.make_request(
  1342. "PUT",
  1343. self.url_other_user,
  1344. access_token=self.admin_user_tok,
  1345. content={"deactivated": False},
  1346. )
  1347. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1348. # Reactivate the user.
  1349. channel = self.make_request(
  1350. "PUT",
  1351. self.url_other_user,
  1352. access_token=self.admin_user_tok,
  1353. content={"deactivated": False, "password": "foo"},
  1354. )
  1355. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1356. self.assertEqual("@user:test", channel.json_body["name"])
  1357. self.assertFalse(channel.json_body["deactivated"])
  1358. self.assertIsNotNone(channel.json_body["password_hash"])
  1359. self._is_erased("@user:test", False)
  1360. @override_config({"password_config": {"localdb_enabled": False}})
  1361. def test_reactivate_user_localdb_disabled(self):
  1362. """
  1363. Test reactivating another user when using SSO.
  1364. """
  1365. # Deactivate the user.
  1366. self._deactivate_user("@user:test")
  1367. # Reactivate the user with a password
  1368. channel = self.make_request(
  1369. "PUT",
  1370. self.url_other_user,
  1371. access_token=self.admin_user_tok,
  1372. content={"deactivated": False, "password": "foo"},
  1373. )
  1374. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1375. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1376. # Reactivate the user without a password.
  1377. channel = self.make_request(
  1378. "PUT",
  1379. self.url_other_user,
  1380. access_token=self.admin_user_tok,
  1381. content={"deactivated": False},
  1382. )
  1383. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1384. self.assertEqual("@user:test", channel.json_body["name"])
  1385. self.assertFalse(channel.json_body["deactivated"])
  1386. self.assertIsNone(channel.json_body["password_hash"])
  1387. self._is_erased("@user:test", False)
  1388. @override_config({"password_config": {"enabled": False}})
  1389. def test_reactivate_user_password_disabled(self):
  1390. """
  1391. Test reactivating another user when using SSO.
  1392. """
  1393. # Deactivate the user.
  1394. self._deactivate_user("@user:test")
  1395. # Reactivate the user with a password
  1396. channel = self.make_request(
  1397. "PUT",
  1398. self.url_other_user,
  1399. access_token=self.admin_user_tok,
  1400. content={"deactivated": False, "password": "foo"},
  1401. )
  1402. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1403. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1404. # Reactivate the user without a password.
  1405. channel = self.make_request(
  1406. "PUT",
  1407. self.url_other_user,
  1408. access_token=self.admin_user_tok,
  1409. content={"deactivated": False},
  1410. )
  1411. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1412. self.assertEqual("@user:test", channel.json_body["name"])
  1413. self.assertFalse(channel.json_body["deactivated"])
  1414. self.assertIsNone(channel.json_body["password_hash"])
  1415. self._is_erased("@user:test", False)
  1416. def test_set_user_as_admin(self):
  1417. """
  1418. Test setting the admin flag on a user.
  1419. """
  1420. # Set a user as an admin
  1421. channel = self.make_request(
  1422. "PUT",
  1423. self.url_other_user,
  1424. access_token=self.admin_user_tok,
  1425. content={"admin": True},
  1426. )
  1427. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1428. self.assertEqual("@user:test", channel.json_body["name"])
  1429. self.assertTrue(channel.json_body["admin"])
  1430. # Get user
  1431. channel = self.make_request(
  1432. "GET",
  1433. self.url_other_user,
  1434. access_token=self.admin_user_tok,
  1435. )
  1436. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1437. self.assertEqual("@user:test", channel.json_body["name"])
  1438. self.assertTrue(channel.json_body["admin"])
  1439. def test_accidental_deactivation_prevention(self):
  1440. """
  1441. Ensure an account can't accidentally be deactivated by using a str value
  1442. for the deactivated body parameter
  1443. """
  1444. url = "/_synapse/admin/v2/users/@bob:test"
  1445. # Create user
  1446. channel = self.make_request(
  1447. "PUT",
  1448. url,
  1449. access_token=self.admin_user_tok,
  1450. content={"password": "abc123"},
  1451. )
  1452. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  1453. self.assertEqual("@bob:test", channel.json_body["name"])
  1454. self.assertEqual("bob", channel.json_body["displayname"])
  1455. # Get user
  1456. channel = self.make_request(
  1457. "GET",
  1458. url,
  1459. access_token=self.admin_user_tok,
  1460. )
  1461. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1462. self.assertEqual("@bob:test", channel.json_body["name"])
  1463. self.assertEqual("bob", channel.json_body["displayname"])
  1464. self.assertEqual(0, channel.json_body["deactivated"])
  1465. # Change password (and use a str for deactivate instead of a bool)
  1466. channel = self.make_request(
  1467. "PUT",
  1468. url,
  1469. access_token=self.admin_user_tok,
  1470. content={"password": "abc123", "deactivated": "false"},
  1471. )
  1472. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1473. # Check user is not deactivated
  1474. channel = self.make_request(
  1475. "GET",
  1476. url,
  1477. access_token=self.admin_user_tok,
  1478. )
  1479. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1480. self.assertEqual("@bob:test", channel.json_body["name"])
  1481. self.assertEqual("bob", channel.json_body["displayname"])
  1482. # Ensure they're still alive
  1483. self.assertEqual(0, channel.json_body["deactivated"])
  1484. def _is_erased(self, user_id: str, expect: bool) -> None:
  1485. """Assert that the user is erased or not"""
  1486. d = self.store.is_user_erased(user_id)
  1487. if expect:
  1488. self.assertTrue(self.get_success(d))
  1489. else:
  1490. self.assertFalse(self.get_success(d))
  1491. def _deactivate_user(self, user_id: str) -> None:
  1492. """Deactivate user and set as erased"""
  1493. # Deactivate the user.
  1494. channel = self.make_request(
  1495. "PUT",
  1496. "/_synapse/admin/v2/users/%s" % urllib.parse.quote(user_id),
  1497. access_token=self.admin_user_tok,
  1498. content={"deactivated": True},
  1499. )
  1500. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1501. self.assertTrue(channel.json_body["deactivated"])
  1502. self.assertIsNone(channel.json_body["password_hash"])
  1503. self._is_erased(user_id, False)
  1504. d = self.store.mark_user_erased(user_id)
  1505. self.assertIsNone(self.get_success(d))
  1506. self._is_erased(user_id, True)
  1507. class UserMembershipRestTestCase(unittest.HomeserverTestCase):
  1508. servlets = [
  1509. synapse.rest.admin.register_servlets,
  1510. login.register_servlets,
  1511. room.register_servlets,
  1512. ]
  1513. def prepare(self, reactor, clock, hs):
  1514. self.admin_user = self.register_user("admin", "pass", admin=True)
  1515. self.admin_user_tok = self.login("admin", "pass")
  1516. self.other_user = self.register_user("user", "pass")
  1517. self.url = "/_synapse/admin/v1/users/%s/joined_rooms" % urllib.parse.quote(
  1518. self.other_user
  1519. )
  1520. def test_no_auth(self):
  1521. """
  1522. Try to list rooms of an user without authentication.
  1523. """
  1524. channel = self.make_request("GET", self.url, b"{}")
  1525. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1526. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1527. def test_requester_is_no_admin(self):
  1528. """
  1529. If the user is not a server admin, an error is returned.
  1530. """
  1531. other_user_token = self.login("user", "pass")
  1532. channel = self.make_request(
  1533. "GET",
  1534. self.url,
  1535. access_token=other_user_token,
  1536. )
  1537. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1538. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1539. def test_user_does_not_exist(self):
  1540. """
  1541. Tests that a lookup for a user that does not exist returns an empty list
  1542. """
  1543. url = "/_synapse/admin/v1/users/@unknown_person:test/joined_rooms"
  1544. channel = self.make_request(
  1545. "GET",
  1546. url,
  1547. access_token=self.admin_user_tok,
  1548. )
  1549. self.assertEqual(200, channel.code, msg=channel.json_body)
  1550. self.assertEqual(0, channel.json_body["total"])
  1551. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  1552. def test_user_is_not_local(self):
  1553. """
  1554. Tests that a lookup for a user that is not a local and participates in no conversation returns an empty list
  1555. """
  1556. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/joined_rooms"
  1557. channel = self.make_request(
  1558. "GET",
  1559. url,
  1560. access_token=self.admin_user_tok,
  1561. )
  1562. self.assertEqual(200, channel.code, msg=channel.json_body)
  1563. self.assertEqual(0, channel.json_body["total"])
  1564. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  1565. def test_no_memberships(self):
  1566. """
  1567. Tests that a normal lookup for rooms is successfully
  1568. if user has no memberships
  1569. """
  1570. # Get rooms
  1571. channel = self.make_request(
  1572. "GET",
  1573. self.url,
  1574. access_token=self.admin_user_tok,
  1575. )
  1576. self.assertEqual(200, channel.code, msg=channel.json_body)
  1577. self.assertEqual(0, channel.json_body["total"])
  1578. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  1579. def test_get_rooms(self):
  1580. """
  1581. Tests that a normal lookup for rooms is successfully
  1582. """
  1583. # Create rooms and join
  1584. other_user_tok = self.login("user", "pass")
  1585. number_rooms = 5
  1586. for _ in range(number_rooms):
  1587. self.helper.create_room_as(self.other_user, tok=other_user_tok)
  1588. # Get rooms
  1589. channel = self.make_request(
  1590. "GET",
  1591. self.url,
  1592. access_token=self.admin_user_tok,
  1593. )
  1594. self.assertEqual(200, channel.code, msg=channel.json_body)
  1595. self.assertEqual(number_rooms, channel.json_body["total"])
  1596. self.assertEqual(number_rooms, len(channel.json_body["joined_rooms"]))
  1597. def test_get_rooms_with_nonlocal_user(self):
  1598. """
  1599. Tests that a normal lookup for rooms is successful with a non-local user
  1600. """
  1601. other_user_tok = self.login("user", "pass")
  1602. event_builder_factory = self.hs.get_event_builder_factory()
  1603. event_creation_handler = self.hs.get_event_creation_handler()
  1604. storage = self.hs.get_storage()
  1605. # Create two rooms, one with a local user only and one with both a local
  1606. # and remote user.
  1607. self.helper.create_room_as(self.other_user, tok=other_user_tok)
  1608. local_and_remote_room_id = self.helper.create_room_as(
  1609. self.other_user, tok=other_user_tok
  1610. )
  1611. # Add a remote user to the room.
  1612. builder = event_builder_factory.for_room_version(
  1613. RoomVersions.V1,
  1614. {
  1615. "type": "m.room.member",
  1616. "sender": "@joiner:remote_hs",
  1617. "state_key": "@joiner:remote_hs",
  1618. "room_id": local_and_remote_room_id,
  1619. "content": {"membership": "join"},
  1620. },
  1621. )
  1622. event, context = self.get_success(
  1623. event_creation_handler.create_new_client_event(builder)
  1624. )
  1625. self.get_success(storage.persistence.persist_event(event, context))
  1626. # Now get rooms
  1627. url = "/_synapse/admin/v1/users/@joiner:remote_hs/joined_rooms"
  1628. channel = self.make_request(
  1629. "GET",
  1630. url,
  1631. access_token=self.admin_user_tok,
  1632. )
  1633. self.assertEqual(200, channel.code, msg=channel.json_body)
  1634. self.assertEqual(1, channel.json_body["total"])
  1635. self.assertEqual([local_and_remote_room_id], channel.json_body["joined_rooms"])
  1636. class PushersRestTestCase(unittest.HomeserverTestCase):
  1637. servlets = [
  1638. synapse.rest.admin.register_servlets,
  1639. login.register_servlets,
  1640. ]
  1641. def prepare(self, reactor, clock, hs):
  1642. self.store = hs.get_datastore()
  1643. self.admin_user = self.register_user("admin", "pass", admin=True)
  1644. self.admin_user_tok = self.login("admin", "pass")
  1645. self.other_user = self.register_user("user", "pass")
  1646. self.url = "/_synapse/admin/v1/users/%s/pushers" % urllib.parse.quote(
  1647. self.other_user
  1648. )
  1649. def test_no_auth(self):
  1650. """
  1651. Try to list pushers of an user without authentication.
  1652. """
  1653. channel = self.make_request("GET", self.url, b"{}")
  1654. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1655. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1656. def test_requester_is_no_admin(self):
  1657. """
  1658. If the user is not a server admin, an error is returned.
  1659. """
  1660. other_user_token = self.login("user", "pass")
  1661. channel = self.make_request(
  1662. "GET",
  1663. self.url,
  1664. access_token=other_user_token,
  1665. )
  1666. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1667. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1668. def test_user_does_not_exist(self):
  1669. """
  1670. Tests that a lookup for a user that does not exist returns a 404
  1671. """
  1672. url = "/_synapse/admin/v1/users/@unknown_person:test/pushers"
  1673. channel = self.make_request(
  1674. "GET",
  1675. url,
  1676. access_token=self.admin_user_tok,
  1677. )
  1678. self.assertEqual(404, channel.code, msg=channel.json_body)
  1679. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  1680. def test_user_is_not_local(self):
  1681. """
  1682. Tests that a lookup for a user that is not a local returns a 400
  1683. """
  1684. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/pushers"
  1685. channel = self.make_request(
  1686. "GET",
  1687. url,
  1688. access_token=self.admin_user_tok,
  1689. )
  1690. self.assertEqual(400, channel.code, msg=channel.json_body)
  1691. self.assertEqual("Can only lookup local users", channel.json_body["error"])
  1692. def test_get_pushers(self):
  1693. """
  1694. Tests that a normal lookup for pushers is successfully
  1695. """
  1696. # Get pushers
  1697. channel = self.make_request(
  1698. "GET",
  1699. self.url,
  1700. access_token=self.admin_user_tok,
  1701. )
  1702. self.assertEqual(200, channel.code, msg=channel.json_body)
  1703. self.assertEqual(0, channel.json_body["total"])
  1704. # Register the pusher
  1705. other_user_token = self.login("user", "pass")
  1706. user_tuple = self.get_success(
  1707. self.store.get_user_by_access_token(other_user_token)
  1708. )
  1709. token_id = user_tuple.token_id
  1710. self.get_success(
  1711. self.hs.get_pusherpool().add_pusher(
  1712. user_id=self.other_user,
  1713. access_token=token_id,
  1714. kind="http",
  1715. app_id="m.http",
  1716. app_display_name="HTTP Push Notifications",
  1717. device_display_name="pushy push",
  1718. pushkey="a@example.com",
  1719. lang=None,
  1720. data={"url": "https://example.com/_matrix/push/v1/notify"},
  1721. )
  1722. )
  1723. # Get pushers
  1724. channel = self.make_request(
  1725. "GET",
  1726. self.url,
  1727. access_token=self.admin_user_tok,
  1728. )
  1729. self.assertEqual(200, channel.code, msg=channel.json_body)
  1730. self.assertEqual(1, channel.json_body["total"])
  1731. for p in channel.json_body["pushers"]:
  1732. self.assertIn("pushkey", p)
  1733. self.assertIn("kind", p)
  1734. self.assertIn("app_id", p)
  1735. self.assertIn("app_display_name", p)
  1736. self.assertIn("device_display_name", p)
  1737. self.assertIn("profile_tag", p)
  1738. self.assertIn("lang", p)
  1739. self.assertIn("url", p["data"])
  1740. class UserMediaRestTestCase(unittest.HomeserverTestCase):
  1741. servlets = [
  1742. synapse.rest.admin.register_servlets,
  1743. login.register_servlets,
  1744. ]
  1745. def prepare(self, reactor, clock, hs):
  1746. self.store = hs.get_datastore()
  1747. self.media_repo = hs.get_media_repository_resource()
  1748. self.admin_user = self.register_user("admin", "pass", admin=True)
  1749. self.admin_user_tok = self.login("admin", "pass")
  1750. self.other_user = self.register_user("user", "pass")
  1751. self.url = "/_synapse/admin/v1/users/%s/media" % urllib.parse.quote(
  1752. self.other_user
  1753. )
  1754. def test_no_auth(self):
  1755. """
  1756. Try to list media of an user without authentication.
  1757. """
  1758. channel = self.make_request("GET", self.url, b"{}")
  1759. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1760. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1761. def test_requester_is_no_admin(self):
  1762. """
  1763. If the user is not a server admin, an error is returned.
  1764. """
  1765. other_user_token = self.login("user", "pass")
  1766. channel = self.make_request(
  1767. "GET",
  1768. self.url,
  1769. access_token=other_user_token,
  1770. )
  1771. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1772. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1773. def test_user_does_not_exist(self):
  1774. """
  1775. Tests that a lookup for a user that does not exist returns a 404
  1776. """
  1777. url = "/_synapse/admin/v1/users/@unknown_person:test/media"
  1778. channel = self.make_request(
  1779. "GET",
  1780. url,
  1781. access_token=self.admin_user_tok,
  1782. )
  1783. self.assertEqual(404, channel.code, msg=channel.json_body)
  1784. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  1785. def test_user_is_not_local(self):
  1786. """
  1787. Tests that a lookup for a user that is not a local returns a 400
  1788. """
  1789. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/media"
  1790. channel = self.make_request(
  1791. "GET",
  1792. url,
  1793. access_token=self.admin_user_tok,
  1794. )
  1795. self.assertEqual(400, channel.code, msg=channel.json_body)
  1796. self.assertEqual("Can only lookup local users", channel.json_body["error"])
  1797. def test_limit(self):
  1798. """
  1799. Testing list of media with limit
  1800. """
  1801. number_media = 20
  1802. other_user_tok = self.login("user", "pass")
  1803. self._create_media_for_user(other_user_tok, number_media)
  1804. channel = self.make_request(
  1805. "GET",
  1806. self.url + "?limit=5",
  1807. access_token=self.admin_user_tok,
  1808. )
  1809. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1810. self.assertEqual(channel.json_body["total"], number_media)
  1811. self.assertEqual(len(channel.json_body["media"]), 5)
  1812. self.assertEqual(channel.json_body["next_token"], 5)
  1813. self._check_fields(channel.json_body["media"])
  1814. def test_from(self):
  1815. """
  1816. Testing list of media with a defined starting point (from)
  1817. """
  1818. number_media = 20
  1819. other_user_tok = self.login("user", "pass")
  1820. self._create_media_for_user(other_user_tok, number_media)
  1821. channel = self.make_request(
  1822. "GET",
  1823. self.url + "?from=5",
  1824. access_token=self.admin_user_tok,
  1825. )
  1826. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1827. self.assertEqual(channel.json_body["total"], number_media)
  1828. self.assertEqual(len(channel.json_body["media"]), 15)
  1829. self.assertNotIn("next_token", channel.json_body)
  1830. self._check_fields(channel.json_body["media"])
  1831. def test_limit_and_from(self):
  1832. """
  1833. Testing list of media with a defined starting point and limit
  1834. """
  1835. number_media = 20
  1836. other_user_tok = self.login("user", "pass")
  1837. self._create_media_for_user(other_user_tok, number_media)
  1838. channel = self.make_request(
  1839. "GET",
  1840. self.url + "?from=5&limit=10",
  1841. access_token=self.admin_user_tok,
  1842. )
  1843. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1844. self.assertEqual(channel.json_body["total"], number_media)
  1845. self.assertEqual(channel.json_body["next_token"], 15)
  1846. self.assertEqual(len(channel.json_body["media"]), 10)
  1847. self._check_fields(channel.json_body["media"])
  1848. def test_invalid_parameter(self):
  1849. """
  1850. If parameters are invalid, an error is returned.
  1851. """
  1852. # unkown order_by
  1853. channel = self.make_request(
  1854. "GET",
  1855. self.url + "?order_by=bar",
  1856. access_token=self.admin_user_tok,
  1857. )
  1858. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1859. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1860. # invalid search order
  1861. channel = self.make_request(
  1862. "GET",
  1863. self.url + "?dir=bar",
  1864. access_token=self.admin_user_tok,
  1865. )
  1866. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1867. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1868. # negative limit
  1869. channel = self.make_request(
  1870. "GET",
  1871. self.url + "?limit=-5",
  1872. access_token=self.admin_user_tok,
  1873. )
  1874. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1875. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  1876. # negative from
  1877. channel = self.make_request(
  1878. "GET",
  1879. self.url + "?from=-5",
  1880. access_token=self.admin_user_tok,
  1881. )
  1882. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1883. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  1884. def test_next_token(self):
  1885. """
  1886. Testing that `next_token` appears at the right place
  1887. """
  1888. number_media = 20
  1889. other_user_tok = self.login("user", "pass")
  1890. self._create_media_for_user(other_user_tok, number_media)
  1891. # `next_token` does not appear
  1892. # Number of results is the number of entries
  1893. channel = self.make_request(
  1894. "GET",
  1895. self.url + "?limit=20",
  1896. access_token=self.admin_user_tok,
  1897. )
  1898. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1899. self.assertEqual(channel.json_body["total"], number_media)
  1900. self.assertEqual(len(channel.json_body["media"]), number_media)
  1901. self.assertNotIn("next_token", channel.json_body)
  1902. # `next_token` does not appear
  1903. # Number of max results is larger than the number of entries
  1904. channel = self.make_request(
  1905. "GET",
  1906. self.url + "?limit=21",
  1907. access_token=self.admin_user_tok,
  1908. )
  1909. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1910. self.assertEqual(channel.json_body["total"], number_media)
  1911. self.assertEqual(len(channel.json_body["media"]), number_media)
  1912. self.assertNotIn("next_token", channel.json_body)
  1913. # `next_token` does appear
  1914. # Number of max results is smaller than the number of entries
  1915. channel = self.make_request(
  1916. "GET",
  1917. self.url + "?limit=19",
  1918. access_token=self.admin_user_tok,
  1919. )
  1920. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1921. self.assertEqual(channel.json_body["total"], number_media)
  1922. self.assertEqual(len(channel.json_body["media"]), 19)
  1923. self.assertEqual(channel.json_body["next_token"], 19)
  1924. # Check
  1925. # Set `from` to value of `next_token` for request remaining entries
  1926. # `next_token` does not appear
  1927. channel = self.make_request(
  1928. "GET",
  1929. self.url + "?from=19",
  1930. access_token=self.admin_user_tok,
  1931. )
  1932. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1933. self.assertEqual(channel.json_body["total"], number_media)
  1934. self.assertEqual(len(channel.json_body["media"]), 1)
  1935. self.assertNotIn("next_token", channel.json_body)
  1936. def test_user_has_no_media(self):
  1937. """
  1938. Tests that a normal lookup for media is successfully
  1939. if user has no media created
  1940. """
  1941. channel = self.make_request(
  1942. "GET",
  1943. self.url,
  1944. access_token=self.admin_user_tok,
  1945. )
  1946. self.assertEqual(200, channel.code, msg=channel.json_body)
  1947. self.assertEqual(0, channel.json_body["total"])
  1948. self.assertEqual(0, len(channel.json_body["media"]))
  1949. def test_get_media(self):
  1950. """
  1951. Tests that a normal lookup for media is successfully
  1952. """
  1953. number_media = 5
  1954. other_user_tok = self.login("user", "pass")
  1955. self._create_media_for_user(other_user_tok, number_media)
  1956. channel = self.make_request(
  1957. "GET",
  1958. self.url,
  1959. access_token=self.admin_user_tok,
  1960. )
  1961. self.assertEqual(200, channel.code, msg=channel.json_body)
  1962. self.assertEqual(number_media, channel.json_body["total"])
  1963. self.assertEqual(number_media, len(channel.json_body["media"]))
  1964. self.assertNotIn("next_token", channel.json_body)
  1965. self._check_fields(channel.json_body["media"])
  1966. def test_order_by(self):
  1967. """
  1968. Testing order list with parameter `order_by`
  1969. """
  1970. other_user_tok = self.login("user", "pass")
  1971. # Resolution: 1×1, MIME type: image/png, Extension: png, Size: 67 B
  1972. image_data1 = unhexlify(
  1973. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  1974. b"0000001f15c4890000000a49444154789c63000100000500010d"
  1975. b"0a2db40000000049454e44ae426082"
  1976. )
  1977. # Resolution: 1×1, MIME type: image/gif, Extension: gif, Size: 35 B
  1978. image_data2 = unhexlify(
  1979. b"47494638376101000100800100000000"
  1980. b"ffffff2c00000000010001000002024c"
  1981. b"01003b"
  1982. )
  1983. # Resolution: 1×1, MIME type: image/bmp, Extension: bmp, Size: 54 B
  1984. image_data3 = unhexlify(
  1985. b"424d3a0000000000000036000000280000000100000001000000"
  1986. b"0100180000000000040000000000000000000000000000000000"
  1987. b"0000"
  1988. )
  1989. # create media and make sure they do not have the same timestamp
  1990. media1 = self._create_media_and_access(other_user_tok, image_data1, "image.png")
  1991. self.pump(1.0)
  1992. media2 = self._create_media_and_access(other_user_tok, image_data2, "image.gif")
  1993. self.pump(1.0)
  1994. media3 = self._create_media_and_access(other_user_tok, image_data3, "image.bmp")
  1995. self.pump(1.0)
  1996. # Mark one media as safe from quarantine.
  1997. self.get_success(self.store.mark_local_media_as_safe(media2))
  1998. # Quarantine one media
  1999. self.get_success(
  2000. self.store.quarantine_media_by_id("test", media3, self.admin_user)
  2001. )
  2002. # order by default ("created_ts")
  2003. # default is backwards
  2004. self._order_test([media3, media2, media1], None)
  2005. self._order_test([media1, media2, media3], None, "f")
  2006. self._order_test([media3, media2, media1], None, "b")
  2007. # sort by media_id
  2008. sorted_media = sorted([media1, media2, media3], reverse=False)
  2009. sorted_media_reverse = sorted(sorted_media, reverse=True)
  2010. # order by media_id
  2011. self._order_test(sorted_media, "media_id")
  2012. self._order_test(sorted_media, "media_id", "f")
  2013. self._order_test(sorted_media_reverse, "media_id", "b")
  2014. # order by upload_name
  2015. self._order_test([media3, media2, media1], "upload_name")
  2016. self._order_test([media3, media2, media1], "upload_name", "f")
  2017. self._order_test([media1, media2, media3], "upload_name", "b")
  2018. # order by media_type
  2019. # result is ordered by media_id
  2020. # because of uploaded media_type is always 'application/json'
  2021. self._order_test(sorted_media, "media_type")
  2022. self._order_test(sorted_media, "media_type", "f")
  2023. self._order_test(sorted_media, "media_type", "b")
  2024. # order by media_length
  2025. self._order_test([media2, media3, media1], "media_length")
  2026. self._order_test([media2, media3, media1], "media_length", "f")
  2027. self._order_test([media1, media3, media2], "media_length", "b")
  2028. # order by created_ts
  2029. self._order_test([media1, media2, media3], "created_ts")
  2030. self._order_test([media1, media2, media3], "created_ts", "f")
  2031. self._order_test([media3, media2, media1], "created_ts", "b")
  2032. # order by last_access_ts
  2033. self._order_test([media1, media2, media3], "last_access_ts")
  2034. self._order_test([media1, media2, media3], "last_access_ts", "f")
  2035. self._order_test([media3, media2, media1], "last_access_ts", "b")
  2036. # order by quarantined_by
  2037. # one media is in quarantine, others are ordered by media_ids
  2038. # Different sort order of SQlite and PostreSQL
  2039. # If a media is not in quarantine `quarantined_by` is NULL
  2040. # SQLite considers NULL to be smaller than any other value.
  2041. # PostreSQL considers NULL to be larger than any other value.
  2042. # self._order_test(sorted([media1, media2]) + [media3], "quarantined_by")
  2043. # self._order_test(sorted([media1, media2]) + [media3], "quarantined_by", "f")
  2044. # self._order_test([media3] + sorted([media1, media2]), "quarantined_by", "b")
  2045. # order by safe_from_quarantine
  2046. # one media is safe from quarantine, others are ordered by media_ids
  2047. self._order_test(sorted([media1, media3]) + [media2], "safe_from_quarantine")
  2048. self._order_test(
  2049. sorted([media1, media3]) + [media2], "safe_from_quarantine", "f"
  2050. )
  2051. self._order_test(
  2052. [media2] + sorted([media1, media3]), "safe_from_quarantine", "b"
  2053. )
  2054. def _create_media_for_user(self, user_token: str, number_media: int):
  2055. """
  2056. Create a number of media for a specific user
  2057. Args:
  2058. user_token: Access token of the user
  2059. number_media: Number of media to be created for the user
  2060. """
  2061. for _ in range(number_media):
  2062. # file size is 67 Byte
  2063. image_data = unhexlify(
  2064. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  2065. b"0000001f15c4890000000a49444154789c63000100000500010d"
  2066. b"0a2db40000000049454e44ae426082"
  2067. )
  2068. self._create_media_and_access(user_token, image_data)
  2069. def _create_media_and_access(
  2070. self,
  2071. user_token: str,
  2072. image_data: bytes,
  2073. filename: str = "image1.png",
  2074. ) -> str:
  2075. """
  2076. Create one media for a specific user, access and returns `media_id`
  2077. Args:
  2078. user_token: Access token of the user
  2079. image_data: binary data of image
  2080. filename: The filename of the media to be uploaded
  2081. Returns:
  2082. The ID of the newly created media.
  2083. """
  2084. upload_resource = self.media_repo.children[b"upload"]
  2085. download_resource = self.media_repo.children[b"download"]
  2086. # Upload some media into the room
  2087. response = self.helper.upload_media(
  2088. upload_resource, image_data, user_token, filename, expect_code=200
  2089. )
  2090. # Extract media ID from the response
  2091. server_and_media_id = response["content_uri"][6:] # Cut off 'mxc://'
  2092. media_id = server_and_media_id.split("/")[1]
  2093. # Try to access a media and to create `last_access_ts`
  2094. channel = make_request(
  2095. self.reactor,
  2096. FakeSite(download_resource),
  2097. "GET",
  2098. server_and_media_id,
  2099. shorthand=False,
  2100. access_token=user_token,
  2101. )
  2102. self.assertEqual(
  2103. 200,
  2104. channel.code,
  2105. msg=(
  2106. "Expected to receive a 200 on accessing media: %s" % server_and_media_id
  2107. ),
  2108. )
  2109. return media_id
  2110. def _check_fields(self, content: JsonDict):
  2111. """Checks that the expected user attributes are present in content
  2112. Args:
  2113. content: List that is checked for content
  2114. """
  2115. for m in content:
  2116. self.assertIn("media_id", m)
  2117. self.assertIn("media_type", m)
  2118. self.assertIn("media_length", m)
  2119. self.assertIn("upload_name", m)
  2120. self.assertIn("created_ts", m)
  2121. self.assertIn("last_access_ts", m)
  2122. self.assertIn("quarantined_by", m)
  2123. self.assertIn("safe_from_quarantine", m)
  2124. def _order_test(
  2125. self,
  2126. expected_media_list: List[str],
  2127. order_by: Optional[str],
  2128. dir: Optional[str] = None,
  2129. ):
  2130. """Request the list of media in a certain order. Assert that order is what
  2131. we expect
  2132. Args:
  2133. expected_media_list: The list of media_ids in the order we expect to get
  2134. back from the server
  2135. order_by: The type of ordering to give the server
  2136. dir: The direction of ordering to give the server
  2137. """
  2138. url = self.url + "?"
  2139. if order_by is not None:
  2140. url += "order_by=%s&" % (order_by,)
  2141. if dir is not None and dir in ("b", "f"):
  2142. url += "dir=%s" % (dir,)
  2143. channel = self.make_request(
  2144. "GET",
  2145. url.encode("ascii"),
  2146. access_token=self.admin_user_tok,
  2147. )
  2148. self.assertEqual(200, channel.code, msg=channel.json_body)
  2149. self.assertEqual(channel.json_body["total"], len(expected_media_list))
  2150. returned_order = [row["media_id"] for row in channel.json_body["media"]]
  2151. self.assertEqual(expected_media_list, returned_order)
  2152. self._check_fields(channel.json_body["media"])
  2153. class UserTokenRestTestCase(unittest.HomeserverTestCase):
  2154. """Test for /_synapse/admin/v1/users/<user>/login"""
  2155. servlets = [
  2156. synapse.rest.admin.register_servlets,
  2157. login.register_servlets,
  2158. sync.register_servlets,
  2159. room.register_servlets,
  2160. devices.register_servlets,
  2161. logout.register_servlets,
  2162. ]
  2163. def prepare(self, reactor, clock, hs):
  2164. self.store = hs.get_datastore()
  2165. self.admin_user = self.register_user("admin", "pass", admin=True)
  2166. self.admin_user_tok = self.login("admin", "pass")
  2167. self.other_user = self.register_user("user", "pass")
  2168. self.other_user_tok = self.login("user", "pass")
  2169. self.url = "/_synapse/admin/v1/users/%s/login" % urllib.parse.quote(
  2170. self.other_user
  2171. )
  2172. def _get_token(self) -> str:
  2173. channel = self.make_request(
  2174. "POST", self.url, b"{}", access_token=self.admin_user_tok
  2175. )
  2176. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2177. return channel.json_body["access_token"]
  2178. def test_no_auth(self):
  2179. """Try to login as a user without authentication."""
  2180. channel = self.make_request("POST", self.url, b"{}")
  2181. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2182. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2183. def test_not_admin(self):
  2184. """Try to login as a user as a non-admin user."""
  2185. channel = self.make_request(
  2186. "POST", self.url, b"{}", access_token=self.other_user_tok
  2187. )
  2188. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  2189. def test_send_event(self):
  2190. """Test that sending event as a user works."""
  2191. # Create a room.
  2192. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  2193. # Login in as the user
  2194. puppet_token = self._get_token()
  2195. # Test that sending works, and generates the event as the right user.
  2196. resp = self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  2197. event_id = resp["event_id"]
  2198. event = self.get_success(self.store.get_event(event_id))
  2199. self.assertEqual(event.sender, self.other_user)
  2200. def test_devices(self):
  2201. """Tests that logging in as a user doesn't create a new device for them."""
  2202. # Login in as the user
  2203. self._get_token()
  2204. # Check that we don't see a new device in our devices list
  2205. channel = self.make_request(
  2206. "GET", "devices", b"{}", access_token=self.other_user_tok
  2207. )
  2208. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2209. # We should only see the one device (from the login in `prepare`)
  2210. self.assertEqual(len(channel.json_body["devices"]), 1)
  2211. def test_logout(self):
  2212. """Test that calling `/logout` with the token works."""
  2213. # Login in as the user
  2214. puppet_token = self._get_token()
  2215. # Test that we can successfully make a request
  2216. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2217. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2218. # Logout with the puppet token
  2219. channel = self.make_request("POST", "logout", b"{}", access_token=puppet_token)
  2220. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2221. # The puppet token should no longer work
  2222. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2223. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2224. # .. but the real user's tokens should still work
  2225. channel = self.make_request(
  2226. "GET", "devices", b"{}", access_token=self.other_user_tok
  2227. )
  2228. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2229. def test_user_logout_all(self):
  2230. """Tests that the target user calling `/logout/all` does *not* expire
  2231. the token.
  2232. """
  2233. # Login in as the user
  2234. puppet_token = self._get_token()
  2235. # Test that we can successfully make a request
  2236. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2237. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2238. # Logout all with the real user token
  2239. channel = self.make_request(
  2240. "POST", "logout/all", b"{}", access_token=self.other_user_tok
  2241. )
  2242. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2243. # The puppet token should still work
  2244. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2245. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2246. # .. but the real user's tokens shouldn't
  2247. channel = self.make_request(
  2248. "GET", "devices", b"{}", access_token=self.other_user_tok
  2249. )
  2250. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2251. def test_admin_logout_all(self):
  2252. """Tests that the admin user calling `/logout/all` does expire the
  2253. token.
  2254. """
  2255. # Login in as the user
  2256. puppet_token = self._get_token()
  2257. # Test that we can successfully make a request
  2258. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2259. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2260. # Logout all with the admin user token
  2261. channel = self.make_request(
  2262. "POST", "logout/all", b"{}", access_token=self.admin_user_tok
  2263. )
  2264. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2265. # The puppet token should no longer work
  2266. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2267. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2268. # .. but the real user's tokens should still work
  2269. channel = self.make_request(
  2270. "GET", "devices", b"{}", access_token=self.other_user_tok
  2271. )
  2272. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2273. @unittest.override_config(
  2274. {
  2275. "public_baseurl": "https://example.org/",
  2276. "user_consent": {
  2277. "version": "1.0",
  2278. "policy_name": "My Cool Privacy Policy",
  2279. "template_dir": "/",
  2280. "require_at_registration": True,
  2281. "block_events_error": "You should accept the policy",
  2282. },
  2283. "form_secret": "123secret",
  2284. }
  2285. )
  2286. def test_consent(self):
  2287. """Test that sending a message is not subject to the privacy policies."""
  2288. # Have the admin user accept the terms.
  2289. self.get_success(self.store.user_set_consent_version(self.admin_user, "1.0"))
  2290. # First, cheekily accept the terms and create a room
  2291. self.get_success(self.store.user_set_consent_version(self.other_user, "1.0"))
  2292. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  2293. self.helper.send_event(room_id, "com.example.test", tok=self.other_user_tok)
  2294. # Now unaccept it and check that we can't send an event
  2295. self.get_success(self.store.user_set_consent_version(self.other_user, "0.0"))
  2296. self.helper.send_event(
  2297. room_id, "com.example.test", tok=self.other_user_tok, expect_code=403
  2298. )
  2299. # Login in as the user
  2300. puppet_token = self._get_token()
  2301. # Sending an event on their behalf should work fine
  2302. self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  2303. @override_config(
  2304. {"limit_usage_by_mau": True, "max_mau_value": 1, "mau_trial_days": 0}
  2305. )
  2306. def test_mau_limit(self):
  2307. # Create a room as the admin user. This will bump the monthly active users to 1.
  2308. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  2309. # Trying to join as the other user should fail due to reaching MAU limit.
  2310. self.helper.join(
  2311. room_id, user=self.other_user, tok=self.other_user_tok, expect_code=403
  2312. )
  2313. # Logging in as the other user and joining a room should work, even
  2314. # though the MAU limit would stop the user doing so.
  2315. puppet_token = self._get_token()
  2316. self.helper.join(room_id, user=self.other_user, tok=puppet_token)
  2317. class WhoisRestTestCase(unittest.HomeserverTestCase):
  2318. servlets = [
  2319. synapse.rest.admin.register_servlets,
  2320. login.register_servlets,
  2321. ]
  2322. def prepare(self, reactor, clock, hs):
  2323. self.admin_user = self.register_user("admin", "pass", admin=True)
  2324. self.admin_user_tok = self.login("admin", "pass")
  2325. self.other_user = self.register_user("user", "pass")
  2326. self.url1 = "/_synapse/admin/v1/whois/%s" % urllib.parse.quote(self.other_user)
  2327. self.url2 = "/_matrix/client/r0/admin/whois/%s" % urllib.parse.quote(
  2328. self.other_user
  2329. )
  2330. def test_no_auth(self):
  2331. """
  2332. Try to get information of an user without authentication.
  2333. """
  2334. channel = self.make_request("GET", self.url1, b"{}")
  2335. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2336. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2337. channel = self.make_request("GET", self.url2, b"{}")
  2338. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2339. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2340. def test_requester_is_not_admin(self):
  2341. """
  2342. If the user is not a server admin, an error is returned.
  2343. """
  2344. self.register_user("user2", "pass")
  2345. other_user2_token = self.login("user2", "pass")
  2346. channel = self.make_request(
  2347. "GET",
  2348. self.url1,
  2349. access_token=other_user2_token,
  2350. )
  2351. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  2352. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2353. channel = self.make_request(
  2354. "GET",
  2355. self.url2,
  2356. access_token=other_user2_token,
  2357. )
  2358. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  2359. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2360. def test_user_is_not_local(self):
  2361. """
  2362. Tests that a lookup for a user that is not a local returns a 400
  2363. """
  2364. url1 = "/_synapse/admin/v1/whois/@unknown_person:unknown_domain"
  2365. url2 = "/_matrix/client/r0/admin/whois/@unknown_person:unknown_domain"
  2366. channel = self.make_request(
  2367. "GET",
  2368. url1,
  2369. access_token=self.admin_user_tok,
  2370. )
  2371. self.assertEqual(400, channel.code, msg=channel.json_body)
  2372. self.assertEqual("Can only whois a local user", channel.json_body["error"])
  2373. channel = self.make_request(
  2374. "GET",
  2375. url2,
  2376. access_token=self.admin_user_tok,
  2377. )
  2378. self.assertEqual(400, channel.code, msg=channel.json_body)
  2379. self.assertEqual("Can only whois a local user", channel.json_body["error"])
  2380. def test_get_whois_admin(self):
  2381. """
  2382. The lookup should succeed for an admin.
  2383. """
  2384. channel = self.make_request(
  2385. "GET",
  2386. self.url1,
  2387. access_token=self.admin_user_tok,
  2388. )
  2389. self.assertEqual(200, channel.code, msg=channel.json_body)
  2390. self.assertEqual(self.other_user, channel.json_body["user_id"])
  2391. self.assertIn("devices", channel.json_body)
  2392. channel = self.make_request(
  2393. "GET",
  2394. self.url2,
  2395. access_token=self.admin_user_tok,
  2396. )
  2397. self.assertEqual(200, channel.code, msg=channel.json_body)
  2398. self.assertEqual(self.other_user, channel.json_body["user_id"])
  2399. self.assertIn("devices", channel.json_body)
  2400. def test_get_whois_user(self):
  2401. """
  2402. The lookup should succeed for a normal user looking up their own information.
  2403. """
  2404. other_user_token = self.login("user", "pass")
  2405. channel = self.make_request(
  2406. "GET",
  2407. self.url1,
  2408. access_token=other_user_token,
  2409. )
  2410. self.assertEqual(200, channel.code, msg=channel.json_body)
  2411. self.assertEqual(self.other_user, channel.json_body["user_id"])
  2412. self.assertIn("devices", channel.json_body)
  2413. channel = self.make_request(
  2414. "GET",
  2415. self.url2,
  2416. access_token=other_user_token,
  2417. )
  2418. self.assertEqual(200, channel.code, msg=channel.json_body)
  2419. self.assertEqual(self.other_user, channel.json_body["user_id"])
  2420. self.assertIn("devices", channel.json_body)
  2421. class ShadowBanRestTestCase(unittest.HomeserverTestCase):
  2422. servlets = [
  2423. synapse.rest.admin.register_servlets,
  2424. login.register_servlets,
  2425. ]
  2426. def prepare(self, reactor, clock, hs):
  2427. self.store = hs.get_datastore()
  2428. self.admin_user = self.register_user("admin", "pass", admin=True)
  2429. self.admin_user_tok = self.login("admin", "pass")
  2430. self.other_user = self.register_user("user", "pass")
  2431. self.url = "/_synapse/admin/v1/users/%s/shadow_ban" % urllib.parse.quote(
  2432. self.other_user
  2433. )
  2434. def test_no_auth(self):
  2435. """
  2436. Try to get information of an user without authentication.
  2437. """
  2438. channel = self.make_request("POST", self.url)
  2439. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2440. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2441. def test_requester_is_not_admin(self):
  2442. """
  2443. If the user is not a server admin, an error is returned.
  2444. """
  2445. other_user_token = self.login("user", "pass")
  2446. channel = self.make_request("POST", self.url, access_token=other_user_token)
  2447. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  2448. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2449. def test_user_is_not_local(self):
  2450. """
  2451. Tests that shadow-banning for a user that is not a local returns a 400
  2452. """
  2453. url = "/_synapse/admin/v1/whois/@unknown_person:unknown_domain"
  2454. channel = self.make_request("POST", url, access_token=self.admin_user_tok)
  2455. self.assertEqual(400, channel.code, msg=channel.json_body)
  2456. def test_success(self):
  2457. """
  2458. Shadow-banning should succeed for an admin.
  2459. """
  2460. # The user starts off as not shadow-banned.
  2461. other_user_token = self.login("user", "pass")
  2462. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  2463. self.assertFalse(result.shadow_banned)
  2464. channel = self.make_request("POST", self.url, access_token=self.admin_user_tok)
  2465. self.assertEqual(200, channel.code, msg=channel.json_body)
  2466. self.assertEqual({}, channel.json_body)
  2467. # Ensure the user is shadow-banned (and the cache was cleared).
  2468. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  2469. self.assertTrue(result.shadow_banned)
  2470. class RateLimitTestCase(unittest.HomeserverTestCase):
  2471. servlets = [
  2472. synapse.rest.admin.register_servlets,
  2473. login.register_servlets,
  2474. ]
  2475. def prepare(self, reactor, clock, hs):
  2476. self.store = hs.get_datastore()
  2477. self.admin_user = self.register_user("admin", "pass", admin=True)
  2478. self.admin_user_tok = self.login("admin", "pass")
  2479. self.other_user = self.register_user("user", "pass")
  2480. self.url = (
  2481. "/_synapse/admin/v1/users/%s/override_ratelimit"
  2482. % urllib.parse.quote(self.other_user)
  2483. )
  2484. def test_no_auth(self):
  2485. """
  2486. Try to get information of a user without authentication.
  2487. """
  2488. channel = self.make_request("GET", self.url, b"{}")
  2489. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2490. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2491. channel = self.make_request("POST", self.url, b"{}")
  2492. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2493. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2494. channel = self.make_request("DELETE", self.url, b"{}")
  2495. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2496. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2497. def test_requester_is_no_admin(self):
  2498. """
  2499. If the user is not a server admin, an error is returned.
  2500. """
  2501. other_user_token = self.login("user", "pass")
  2502. channel = self.make_request(
  2503. "GET",
  2504. self.url,
  2505. access_token=other_user_token,
  2506. )
  2507. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  2508. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2509. channel = self.make_request(
  2510. "POST",
  2511. self.url,
  2512. access_token=other_user_token,
  2513. )
  2514. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  2515. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2516. channel = self.make_request(
  2517. "DELETE",
  2518. self.url,
  2519. access_token=other_user_token,
  2520. )
  2521. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  2522. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2523. def test_user_does_not_exist(self):
  2524. """
  2525. Tests that a lookup for a user that does not exist returns a 404
  2526. """
  2527. url = "/_synapse/admin/v1/users/@unknown_person:test/override_ratelimit"
  2528. channel = self.make_request(
  2529. "GET",
  2530. url,
  2531. access_token=self.admin_user_tok,
  2532. )
  2533. self.assertEqual(404, channel.code, msg=channel.json_body)
  2534. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  2535. channel = self.make_request(
  2536. "POST",
  2537. url,
  2538. access_token=self.admin_user_tok,
  2539. )
  2540. self.assertEqual(404, channel.code, msg=channel.json_body)
  2541. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  2542. channel = self.make_request(
  2543. "DELETE",
  2544. url,
  2545. access_token=self.admin_user_tok,
  2546. )
  2547. self.assertEqual(404, channel.code, msg=channel.json_body)
  2548. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  2549. def test_user_is_not_local(self):
  2550. """
  2551. Tests that a lookup for a user that is not a local returns a 400
  2552. """
  2553. url = (
  2554. "/_synapse/admin/v1/users/@unknown_person:unknown_domain/override_ratelimit"
  2555. )
  2556. channel = self.make_request(
  2557. "GET",
  2558. url,
  2559. access_token=self.admin_user_tok,
  2560. )
  2561. self.assertEqual(400, channel.code, msg=channel.json_body)
  2562. self.assertEqual("Can only lookup local users", channel.json_body["error"])
  2563. channel = self.make_request(
  2564. "POST",
  2565. url,
  2566. access_token=self.admin_user_tok,
  2567. )
  2568. self.assertEqual(400, channel.code, msg=channel.json_body)
  2569. self.assertEqual(
  2570. "Only local users can be ratelimited", channel.json_body["error"]
  2571. )
  2572. channel = self.make_request(
  2573. "DELETE",
  2574. url,
  2575. access_token=self.admin_user_tok,
  2576. )
  2577. self.assertEqual(400, channel.code, msg=channel.json_body)
  2578. self.assertEqual(
  2579. "Only local users can be ratelimited", channel.json_body["error"]
  2580. )
  2581. def test_invalid_parameter(self):
  2582. """
  2583. If parameters are invalid, an error is returned.
  2584. """
  2585. # messages_per_second is a string
  2586. channel = self.make_request(
  2587. "POST",
  2588. self.url,
  2589. access_token=self.admin_user_tok,
  2590. content={"messages_per_second": "string"},
  2591. )
  2592. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  2593. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2594. # messages_per_second is negative
  2595. channel = self.make_request(
  2596. "POST",
  2597. self.url,
  2598. access_token=self.admin_user_tok,
  2599. content={"messages_per_second": -1},
  2600. )
  2601. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  2602. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2603. # burst_count is a string
  2604. channel = self.make_request(
  2605. "POST",
  2606. self.url,
  2607. access_token=self.admin_user_tok,
  2608. content={"burst_count": "string"},
  2609. )
  2610. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  2611. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2612. # burst_count is negative
  2613. channel = self.make_request(
  2614. "POST",
  2615. self.url,
  2616. access_token=self.admin_user_tok,
  2617. content={"burst_count": -1},
  2618. )
  2619. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  2620. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2621. def test_return_zero_when_null(self):
  2622. """
  2623. If values in database are `null` API should return an int `0`
  2624. """
  2625. self.get_success(
  2626. self.store.db_pool.simple_upsert(
  2627. table="ratelimit_override",
  2628. keyvalues={"user_id": self.other_user},
  2629. values={
  2630. "messages_per_second": None,
  2631. "burst_count": None,
  2632. },
  2633. )
  2634. )
  2635. # request status
  2636. channel = self.make_request(
  2637. "GET",
  2638. self.url,
  2639. access_token=self.admin_user_tok,
  2640. )
  2641. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2642. self.assertEqual(0, channel.json_body["messages_per_second"])
  2643. self.assertEqual(0, channel.json_body["burst_count"])
  2644. def test_success(self):
  2645. """
  2646. Rate-limiting (set/update/delete) should succeed for an admin.
  2647. """
  2648. # request status
  2649. channel = self.make_request(
  2650. "GET",
  2651. self.url,
  2652. access_token=self.admin_user_tok,
  2653. )
  2654. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2655. self.assertNotIn("messages_per_second", channel.json_body)
  2656. self.assertNotIn("burst_count", channel.json_body)
  2657. # set ratelimit
  2658. channel = self.make_request(
  2659. "POST",
  2660. self.url,
  2661. access_token=self.admin_user_tok,
  2662. content={"messages_per_second": 10, "burst_count": 11},
  2663. )
  2664. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2665. self.assertEqual(10, channel.json_body["messages_per_second"])
  2666. self.assertEqual(11, channel.json_body["burst_count"])
  2667. # update ratelimit
  2668. channel = self.make_request(
  2669. "POST",
  2670. self.url,
  2671. access_token=self.admin_user_tok,
  2672. content={"messages_per_second": 20, "burst_count": 21},
  2673. )
  2674. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2675. self.assertEqual(20, channel.json_body["messages_per_second"])
  2676. self.assertEqual(21, channel.json_body["burst_count"])
  2677. # request status
  2678. channel = self.make_request(
  2679. "GET",
  2680. self.url,
  2681. access_token=self.admin_user_tok,
  2682. )
  2683. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2684. self.assertEqual(20, channel.json_body["messages_per_second"])
  2685. self.assertEqual(21, channel.json_body["burst_count"])
  2686. # delete ratelimit
  2687. channel = self.make_request(
  2688. "DELETE",
  2689. self.url,
  2690. access_token=self.admin_user_tok,
  2691. )
  2692. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2693. self.assertNotIn("messages_per_second", channel.json_body)
  2694. self.assertNotIn("burst_count", channel.json_body)
  2695. # request status
  2696. channel = self.make_request(
  2697. "GET",
  2698. self.url,
  2699. access_token=self.admin_user_tok,
  2700. )
  2701. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2702. self.assertNotIn("messages_per_second", channel.json_body)
  2703. self.assertNotIn("burst_count", channel.json_body)