test_user.py 118 KB

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