test_user.py 148 KB

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