test_user.py 146 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995
  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. def test_deactivate_user_erase_false(self) -> None:
  840. """
  841. Test deactivating a user and set `erase` to `false`
  842. """
  843. # Get user
  844. channel = self.make_request(
  845. "GET",
  846. self.url_other_user,
  847. access_token=self.admin_user_tok,
  848. )
  849. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  850. self.assertEqual("@user:test", channel.json_body["name"])
  851. self.assertEqual(False, channel.json_body["deactivated"])
  852. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  853. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  854. self.assertEqual("User1", channel.json_body["displayname"])
  855. # Deactivate user
  856. channel = self.make_request(
  857. "POST",
  858. self.url,
  859. access_token=self.admin_user_tok,
  860. content={"erase": False},
  861. )
  862. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  863. # Get user
  864. channel = self.make_request(
  865. "GET",
  866. self.url_other_user,
  867. access_token=self.admin_user_tok,
  868. )
  869. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  870. self.assertEqual("@user:test", channel.json_body["name"])
  871. self.assertEqual(True, channel.json_body["deactivated"])
  872. self.assertEqual(0, len(channel.json_body["threepids"]))
  873. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  874. self.assertEqual("User1", channel.json_body["displayname"])
  875. self._is_erased("@user:test", False)
  876. def test_deactivate_user_erase_true_no_profile(self) -> None:
  877. """
  878. Test deactivating a user and set `erase` to `true`
  879. if user has no profile information (stored in the database table `profiles`).
  880. """
  881. # Users normally have an entry in `profiles`, but occasionally they are created without one.
  882. # To test deactivation for users without a profile, we delete the profile information for our user.
  883. self.get_success(
  884. self.store.db_pool.simple_delete_one(
  885. table="profiles", keyvalues={"user_id": "user"}
  886. )
  887. )
  888. # Get user
  889. channel = self.make_request(
  890. "GET",
  891. self.url_other_user,
  892. access_token=self.admin_user_tok,
  893. )
  894. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  895. self.assertEqual("@user:test", channel.json_body["name"])
  896. self.assertEqual(False, channel.json_body["deactivated"])
  897. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  898. self.assertIsNone(channel.json_body["avatar_url"])
  899. self.assertIsNone(channel.json_body["displayname"])
  900. # Deactivate and erase user
  901. channel = self.make_request(
  902. "POST",
  903. self.url,
  904. access_token=self.admin_user_tok,
  905. content={"erase": True},
  906. )
  907. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  908. # Get user
  909. channel = self.make_request(
  910. "GET",
  911. self.url_other_user,
  912. access_token=self.admin_user_tok,
  913. )
  914. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  915. self.assertEqual("@user:test", channel.json_body["name"])
  916. self.assertEqual(True, channel.json_body["deactivated"])
  917. self.assertEqual(0, len(channel.json_body["threepids"]))
  918. self.assertIsNone(channel.json_body["avatar_url"])
  919. self.assertIsNone(channel.json_body["displayname"])
  920. self._is_erased("@user:test", True)
  921. def _is_erased(self, user_id: str, expect: bool) -> None:
  922. """Assert that the user is erased or not"""
  923. d = self.store.is_user_erased(user_id)
  924. if expect:
  925. self.assertTrue(self.get_success(d))
  926. else:
  927. self.assertFalse(self.get_success(d))
  928. class UserRestTestCase(unittest.HomeserverTestCase):
  929. servlets = [
  930. synapse.rest.admin.register_servlets,
  931. login.register_servlets,
  932. sync.register_servlets,
  933. ]
  934. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  935. self.store = hs.get_datastores().main
  936. self.auth_handler = hs.get_auth_handler()
  937. # create users and get access tokens
  938. # regardless of whether password login or SSO is allowed
  939. self.admin_user = self.register_user("admin", "pass", admin=True)
  940. self.admin_user_tok = self.get_success(
  941. self.auth_handler.create_access_token_for_user_id(
  942. self.admin_user, device_id=None, valid_until_ms=None
  943. )
  944. )
  945. self.other_user = self.register_user("user", "pass", displayname="User")
  946. self.other_user_token = self.get_success(
  947. self.auth_handler.create_access_token_for_user_id(
  948. self.other_user, device_id=None, valid_until_ms=None
  949. )
  950. )
  951. self.url_prefix = "/_synapse/admin/v2/users/%s"
  952. self.url_other_user = self.url_prefix % self.other_user
  953. def test_requester_is_no_admin(self) -> None:
  954. """
  955. If the user is not a server admin, an error is returned.
  956. """
  957. url = self.url_prefix % "@bob:test"
  958. channel = self.make_request(
  959. "GET",
  960. url,
  961. access_token=self.other_user_token,
  962. )
  963. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  964. self.assertEqual("You are not a server admin", channel.json_body["error"])
  965. channel = self.make_request(
  966. "PUT",
  967. url,
  968. access_token=self.other_user_token,
  969. content=b"{}",
  970. )
  971. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  972. self.assertEqual("You are not a server admin", channel.json_body["error"])
  973. def test_user_does_not_exist(self) -> None:
  974. """
  975. Tests that a lookup for a user that does not exist returns a HTTPStatus.NOT_FOUND
  976. """
  977. channel = self.make_request(
  978. "GET",
  979. self.url_prefix % "@unknown_person:test",
  980. access_token=self.admin_user_tok,
  981. )
  982. self.assertEqual(HTTPStatus.NOT_FOUND, channel.code, msg=channel.json_body)
  983. self.assertEqual("M_NOT_FOUND", channel.json_body["errcode"])
  984. def test_invalid_parameter(self) -> None:
  985. """
  986. If parameters are invalid, an error is returned.
  987. """
  988. # admin not bool
  989. channel = self.make_request(
  990. "PUT",
  991. self.url_other_user,
  992. access_token=self.admin_user_tok,
  993. content={"admin": "not_bool"},
  994. )
  995. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  996. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  997. # deactivated not bool
  998. channel = self.make_request(
  999. "PUT",
  1000. self.url_other_user,
  1001. access_token=self.admin_user_tok,
  1002. content={"deactivated": "not_bool"},
  1003. )
  1004. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1005. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1006. # password not str
  1007. channel = self.make_request(
  1008. "PUT",
  1009. self.url_other_user,
  1010. access_token=self.admin_user_tok,
  1011. content={"password": True},
  1012. )
  1013. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1014. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1015. # password not length
  1016. channel = self.make_request(
  1017. "PUT",
  1018. self.url_other_user,
  1019. access_token=self.admin_user_tok,
  1020. content={"password": "x" * 513},
  1021. )
  1022. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1023. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1024. # user_type not valid
  1025. channel = self.make_request(
  1026. "PUT",
  1027. self.url_other_user,
  1028. access_token=self.admin_user_tok,
  1029. content={"user_type": "new type"},
  1030. )
  1031. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1032. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1033. # external_ids not valid
  1034. channel = self.make_request(
  1035. "PUT",
  1036. self.url_other_user,
  1037. access_token=self.admin_user_tok,
  1038. content={
  1039. "external_ids": {"auth_provider": "prov", "wrong_external_id": "id"}
  1040. },
  1041. )
  1042. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1043. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1044. channel = self.make_request(
  1045. "PUT",
  1046. self.url_other_user,
  1047. access_token=self.admin_user_tok,
  1048. content={"external_ids": {"external_id": "id"}},
  1049. )
  1050. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1051. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1052. # threepids not valid
  1053. channel = self.make_request(
  1054. "PUT",
  1055. self.url_other_user,
  1056. access_token=self.admin_user_tok,
  1057. content={"threepids": {"medium": "email", "wrong_address": "id"}},
  1058. )
  1059. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1060. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1061. channel = self.make_request(
  1062. "PUT",
  1063. self.url_other_user,
  1064. access_token=self.admin_user_tok,
  1065. content={"threepids": {"address": "value"}},
  1066. )
  1067. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1068. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1069. def test_get_user(self) -> None:
  1070. """
  1071. Test a simple get of a user.
  1072. """
  1073. channel = self.make_request(
  1074. "GET",
  1075. self.url_other_user,
  1076. access_token=self.admin_user_tok,
  1077. )
  1078. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1079. self.assertEqual("@user:test", channel.json_body["name"])
  1080. self.assertEqual("User", channel.json_body["displayname"])
  1081. self._check_fields(channel.json_body)
  1082. def test_create_server_admin(self) -> None:
  1083. """
  1084. Check that a new admin user is created successfully.
  1085. """
  1086. url = self.url_prefix % "@bob:test"
  1087. # Create user (server admin)
  1088. body = {
  1089. "password": "abc123",
  1090. "admin": True,
  1091. "displayname": "Bob's name",
  1092. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1093. "avatar_url": "mxc://fibble/wibble",
  1094. }
  1095. channel = self.make_request(
  1096. "PUT",
  1097. url,
  1098. access_token=self.admin_user_tok,
  1099. content=body,
  1100. )
  1101. self.assertEqual(201, channel.code, msg=channel.json_body)
  1102. self.assertEqual("@bob:test", channel.json_body["name"])
  1103. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1104. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1105. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1106. self.assertTrue(channel.json_body["admin"])
  1107. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1108. self._check_fields(channel.json_body)
  1109. # Get user
  1110. channel = self.make_request(
  1111. "GET",
  1112. url,
  1113. access_token=self.admin_user_tok,
  1114. )
  1115. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1116. self.assertEqual("@bob:test", channel.json_body["name"])
  1117. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1118. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1119. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1120. self.assertTrue(channel.json_body["admin"])
  1121. self.assertFalse(channel.json_body["is_guest"])
  1122. self.assertFalse(channel.json_body["deactivated"])
  1123. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1124. self._check_fields(channel.json_body)
  1125. def test_create_user(self) -> None:
  1126. """
  1127. Check that a new regular user is created successfully.
  1128. """
  1129. url = self.url_prefix % "@bob:test"
  1130. # Create user
  1131. body = {
  1132. "password": "abc123",
  1133. "admin": False,
  1134. "displayname": "Bob's name",
  1135. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1136. "external_ids": [
  1137. {
  1138. "external_id": "external_id1",
  1139. "auth_provider": "auth_provider1",
  1140. },
  1141. ],
  1142. "avatar_url": "mxc://fibble/wibble",
  1143. }
  1144. channel = self.make_request(
  1145. "PUT",
  1146. url,
  1147. access_token=self.admin_user_tok,
  1148. content=body,
  1149. )
  1150. self.assertEqual(201, channel.code, msg=channel.json_body)
  1151. self.assertEqual("@bob:test", channel.json_body["name"])
  1152. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1153. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1154. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1155. self.assertEqual(1, len(channel.json_body["threepids"]))
  1156. self.assertEqual(
  1157. "external_id1", channel.json_body["external_ids"][0]["external_id"]
  1158. )
  1159. self.assertEqual(
  1160. "auth_provider1", channel.json_body["external_ids"][0]["auth_provider"]
  1161. )
  1162. self.assertEqual(1, len(channel.json_body["external_ids"]))
  1163. self.assertFalse(channel.json_body["admin"])
  1164. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1165. self._check_fields(channel.json_body)
  1166. # Get user
  1167. channel = self.make_request(
  1168. "GET",
  1169. url,
  1170. access_token=self.admin_user_tok,
  1171. )
  1172. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1173. self.assertEqual("@bob:test", channel.json_body["name"])
  1174. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1175. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1176. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1177. self.assertFalse(channel.json_body["admin"])
  1178. self.assertFalse(channel.json_body["is_guest"])
  1179. self.assertFalse(channel.json_body["deactivated"])
  1180. self.assertFalse(channel.json_body["shadow_banned"])
  1181. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1182. self._check_fields(channel.json_body)
  1183. @override_config(
  1184. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  1185. )
  1186. def test_create_user_mau_limit_reached_active_admin(self) -> None:
  1187. """
  1188. Check that an admin can register a new user via the admin API
  1189. even if the MAU limit is reached.
  1190. Admin user was active before creating user.
  1191. """
  1192. handler = self.hs.get_registration_handler()
  1193. # Sync to set admin user to active
  1194. # before limit of monthly active users is reached
  1195. channel = self.make_request("GET", "/sync", access_token=self.admin_user_tok)
  1196. if channel.code != HTTPStatus.OK:
  1197. raise HttpResponseException(
  1198. channel.code, channel.result["reason"], channel.json_body
  1199. )
  1200. # Set monthly active users to the limit
  1201. self.store.get_monthly_active_count = Mock(
  1202. return_value=make_awaitable(self.hs.config.server.max_mau_value)
  1203. )
  1204. # Check that the blocking of monthly active users is working as expected
  1205. # The registration of a new user fails due to the limit
  1206. self.get_failure(
  1207. handler.register_user(localpart="local_part"), ResourceLimitError
  1208. )
  1209. # Register new user with admin API
  1210. url = self.url_prefix % "@bob:test"
  1211. # Create user
  1212. channel = self.make_request(
  1213. "PUT",
  1214. url,
  1215. access_token=self.admin_user_tok,
  1216. content={"password": "abc123", "admin": False},
  1217. )
  1218. self.assertEqual(201, channel.code, msg=channel.json_body)
  1219. self.assertEqual("@bob:test", channel.json_body["name"])
  1220. self.assertFalse(channel.json_body["admin"])
  1221. @override_config(
  1222. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  1223. )
  1224. def test_create_user_mau_limit_reached_passive_admin(self) -> None:
  1225. """
  1226. Check that an admin can register a new user via the admin API
  1227. even if the MAU limit is reached.
  1228. Admin user was not active before creating user.
  1229. """
  1230. handler = self.hs.get_registration_handler()
  1231. # Set monthly active users to the limit
  1232. self.store.get_monthly_active_count = Mock(
  1233. return_value=make_awaitable(self.hs.config.server.max_mau_value)
  1234. )
  1235. # Check that the blocking of monthly active users is working as expected
  1236. # The registration of a new user fails due to the limit
  1237. self.get_failure(
  1238. handler.register_user(localpart="local_part"), ResourceLimitError
  1239. )
  1240. # Register new user with admin API
  1241. url = self.url_prefix % "@bob:test"
  1242. # Create user
  1243. channel = self.make_request(
  1244. "PUT",
  1245. url,
  1246. access_token=self.admin_user_tok,
  1247. content={"password": "abc123", "admin": False},
  1248. )
  1249. # Admin user is not blocked by mau anymore
  1250. self.assertEqual(201, channel.code, msg=channel.json_body)
  1251. self.assertEqual("@bob:test", channel.json_body["name"])
  1252. self.assertFalse(channel.json_body["admin"])
  1253. @override_config(
  1254. {
  1255. "email": {
  1256. "enable_notifs": True,
  1257. "notif_for_new_users": True,
  1258. "notif_from": "test@example.com",
  1259. },
  1260. "public_baseurl": "https://example.com",
  1261. }
  1262. )
  1263. def test_create_user_email_notif_for_new_users(self) -> None:
  1264. """
  1265. Check that a new regular user is created successfully and
  1266. got an email pusher.
  1267. """
  1268. url = self.url_prefix % "@bob:test"
  1269. # Create user
  1270. body = {
  1271. "password": "abc123",
  1272. # Note that the given email is not in canonical form.
  1273. "threepids": [{"medium": "email", "address": "Bob@bob.bob"}],
  1274. }
  1275. channel = self.make_request(
  1276. "PUT",
  1277. url,
  1278. access_token=self.admin_user_tok,
  1279. content=body,
  1280. )
  1281. self.assertEqual(201, channel.code, msg=channel.json_body)
  1282. self.assertEqual("@bob:test", channel.json_body["name"])
  1283. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1284. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1285. pushers = self.get_success(
  1286. self.store.get_pushers_by({"user_name": "@bob:test"})
  1287. )
  1288. pushers = list(pushers)
  1289. self.assertEqual(len(pushers), 1)
  1290. self.assertEqual("@bob:test", pushers[0].user_name)
  1291. @override_config(
  1292. {
  1293. "email": {
  1294. "enable_notifs": False,
  1295. "notif_for_new_users": False,
  1296. "notif_from": "test@example.com",
  1297. },
  1298. "public_baseurl": "https://example.com",
  1299. }
  1300. )
  1301. def test_create_user_email_no_notif_for_new_users(self) -> None:
  1302. """
  1303. Check that a new regular user is created successfully and
  1304. got not an email pusher.
  1305. """
  1306. url = self.url_prefix % "@bob:test"
  1307. # Create user
  1308. body = {
  1309. "password": "abc123",
  1310. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1311. }
  1312. channel = self.make_request(
  1313. "PUT",
  1314. url,
  1315. access_token=self.admin_user_tok,
  1316. content=body,
  1317. )
  1318. self.assertEqual(201, channel.code, msg=channel.json_body)
  1319. self.assertEqual("@bob:test", channel.json_body["name"])
  1320. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1321. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1322. pushers = self.get_success(
  1323. self.store.get_pushers_by({"user_name": "@bob:test"})
  1324. )
  1325. pushers = list(pushers)
  1326. self.assertEqual(len(pushers), 0)
  1327. def test_set_password(self) -> None:
  1328. """
  1329. Test setting a new password for another user.
  1330. """
  1331. # Change password
  1332. channel = self.make_request(
  1333. "PUT",
  1334. self.url_other_user,
  1335. access_token=self.admin_user_tok,
  1336. content={"password": "hahaha"},
  1337. )
  1338. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1339. self._check_fields(channel.json_body)
  1340. def test_set_displayname(self) -> None:
  1341. """
  1342. Test setting the displayname of another user.
  1343. """
  1344. # Modify user
  1345. channel = self.make_request(
  1346. "PUT",
  1347. self.url_other_user,
  1348. access_token=self.admin_user_tok,
  1349. content={"displayname": "foobar"},
  1350. )
  1351. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1352. self.assertEqual("@user:test", channel.json_body["name"])
  1353. self.assertEqual("foobar", channel.json_body["displayname"])
  1354. # Get user
  1355. channel = self.make_request(
  1356. "GET",
  1357. self.url_other_user,
  1358. access_token=self.admin_user_tok,
  1359. )
  1360. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1361. self.assertEqual("@user:test", channel.json_body["name"])
  1362. self.assertEqual("foobar", channel.json_body["displayname"])
  1363. def test_set_threepid(self) -> None:
  1364. """
  1365. Test setting threepid for an other user.
  1366. """
  1367. # Add two threepids to user
  1368. channel = self.make_request(
  1369. "PUT",
  1370. self.url_other_user,
  1371. access_token=self.admin_user_tok,
  1372. content={
  1373. "threepids": [
  1374. {"medium": "email", "address": "bob1@bob.bob"},
  1375. {"medium": "email", "address": "bob2@bob.bob"},
  1376. ],
  1377. },
  1378. )
  1379. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1380. self.assertEqual("@user:test", channel.json_body["name"])
  1381. self.assertEqual(2, len(channel.json_body["threepids"]))
  1382. # result does not always have the same sort order, therefore it becomes sorted
  1383. sorted_result = sorted(
  1384. channel.json_body["threepids"], key=lambda k: k["address"]
  1385. )
  1386. self.assertEqual("email", sorted_result[0]["medium"])
  1387. self.assertEqual("bob1@bob.bob", sorted_result[0]["address"])
  1388. self.assertEqual("email", sorted_result[1]["medium"])
  1389. self.assertEqual("bob2@bob.bob", sorted_result[1]["address"])
  1390. self._check_fields(channel.json_body)
  1391. # Set a new and remove a threepid
  1392. channel = self.make_request(
  1393. "PUT",
  1394. self.url_other_user,
  1395. access_token=self.admin_user_tok,
  1396. content={
  1397. "threepids": [
  1398. {"medium": "email", "address": "bob2@bob.bob"},
  1399. {"medium": "email", "address": "bob3@bob.bob"},
  1400. ],
  1401. },
  1402. )
  1403. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1404. self.assertEqual("@user:test", channel.json_body["name"])
  1405. self.assertEqual(2, len(channel.json_body["threepids"]))
  1406. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1407. self.assertEqual("bob2@bob.bob", channel.json_body["threepids"][0]["address"])
  1408. self.assertEqual("email", channel.json_body["threepids"][1]["medium"])
  1409. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][1]["address"])
  1410. self._check_fields(channel.json_body)
  1411. # Get user
  1412. channel = self.make_request(
  1413. "GET",
  1414. self.url_other_user,
  1415. access_token=self.admin_user_tok,
  1416. )
  1417. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1418. self.assertEqual("@user:test", channel.json_body["name"])
  1419. self.assertEqual(2, len(channel.json_body["threepids"]))
  1420. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1421. self.assertEqual("bob2@bob.bob", channel.json_body["threepids"][0]["address"])
  1422. self.assertEqual("email", channel.json_body["threepids"][1]["medium"])
  1423. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][1]["address"])
  1424. self._check_fields(channel.json_body)
  1425. # Remove threepids
  1426. channel = self.make_request(
  1427. "PUT",
  1428. self.url_other_user,
  1429. access_token=self.admin_user_tok,
  1430. content={"threepids": []},
  1431. )
  1432. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1433. self.assertEqual("@user:test", channel.json_body["name"])
  1434. self.assertEqual(0, len(channel.json_body["threepids"]))
  1435. self._check_fields(channel.json_body)
  1436. def test_set_duplicate_threepid(self) -> None:
  1437. """
  1438. Test setting the same threepid for a second user.
  1439. First user loses and second user gets mapping of this threepid.
  1440. """
  1441. # create a user to set a threepid
  1442. first_user = self.register_user("first_user", "pass")
  1443. url_first_user = self.url_prefix % first_user
  1444. # Add threepid to first user
  1445. channel = self.make_request(
  1446. "PUT",
  1447. url_first_user,
  1448. access_token=self.admin_user_tok,
  1449. content={
  1450. "threepids": [
  1451. {"medium": "email", "address": "bob1@bob.bob"},
  1452. ],
  1453. },
  1454. )
  1455. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1456. self.assertEqual(first_user, channel.json_body["name"])
  1457. self.assertEqual(1, len(channel.json_body["threepids"]))
  1458. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1459. self.assertEqual("bob1@bob.bob", channel.json_body["threepids"][0]["address"])
  1460. self._check_fields(channel.json_body)
  1461. # Add threepids to other user
  1462. channel = self.make_request(
  1463. "PUT",
  1464. self.url_other_user,
  1465. access_token=self.admin_user_tok,
  1466. content={
  1467. "threepids": [
  1468. {"medium": "email", "address": "bob2@bob.bob"},
  1469. ],
  1470. },
  1471. )
  1472. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1473. self.assertEqual("@user:test", channel.json_body["name"])
  1474. self.assertEqual(1, len(channel.json_body["threepids"]))
  1475. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1476. self.assertEqual("bob2@bob.bob", channel.json_body["threepids"][0]["address"])
  1477. self._check_fields(channel.json_body)
  1478. # Add two new threepids to other user
  1479. # one is used by first_user
  1480. channel = self.make_request(
  1481. "PUT",
  1482. self.url_other_user,
  1483. access_token=self.admin_user_tok,
  1484. content={
  1485. "threepids": [
  1486. {"medium": "email", "address": "bob1@bob.bob"},
  1487. {"medium": "email", "address": "bob3@bob.bob"},
  1488. ],
  1489. },
  1490. )
  1491. # other user has this two threepids
  1492. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1493. self.assertEqual("@user:test", channel.json_body["name"])
  1494. self.assertEqual(2, len(channel.json_body["threepids"]))
  1495. # result does not always have the same sort order, therefore it becomes sorted
  1496. sorted_result = sorted(
  1497. channel.json_body["threepids"], key=lambda k: k["address"]
  1498. )
  1499. self.assertEqual("email", sorted_result[0]["medium"])
  1500. self.assertEqual("bob1@bob.bob", sorted_result[0]["address"])
  1501. self.assertEqual("email", sorted_result[1]["medium"])
  1502. self.assertEqual("bob3@bob.bob", sorted_result[1]["address"])
  1503. self._check_fields(channel.json_body)
  1504. # first_user has no threepid anymore
  1505. channel = self.make_request(
  1506. "GET",
  1507. url_first_user,
  1508. access_token=self.admin_user_tok,
  1509. )
  1510. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1511. self.assertEqual(first_user, channel.json_body["name"])
  1512. self.assertEqual(0, len(channel.json_body["threepids"]))
  1513. self._check_fields(channel.json_body)
  1514. def test_set_external_id(self) -> None:
  1515. """
  1516. Test setting external id for an other user.
  1517. """
  1518. # Add two external_ids
  1519. channel = self.make_request(
  1520. "PUT",
  1521. self.url_other_user,
  1522. access_token=self.admin_user_tok,
  1523. content={
  1524. "external_ids": [
  1525. {
  1526. "external_id": "external_id1",
  1527. "auth_provider": "auth_provider1",
  1528. },
  1529. {
  1530. "external_id": "external_id2",
  1531. "auth_provider": "auth_provider2",
  1532. },
  1533. ]
  1534. },
  1535. )
  1536. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1537. self.assertEqual("@user:test", channel.json_body["name"])
  1538. self.assertEqual(2, len(channel.json_body["external_ids"]))
  1539. # result does not always have the same sort order, therefore it becomes sorted
  1540. self.assertEqual(
  1541. sorted(channel.json_body["external_ids"], key=lambda k: k["auth_provider"]),
  1542. [
  1543. {"auth_provider": "auth_provider1", "external_id": "external_id1"},
  1544. {"auth_provider": "auth_provider2", "external_id": "external_id2"},
  1545. ],
  1546. )
  1547. self._check_fields(channel.json_body)
  1548. # Set a new and remove an external_id
  1549. channel = self.make_request(
  1550. "PUT",
  1551. self.url_other_user,
  1552. access_token=self.admin_user_tok,
  1553. content={
  1554. "external_ids": [
  1555. {
  1556. "external_id": "external_id2",
  1557. "auth_provider": "auth_provider2",
  1558. },
  1559. {
  1560. "external_id": "external_id3",
  1561. "auth_provider": "auth_provider3",
  1562. },
  1563. ]
  1564. },
  1565. )
  1566. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1567. self.assertEqual("@user:test", channel.json_body["name"])
  1568. self.assertEqual(2, len(channel.json_body["external_ids"]))
  1569. self.assertEqual(
  1570. channel.json_body["external_ids"],
  1571. [
  1572. {"auth_provider": "auth_provider2", "external_id": "external_id2"},
  1573. {"auth_provider": "auth_provider3", "external_id": "external_id3"},
  1574. ],
  1575. )
  1576. self._check_fields(channel.json_body)
  1577. # Get user
  1578. channel = self.make_request(
  1579. "GET",
  1580. self.url_other_user,
  1581. access_token=self.admin_user_tok,
  1582. )
  1583. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1584. self.assertEqual("@user:test", channel.json_body["name"])
  1585. self.assertEqual(2, len(channel.json_body["external_ids"]))
  1586. self.assertEqual(
  1587. channel.json_body["external_ids"],
  1588. [
  1589. {"auth_provider": "auth_provider2", "external_id": "external_id2"},
  1590. {"auth_provider": "auth_provider3", "external_id": "external_id3"},
  1591. ],
  1592. )
  1593. self._check_fields(channel.json_body)
  1594. # Remove external_ids
  1595. channel = self.make_request(
  1596. "PUT",
  1597. self.url_other_user,
  1598. access_token=self.admin_user_tok,
  1599. content={"external_ids": []},
  1600. )
  1601. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1602. self.assertEqual("@user:test", channel.json_body["name"])
  1603. self.assertEqual(0, len(channel.json_body["external_ids"]))
  1604. def test_set_duplicate_external_id(self) -> None:
  1605. """
  1606. Test that setting the same external id for a second user fails and
  1607. external id from user must not be changed.
  1608. """
  1609. # create a user to use an external id
  1610. first_user = self.register_user("first_user", "pass")
  1611. url_first_user = self.url_prefix % first_user
  1612. # Add an external id to first user
  1613. channel = self.make_request(
  1614. "PUT",
  1615. url_first_user,
  1616. access_token=self.admin_user_tok,
  1617. content={
  1618. "external_ids": [
  1619. {
  1620. "external_id": "external_id1",
  1621. "auth_provider": "auth_provider",
  1622. },
  1623. ],
  1624. },
  1625. )
  1626. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1627. self.assertEqual(first_user, channel.json_body["name"])
  1628. self.assertEqual(1, len(channel.json_body["external_ids"]))
  1629. self.assertEqual(
  1630. "external_id1", channel.json_body["external_ids"][0]["external_id"]
  1631. )
  1632. self.assertEqual(
  1633. "auth_provider", channel.json_body["external_ids"][0]["auth_provider"]
  1634. )
  1635. self._check_fields(channel.json_body)
  1636. # Add an external id to other user
  1637. channel = self.make_request(
  1638. "PUT",
  1639. self.url_other_user,
  1640. access_token=self.admin_user_tok,
  1641. content={
  1642. "external_ids": [
  1643. {
  1644. "external_id": "external_id2",
  1645. "auth_provider": "auth_provider",
  1646. },
  1647. ],
  1648. },
  1649. )
  1650. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1651. self.assertEqual("@user:test", channel.json_body["name"])
  1652. self.assertEqual(1, len(channel.json_body["external_ids"]))
  1653. self.assertEqual(
  1654. "external_id2", channel.json_body["external_ids"][0]["external_id"]
  1655. )
  1656. self.assertEqual(
  1657. "auth_provider", channel.json_body["external_ids"][0]["auth_provider"]
  1658. )
  1659. self._check_fields(channel.json_body)
  1660. # Add two new external_ids to other user
  1661. # one is used by first
  1662. channel = self.make_request(
  1663. "PUT",
  1664. self.url_other_user,
  1665. access_token=self.admin_user_tok,
  1666. content={
  1667. "external_ids": [
  1668. {
  1669. "external_id": "external_id1",
  1670. "auth_provider": "auth_provider",
  1671. },
  1672. {
  1673. "external_id": "external_id3",
  1674. "auth_provider": "auth_provider",
  1675. },
  1676. ],
  1677. },
  1678. )
  1679. # must fail
  1680. self.assertEqual(HTTPStatus.CONFLICT, channel.code, msg=channel.json_body)
  1681. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1682. self.assertEqual("External id is already in use.", channel.json_body["error"])
  1683. # other user must not changed
  1684. channel = self.make_request(
  1685. "GET",
  1686. self.url_other_user,
  1687. access_token=self.admin_user_tok,
  1688. )
  1689. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1690. self.assertEqual("@user:test", channel.json_body["name"])
  1691. self.assertEqual(1, len(channel.json_body["external_ids"]))
  1692. self.assertEqual(
  1693. "external_id2", channel.json_body["external_ids"][0]["external_id"]
  1694. )
  1695. self.assertEqual(
  1696. "auth_provider", channel.json_body["external_ids"][0]["auth_provider"]
  1697. )
  1698. self._check_fields(channel.json_body)
  1699. # first user must not changed
  1700. channel = self.make_request(
  1701. "GET",
  1702. url_first_user,
  1703. access_token=self.admin_user_tok,
  1704. )
  1705. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1706. self.assertEqual(first_user, channel.json_body["name"])
  1707. self.assertEqual(1, len(channel.json_body["external_ids"]))
  1708. self.assertEqual(
  1709. "external_id1", channel.json_body["external_ids"][0]["external_id"]
  1710. )
  1711. self.assertEqual(
  1712. "auth_provider", channel.json_body["external_ids"][0]["auth_provider"]
  1713. )
  1714. self._check_fields(channel.json_body)
  1715. def test_deactivate_user(self) -> None:
  1716. """
  1717. Test deactivating another user.
  1718. """
  1719. # set attributes for user
  1720. self.get_success(
  1721. self.store.set_profile_avatar_url("user", "mxc://servername/mediaid")
  1722. )
  1723. self.get_success(
  1724. self.store.user_add_threepid("@user:test", "email", "foo@bar.com", 0, 0)
  1725. )
  1726. # Get user
  1727. channel = self.make_request(
  1728. "GET",
  1729. self.url_other_user,
  1730. access_token=self.admin_user_tok,
  1731. )
  1732. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1733. self.assertEqual("@user:test", channel.json_body["name"])
  1734. self.assertFalse(channel.json_body["deactivated"])
  1735. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  1736. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1737. self.assertEqual("User", channel.json_body["displayname"])
  1738. # Deactivate user
  1739. channel = self.make_request(
  1740. "PUT",
  1741. self.url_other_user,
  1742. access_token=self.admin_user_tok,
  1743. content={"deactivated": True},
  1744. )
  1745. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1746. self.assertEqual("@user:test", channel.json_body["name"])
  1747. self.assertTrue(channel.json_body["deactivated"])
  1748. self.assertEqual(0, len(channel.json_body["threepids"]))
  1749. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1750. self.assertEqual("User", channel.json_body["displayname"])
  1751. # This key was removed intentionally. Ensure it is not accidentally re-included.
  1752. self.assertNotIn("password_hash", channel.json_body)
  1753. # the user is deactivated, the threepid will be deleted
  1754. # Get user
  1755. channel = self.make_request(
  1756. "GET",
  1757. self.url_other_user,
  1758. access_token=self.admin_user_tok,
  1759. )
  1760. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1761. self.assertEqual("@user:test", channel.json_body["name"])
  1762. self.assertTrue(channel.json_body["deactivated"])
  1763. self.assertEqual(0, len(channel.json_body["threepids"]))
  1764. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1765. self.assertEqual("User", channel.json_body["displayname"])
  1766. # This key was removed intentionally. Ensure it is not accidentally re-included.
  1767. self.assertNotIn("password_hash", channel.json_body)
  1768. @override_config({"user_directory": {"enabled": True, "search_all_users": True}})
  1769. def test_change_name_deactivate_user_user_directory(self) -> None:
  1770. """
  1771. Test change profile information of a deactivated user and
  1772. check that it does not appear in user directory
  1773. """
  1774. # is in user directory
  1775. profile = self.get_success(self.store.get_user_in_directory(self.other_user))
  1776. self.assertTrue(profile["display_name"] == "User")
  1777. # Deactivate user
  1778. channel = self.make_request(
  1779. "PUT",
  1780. self.url_other_user,
  1781. access_token=self.admin_user_tok,
  1782. content={"deactivated": True},
  1783. )
  1784. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1785. self.assertEqual("@user:test", channel.json_body["name"])
  1786. self.assertTrue(channel.json_body["deactivated"])
  1787. # is not in user directory
  1788. profile = self.get_success(self.store.get_user_in_directory(self.other_user))
  1789. self.assertIsNone(profile)
  1790. # Set new displayname user
  1791. channel = self.make_request(
  1792. "PUT",
  1793. self.url_other_user,
  1794. access_token=self.admin_user_tok,
  1795. content={"displayname": "Foobar"},
  1796. )
  1797. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1798. self.assertEqual("@user:test", channel.json_body["name"])
  1799. self.assertTrue(channel.json_body["deactivated"])
  1800. self.assertEqual("Foobar", channel.json_body["displayname"])
  1801. # is not in user directory
  1802. profile = self.get_success(self.store.get_user_in_directory(self.other_user))
  1803. self.assertIsNone(profile)
  1804. def test_reactivate_user(self) -> None:
  1805. """
  1806. Test reactivating another user.
  1807. """
  1808. # Deactivate the user.
  1809. self._deactivate_user("@user:test")
  1810. # Attempt to reactivate the user (without a password).
  1811. channel = self.make_request(
  1812. "PUT",
  1813. self.url_other_user,
  1814. access_token=self.admin_user_tok,
  1815. content={"deactivated": False},
  1816. )
  1817. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1818. # Reactivate the user.
  1819. channel = self.make_request(
  1820. "PUT",
  1821. self.url_other_user,
  1822. access_token=self.admin_user_tok,
  1823. content={"deactivated": False, "password": "foo"},
  1824. )
  1825. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1826. self.assertEqual("@user:test", channel.json_body["name"])
  1827. self.assertFalse(channel.json_body["deactivated"])
  1828. self._is_erased("@user:test", False)
  1829. # This key was removed intentionally. Ensure it is not accidentally re-included.
  1830. self.assertNotIn("password_hash", channel.json_body)
  1831. @override_config({"password_config": {"localdb_enabled": False}})
  1832. def test_reactivate_user_localdb_disabled(self) -> None:
  1833. """
  1834. Test reactivating another user when using SSO.
  1835. """
  1836. # Deactivate the user.
  1837. self._deactivate_user("@user:test")
  1838. # Reactivate the user with a password
  1839. channel = self.make_request(
  1840. "PUT",
  1841. self.url_other_user,
  1842. access_token=self.admin_user_tok,
  1843. content={"deactivated": False, "password": "foo"},
  1844. )
  1845. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  1846. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1847. # Reactivate the user without a password.
  1848. channel = self.make_request(
  1849. "PUT",
  1850. self.url_other_user,
  1851. access_token=self.admin_user_tok,
  1852. content={"deactivated": False},
  1853. )
  1854. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1855. self.assertEqual("@user:test", channel.json_body["name"])
  1856. self.assertFalse(channel.json_body["deactivated"])
  1857. self._is_erased("@user:test", False)
  1858. # This key was removed intentionally. Ensure it is not accidentally re-included.
  1859. self.assertNotIn("password_hash", channel.json_body)
  1860. @override_config({"password_config": {"enabled": False}})
  1861. def test_reactivate_user_password_disabled(self) -> None:
  1862. """
  1863. Test reactivating another user when using SSO.
  1864. """
  1865. # Deactivate the user.
  1866. self._deactivate_user("@user:test")
  1867. # Reactivate the user with a password
  1868. channel = self.make_request(
  1869. "PUT",
  1870. self.url_other_user,
  1871. access_token=self.admin_user_tok,
  1872. content={"deactivated": False, "password": "foo"},
  1873. )
  1874. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  1875. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1876. # Reactivate the user without a password.
  1877. channel = self.make_request(
  1878. "PUT",
  1879. self.url_other_user,
  1880. access_token=self.admin_user_tok,
  1881. content={"deactivated": False},
  1882. )
  1883. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1884. self.assertEqual("@user:test", channel.json_body["name"])
  1885. self.assertFalse(channel.json_body["deactivated"])
  1886. self._is_erased("@user:test", False)
  1887. # This key was removed intentionally. Ensure it is not accidentally re-included.
  1888. self.assertNotIn("password_hash", channel.json_body)
  1889. def test_set_user_as_admin(self) -> None:
  1890. """
  1891. Test setting the admin flag on a user.
  1892. """
  1893. # Set a user as an admin
  1894. channel = self.make_request(
  1895. "PUT",
  1896. self.url_other_user,
  1897. access_token=self.admin_user_tok,
  1898. content={"admin": True},
  1899. )
  1900. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1901. self.assertEqual("@user:test", channel.json_body["name"])
  1902. self.assertTrue(channel.json_body["admin"])
  1903. # Get user
  1904. channel = self.make_request(
  1905. "GET",
  1906. self.url_other_user,
  1907. access_token=self.admin_user_tok,
  1908. )
  1909. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1910. self.assertEqual("@user:test", channel.json_body["name"])
  1911. self.assertTrue(channel.json_body["admin"])
  1912. def test_set_user_type(self) -> None:
  1913. """
  1914. Test changing user type.
  1915. """
  1916. # Set to support type
  1917. channel = self.make_request(
  1918. "PUT",
  1919. self.url_other_user,
  1920. access_token=self.admin_user_tok,
  1921. content={"user_type": UserTypes.SUPPORT},
  1922. )
  1923. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1924. self.assertEqual("@user:test", channel.json_body["name"])
  1925. self.assertEqual(UserTypes.SUPPORT, channel.json_body["user_type"])
  1926. # Get user
  1927. channel = self.make_request(
  1928. "GET",
  1929. self.url_other_user,
  1930. access_token=self.admin_user_tok,
  1931. )
  1932. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1933. self.assertEqual("@user:test", channel.json_body["name"])
  1934. self.assertEqual(UserTypes.SUPPORT, channel.json_body["user_type"])
  1935. # Change back to a regular user
  1936. channel = self.make_request(
  1937. "PUT",
  1938. self.url_other_user,
  1939. access_token=self.admin_user_tok,
  1940. content={"user_type": None},
  1941. )
  1942. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1943. self.assertEqual("@user:test", channel.json_body["name"])
  1944. self.assertIsNone(channel.json_body["user_type"])
  1945. # Get user
  1946. channel = self.make_request(
  1947. "GET",
  1948. self.url_other_user,
  1949. access_token=self.admin_user_tok,
  1950. )
  1951. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1952. self.assertEqual("@user:test", channel.json_body["name"])
  1953. self.assertIsNone(channel.json_body["user_type"])
  1954. def test_accidental_deactivation_prevention(self) -> None:
  1955. """
  1956. Ensure an account can't accidentally be deactivated by using a str value
  1957. for the deactivated body parameter
  1958. """
  1959. url = self.url_prefix % "@bob:test"
  1960. # Create user
  1961. channel = self.make_request(
  1962. "PUT",
  1963. url,
  1964. access_token=self.admin_user_tok,
  1965. content={"password": "abc123"},
  1966. )
  1967. self.assertEqual(201, channel.code, msg=channel.json_body)
  1968. self.assertEqual("@bob:test", channel.json_body["name"])
  1969. self.assertEqual("bob", channel.json_body["displayname"])
  1970. # Get user
  1971. channel = self.make_request(
  1972. "GET",
  1973. url,
  1974. access_token=self.admin_user_tok,
  1975. )
  1976. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1977. self.assertEqual("@bob:test", channel.json_body["name"])
  1978. self.assertEqual("bob", channel.json_body["displayname"])
  1979. self.assertEqual(0, channel.json_body["deactivated"])
  1980. # Change password (and use a str for deactivate instead of a bool)
  1981. channel = self.make_request(
  1982. "PUT",
  1983. url,
  1984. access_token=self.admin_user_tok,
  1985. content={"password": "abc123", "deactivated": "false"},
  1986. )
  1987. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  1988. # Check user is not deactivated
  1989. channel = self.make_request(
  1990. "GET",
  1991. url,
  1992. access_token=self.admin_user_tok,
  1993. )
  1994. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  1995. self.assertEqual("@bob:test", channel.json_body["name"])
  1996. self.assertEqual("bob", channel.json_body["displayname"])
  1997. # Ensure they're still alive
  1998. self.assertEqual(0, channel.json_body["deactivated"])
  1999. def _is_erased(self, user_id: str, expect: bool) -> None:
  2000. """Assert that the user is erased or not"""
  2001. d = self.store.is_user_erased(user_id)
  2002. if expect:
  2003. self.assertTrue(self.get_success(d))
  2004. else:
  2005. self.assertFalse(self.get_success(d))
  2006. def _deactivate_user(self, user_id: str) -> None:
  2007. """Deactivate user and set as erased"""
  2008. # Deactivate the user.
  2009. channel = self.make_request(
  2010. "PUT",
  2011. self.url_prefix % urllib.parse.quote(user_id),
  2012. access_token=self.admin_user_tok,
  2013. content={"deactivated": True},
  2014. )
  2015. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2016. self.assertTrue(channel.json_body["deactivated"])
  2017. self._is_erased(user_id, False)
  2018. d = self.store.mark_user_erased(user_id)
  2019. self.assertIsNone(self.get_success(d))
  2020. self._is_erased(user_id, True)
  2021. # This key was removed intentionally. Ensure it is not accidentally re-included.
  2022. self.assertNotIn("password_hash", channel.json_body)
  2023. def _check_fields(self, content: JsonDict) -> None:
  2024. """Checks that the expected user attributes are present in content
  2025. Args:
  2026. content: Content dictionary to check
  2027. """
  2028. self.assertIn("displayname", content)
  2029. self.assertIn("threepids", content)
  2030. self.assertIn("avatar_url", content)
  2031. self.assertIn("admin", content)
  2032. self.assertIn("deactivated", content)
  2033. self.assertIn("shadow_banned", content)
  2034. self.assertIn("creation_ts", content)
  2035. self.assertIn("appservice_id", content)
  2036. self.assertIn("consent_server_notice_sent", content)
  2037. self.assertIn("consent_version", content)
  2038. self.assertIn("external_ids", content)
  2039. # This key was removed intentionally. Ensure it is not accidentally re-included.
  2040. self.assertNotIn("password_hash", content)
  2041. class UserMembershipRestTestCase(unittest.HomeserverTestCase):
  2042. servlets = [
  2043. synapse.rest.admin.register_servlets,
  2044. login.register_servlets,
  2045. room.register_servlets,
  2046. ]
  2047. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2048. self.admin_user = self.register_user("admin", "pass", admin=True)
  2049. self.admin_user_tok = self.login("admin", "pass")
  2050. self.other_user = self.register_user("user", "pass")
  2051. self.url = "/_synapse/admin/v1/users/%s/joined_rooms" % urllib.parse.quote(
  2052. self.other_user
  2053. )
  2054. def test_no_auth(self) -> None:
  2055. """
  2056. Try to list rooms of an user without authentication.
  2057. """
  2058. channel = self.make_request("GET", self.url, b"{}")
  2059. self.assertEqual(HTTPStatus.UNAUTHORIZED, channel.code, msg=channel.json_body)
  2060. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2061. def test_requester_is_no_admin(self) -> None:
  2062. """
  2063. If the user is not a server admin, an error is returned.
  2064. """
  2065. other_user_token = self.login("user", "pass")
  2066. channel = self.make_request(
  2067. "GET",
  2068. self.url,
  2069. access_token=other_user_token,
  2070. )
  2071. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  2072. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2073. def test_user_does_not_exist(self) -> None:
  2074. """
  2075. Tests that a lookup for a user that does not exist returns an empty list
  2076. """
  2077. url = "/_synapse/admin/v1/users/@unknown_person:test/joined_rooms"
  2078. channel = self.make_request(
  2079. "GET",
  2080. url,
  2081. access_token=self.admin_user_tok,
  2082. )
  2083. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2084. self.assertEqual(0, channel.json_body["total"])
  2085. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  2086. def test_user_is_not_local(self) -> None:
  2087. """
  2088. Tests that a lookup for a user that is not a local and participates in no conversation returns an empty list
  2089. """
  2090. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/joined_rooms"
  2091. channel = self.make_request(
  2092. "GET",
  2093. url,
  2094. access_token=self.admin_user_tok,
  2095. )
  2096. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2097. self.assertEqual(0, channel.json_body["total"])
  2098. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  2099. def test_no_memberships(self) -> None:
  2100. """
  2101. Tests that a normal lookup for rooms is successfully
  2102. if user has no memberships
  2103. """
  2104. # Get rooms
  2105. channel = self.make_request(
  2106. "GET",
  2107. self.url,
  2108. access_token=self.admin_user_tok,
  2109. )
  2110. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2111. self.assertEqual(0, channel.json_body["total"])
  2112. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  2113. def test_get_rooms(self) -> None:
  2114. """
  2115. Tests that a normal lookup for rooms is successfully
  2116. """
  2117. # Create rooms and join
  2118. other_user_tok = self.login("user", "pass")
  2119. number_rooms = 5
  2120. for _ in range(number_rooms):
  2121. self.helper.create_room_as(self.other_user, tok=other_user_tok)
  2122. # Get rooms
  2123. channel = self.make_request(
  2124. "GET",
  2125. self.url,
  2126. access_token=self.admin_user_tok,
  2127. )
  2128. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2129. self.assertEqual(number_rooms, channel.json_body["total"])
  2130. self.assertEqual(number_rooms, len(channel.json_body["joined_rooms"]))
  2131. def test_get_rooms_with_nonlocal_user(self) -> None:
  2132. """
  2133. Tests that a normal lookup for rooms is successful with a non-local user
  2134. """
  2135. other_user_tok = self.login("user", "pass")
  2136. event_builder_factory = self.hs.get_event_builder_factory()
  2137. event_creation_handler = self.hs.get_event_creation_handler()
  2138. storage = self.hs.get_storage()
  2139. # Create two rooms, one with a local user only and one with both a local
  2140. # and remote user.
  2141. self.helper.create_room_as(self.other_user, tok=other_user_tok)
  2142. local_and_remote_room_id = self.helper.create_room_as(
  2143. self.other_user, tok=other_user_tok
  2144. )
  2145. # Add a remote user to the room.
  2146. builder = event_builder_factory.for_room_version(
  2147. RoomVersions.V1,
  2148. {
  2149. "type": "m.room.member",
  2150. "sender": "@joiner:remote_hs",
  2151. "state_key": "@joiner:remote_hs",
  2152. "room_id": local_and_remote_room_id,
  2153. "content": {"membership": "join"},
  2154. },
  2155. )
  2156. event, context = self.get_success(
  2157. event_creation_handler.create_new_client_event(builder)
  2158. )
  2159. self.get_success(storage.persistence.persist_event(event, context))
  2160. # Now get rooms
  2161. url = "/_synapse/admin/v1/users/@joiner:remote_hs/joined_rooms"
  2162. channel = self.make_request(
  2163. "GET",
  2164. url,
  2165. access_token=self.admin_user_tok,
  2166. )
  2167. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2168. self.assertEqual(1, channel.json_body["total"])
  2169. self.assertEqual([local_and_remote_room_id], channel.json_body["joined_rooms"])
  2170. class PushersRestTestCase(unittest.HomeserverTestCase):
  2171. servlets = [
  2172. synapse.rest.admin.register_servlets,
  2173. login.register_servlets,
  2174. ]
  2175. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2176. self.store = hs.get_datastores().main
  2177. self.admin_user = self.register_user("admin", "pass", admin=True)
  2178. self.admin_user_tok = self.login("admin", "pass")
  2179. self.other_user = self.register_user("user", "pass")
  2180. self.url = "/_synapse/admin/v1/users/%s/pushers" % urllib.parse.quote(
  2181. self.other_user
  2182. )
  2183. def test_no_auth(self) -> None:
  2184. """
  2185. Try to list pushers of an user without authentication.
  2186. """
  2187. channel = self.make_request("GET", self.url, b"{}")
  2188. self.assertEqual(HTTPStatus.UNAUTHORIZED, channel.code, msg=channel.json_body)
  2189. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2190. def test_requester_is_no_admin(self) -> None:
  2191. """
  2192. If the user is not a server admin, an error is returned.
  2193. """
  2194. other_user_token = self.login("user", "pass")
  2195. channel = self.make_request(
  2196. "GET",
  2197. self.url,
  2198. access_token=other_user_token,
  2199. )
  2200. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  2201. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2202. def test_user_does_not_exist(self) -> None:
  2203. """
  2204. Tests that a lookup for a user that does not exist returns a HTTPStatus.NOT_FOUND
  2205. """
  2206. url = "/_synapse/admin/v1/users/@unknown_person:test/pushers"
  2207. channel = self.make_request(
  2208. "GET",
  2209. url,
  2210. access_token=self.admin_user_tok,
  2211. )
  2212. self.assertEqual(HTTPStatus.NOT_FOUND, channel.code, msg=channel.json_body)
  2213. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  2214. def test_user_is_not_local(self) -> None:
  2215. """
  2216. Tests that a lookup for a user that is not a local returns a HTTPStatus.BAD_REQUEST
  2217. """
  2218. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/pushers"
  2219. channel = self.make_request(
  2220. "GET",
  2221. url,
  2222. access_token=self.admin_user_tok,
  2223. )
  2224. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  2225. self.assertEqual("Can only look up local users", channel.json_body["error"])
  2226. def test_get_pushers(self) -> None:
  2227. """
  2228. Tests that a normal lookup for pushers is successfully
  2229. """
  2230. # Get pushers
  2231. channel = self.make_request(
  2232. "GET",
  2233. self.url,
  2234. access_token=self.admin_user_tok,
  2235. )
  2236. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2237. self.assertEqual(0, channel.json_body["total"])
  2238. # Register the pusher
  2239. other_user_token = self.login("user", "pass")
  2240. user_tuple = self.get_success(
  2241. self.store.get_user_by_access_token(other_user_token)
  2242. )
  2243. token_id = user_tuple.token_id
  2244. self.get_success(
  2245. self.hs.get_pusherpool().add_pusher(
  2246. user_id=self.other_user,
  2247. access_token=token_id,
  2248. kind="http",
  2249. app_id="m.http",
  2250. app_display_name="HTTP Push Notifications",
  2251. device_display_name="pushy push",
  2252. pushkey="a@example.com",
  2253. lang=None,
  2254. data={"url": "https://example.com/_matrix/push/v1/notify"},
  2255. )
  2256. )
  2257. # Get pushers
  2258. channel = self.make_request(
  2259. "GET",
  2260. self.url,
  2261. access_token=self.admin_user_tok,
  2262. )
  2263. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2264. self.assertEqual(1, channel.json_body["total"])
  2265. for p in channel.json_body["pushers"]:
  2266. self.assertIn("pushkey", p)
  2267. self.assertIn("kind", p)
  2268. self.assertIn("app_id", p)
  2269. self.assertIn("app_display_name", p)
  2270. self.assertIn("device_display_name", p)
  2271. self.assertIn("profile_tag", p)
  2272. self.assertIn("lang", p)
  2273. self.assertIn("url", p["data"])
  2274. class UserMediaRestTestCase(unittest.HomeserverTestCase):
  2275. servlets = [
  2276. synapse.rest.admin.register_servlets,
  2277. login.register_servlets,
  2278. ]
  2279. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2280. self.store = hs.get_datastores().main
  2281. self.media_repo = hs.get_media_repository_resource()
  2282. self.filepaths = MediaFilePaths(hs.config.media.media_store_path)
  2283. self.admin_user = self.register_user("admin", "pass", admin=True)
  2284. self.admin_user_tok = self.login("admin", "pass")
  2285. self.other_user = self.register_user("user", "pass")
  2286. self.url = "/_synapse/admin/v1/users/%s/media" % urllib.parse.quote(
  2287. self.other_user
  2288. )
  2289. @parameterized.expand(["GET", "DELETE"])
  2290. def test_no_auth(self, method: str) -> None:
  2291. """Try to list media of an user without authentication."""
  2292. channel = self.make_request(method, self.url, {})
  2293. self.assertEqual(HTTPStatus.UNAUTHORIZED, channel.code, msg=channel.json_body)
  2294. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2295. @parameterized.expand(["GET", "DELETE"])
  2296. def test_requester_is_no_admin(self, method: str) -> None:
  2297. """If the user is not a server admin, an error is returned."""
  2298. other_user_token = self.login("user", "pass")
  2299. channel = self.make_request(
  2300. method,
  2301. self.url,
  2302. access_token=other_user_token,
  2303. )
  2304. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  2305. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2306. @parameterized.expand(["GET", "DELETE"])
  2307. def test_user_does_not_exist(self, method: str) -> None:
  2308. """Tests that a lookup for a user that does not exist returns a HTTPStatus.NOT_FOUND"""
  2309. url = "/_synapse/admin/v1/users/@unknown_person:test/media"
  2310. channel = self.make_request(
  2311. method,
  2312. url,
  2313. access_token=self.admin_user_tok,
  2314. )
  2315. self.assertEqual(HTTPStatus.NOT_FOUND, channel.code, msg=channel.json_body)
  2316. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  2317. @parameterized.expand(["GET", "DELETE"])
  2318. def test_user_is_not_local(self, method: str) -> None:
  2319. """Tests that a lookup for a user that is not a local returns a HTTPStatus.BAD_REQUEST"""
  2320. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/media"
  2321. channel = self.make_request(
  2322. method,
  2323. url,
  2324. access_token=self.admin_user_tok,
  2325. )
  2326. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  2327. self.assertEqual("Can only look up local users", channel.json_body["error"])
  2328. def test_limit_GET(self) -> None:
  2329. """Testing list of media with limit"""
  2330. number_media = 20
  2331. other_user_tok = self.login("user", "pass")
  2332. self._create_media_for_user(other_user_tok, number_media)
  2333. channel = self.make_request(
  2334. "GET",
  2335. self.url + "?limit=5",
  2336. access_token=self.admin_user_tok,
  2337. )
  2338. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2339. self.assertEqual(channel.json_body["total"], number_media)
  2340. self.assertEqual(len(channel.json_body["media"]), 5)
  2341. self.assertEqual(channel.json_body["next_token"], 5)
  2342. self._check_fields(channel.json_body["media"])
  2343. def test_limit_DELETE(self) -> None:
  2344. """Testing delete of media with limit"""
  2345. number_media = 20
  2346. other_user_tok = self.login("user", "pass")
  2347. self._create_media_for_user(other_user_tok, number_media)
  2348. channel = self.make_request(
  2349. "DELETE",
  2350. self.url + "?limit=5",
  2351. access_token=self.admin_user_tok,
  2352. )
  2353. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2354. self.assertEqual(channel.json_body["total"], 5)
  2355. self.assertEqual(len(channel.json_body["deleted_media"]), 5)
  2356. def test_from_GET(self) -> None:
  2357. """Testing list of media with a defined starting point (from)"""
  2358. number_media = 20
  2359. other_user_tok = self.login("user", "pass")
  2360. self._create_media_for_user(other_user_tok, number_media)
  2361. channel = self.make_request(
  2362. "GET",
  2363. self.url + "?from=5",
  2364. access_token=self.admin_user_tok,
  2365. )
  2366. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2367. self.assertEqual(channel.json_body["total"], number_media)
  2368. self.assertEqual(len(channel.json_body["media"]), 15)
  2369. self.assertNotIn("next_token", channel.json_body)
  2370. self._check_fields(channel.json_body["media"])
  2371. def test_from_DELETE(self) -> None:
  2372. """Testing delete of media with a defined starting point (from)"""
  2373. number_media = 20
  2374. other_user_tok = self.login("user", "pass")
  2375. self._create_media_for_user(other_user_tok, number_media)
  2376. channel = self.make_request(
  2377. "DELETE",
  2378. self.url + "?from=5",
  2379. access_token=self.admin_user_tok,
  2380. )
  2381. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2382. self.assertEqual(channel.json_body["total"], 15)
  2383. self.assertEqual(len(channel.json_body["deleted_media"]), 15)
  2384. def test_limit_and_from_GET(self) -> None:
  2385. """Testing list of media with a defined starting point and limit"""
  2386. number_media = 20
  2387. other_user_tok = self.login("user", "pass")
  2388. self._create_media_for_user(other_user_tok, number_media)
  2389. channel = self.make_request(
  2390. "GET",
  2391. self.url + "?from=5&limit=10",
  2392. access_token=self.admin_user_tok,
  2393. )
  2394. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2395. self.assertEqual(channel.json_body["total"], number_media)
  2396. self.assertEqual(channel.json_body["next_token"], 15)
  2397. self.assertEqual(len(channel.json_body["media"]), 10)
  2398. self._check_fields(channel.json_body["media"])
  2399. def test_limit_and_from_DELETE(self) -> None:
  2400. """Testing delete of media with a defined starting point and limit"""
  2401. number_media = 20
  2402. other_user_tok = self.login("user", "pass")
  2403. self._create_media_for_user(other_user_tok, number_media)
  2404. channel = self.make_request(
  2405. "DELETE",
  2406. self.url + "?from=5&limit=10",
  2407. access_token=self.admin_user_tok,
  2408. )
  2409. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2410. self.assertEqual(channel.json_body["total"], 10)
  2411. self.assertEqual(len(channel.json_body["deleted_media"]), 10)
  2412. @parameterized.expand(["GET", "DELETE"])
  2413. def test_invalid_parameter(self, method: str) -> None:
  2414. """If parameters are invalid, an error is returned."""
  2415. # unkown order_by
  2416. channel = self.make_request(
  2417. method,
  2418. self.url + "?order_by=bar",
  2419. access_token=self.admin_user_tok,
  2420. )
  2421. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  2422. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2423. # invalid search order
  2424. channel = self.make_request(
  2425. method,
  2426. self.url + "?dir=bar",
  2427. access_token=self.admin_user_tok,
  2428. )
  2429. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  2430. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2431. # negative limit
  2432. channel = self.make_request(
  2433. method,
  2434. self.url + "?limit=-5",
  2435. access_token=self.admin_user_tok,
  2436. )
  2437. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  2438. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2439. # negative from
  2440. channel = self.make_request(
  2441. method,
  2442. self.url + "?from=-5",
  2443. access_token=self.admin_user_tok,
  2444. )
  2445. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  2446. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2447. def test_next_token(self) -> None:
  2448. """
  2449. Testing that `next_token` appears at the right place
  2450. For deleting media `next_token` is not useful, because
  2451. after deleting media the media has a new order.
  2452. """
  2453. number_media = 20
  2454. other_user_tok = self.login("user", "pass")
  2455. self._create_media_for_user(other_user_tok, number_media)
  2456. # `next_token` does not appear
  2457. # Number of results is the number of entries
  2458. channel = self.make_request(
  2459. "GET",
  2460. self.url + "?limit=20",
  2461. access_token=self.admin_user_tok,
  2462. )
  2463. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2464. self.assertEqual(channel.json_body["total"], number_media)
  2465. self.assertEqual(len(channel.json_body["media"]), number_media)
  2466. self.assertNotIn("next_token", channel.json_body)
  2467. # `next_token` does not appear
  2468. # Number of max results is larger than the number of entries
  2469. channel = self.make_request(
  2470. "GET",
  2471. self.url + "?limit=21",
  2472. access_token=self.admin_user_tok,
  2473. )
  2474. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2475. self.assertEqual(channel.json_body["total"], number_media)
  2476. self.assertEqual(len(channel.json_body["media"]), number_media)
  2477. self.assertNotIn("next_token", channel.json_body)
  2478. # `next_token` does appear
  2479. # Number of max results is smaller than the number of entries
  2480. channel = self.make_request(
  2481. "GET",
  2482. self.url + "?limit=19",
  2483. access_token=self.admin_user_tok,
  2484. )
  2485. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2486. self.assertEqual(channel.json_body["total"], number_media)
  2487. self.assertEqual(len(channel.json_body["media"]), 19)
  2488. self.assertEqual(channel.json_body["next_token"], 19)
  2489. # Check
  2490. # Set `from` to value of `next_token` for request remaining entries
  2491. # `next_token` does not appear
  2492. channel = self.make_request(
  2493. "GET",
  2494. self.url + "?from=19",
  2495. access_token=self.admin_user_tok,
  2496. )
  2497. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2498. self.assertEqual(channel.json_body["total"], number_media)
  2499. self.assertEqual(len(channel.json_body["media"]), 1)
  2500. self.assertNotIn("next_token", channel.json_body)
  2501. def test_user_has_no_media_GET(self) -> None:
  2502. """
  2503. Tests that a normal lookup for media is successfully
  2504. if user has no media created
  2505. """
  2506. channel = self.make_request(
  2507. "GET",
  2508. self.url,
  2509. access_token=self.admin_user_tok,
  2510. )
  2511. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2512. self.assertEqual(0, channel.json_body["total"])
  2513. self.assertEqual(0, len(channel.json_body["media"]))
  2514. def test_user_has_no_media_DELETE(self) -> None:
  2515. """
  2516. Tests that a delete is successful if user has no media
  2517. """
  2518. channel = self.make_request(
  2519. "DELETE",
  2520. self.url,
  2521. access_token=self.admin_user_tok,
  2522. )
  2523. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2524. self.assertEqual(0, channel.json_body["total"])
  2525. self.assertEqual(0, len(channel.json_body["deleted_media"]))
  2526. def test_get_media(self) -> None:
  2527. """Tests that a normal lookup for media is successful"""
  2528. number_media = 5
  2529. other_user_tok = self.login("user", "pass")
  2530. self._create_media_for_user(other_user_tok, number_media)
  2531. channel = self.make_request(
  2532. "GET",
  2533. self.url,
  2534. access_token=self.admin_user_tok,
  2535. )
  2536. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2537. self.assertEqual(number_media, channel.json_body["total"])
  2538. self.assertEqual(number_media, len(channel.json_body["media"]))
  2539. self.assertNotIn("next_token", channel.json_body)
  2540. self._check_fields(channel.json_body["media"])
  2541. def test_delete_media(self) -> None:
  2542. """Tests that a normal delete of media is successful"""
  2543. number_media = 5
  2544. other_user_tok = self.login("user", "pass")
  2545. media_ids = self._create_media_for_user(other_user_tok, number_media)
  2546. # Test if the file exists
  2547. local_paths = []
  2548. for media_id in media_ids:
  2549. local_path = self.filepaths.local_media_filepath(media_id)
  2550. self.assertTrue(os.path.exists(local_path))
  2551. local_paths.append(local_path)
  2552. channel = self.make_request(
  2553. "DELETE",
  2554. self.url,
  2555. access_token=self.admin_user_tok,
  2556. )
  2557. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2558. self.assertEqual(number_media, channel.json_body["total"])
  2559. self.assertEqual(number_media, len(channel.json_body["deleted_media"]))
  2560. self.assertCountEqual(channel.json_body["deleted_media"], media_ids)
  2561. # Test if the file is deleted
  2562. for local_path in local_paths:
  2563. self.assertFalse(os.path.exists(local_path))
  2564. def test_order_by(self) -> None:
  2565. """
  2566. Testing order list with parameter `order_by`
  2567. """
  2568. other_user_tok = self.login("user", "pass")
  2569. # Resolution: 1×1, MIME type: image/png, Extension: png, Size: 67 B
  2570. image_data1 = SMALL_PNG
  2571. # Resolution: 1×1, MIME type: image/gif, Extension: gif, Size: 35 B
  2572. image_data2 = unhexlify(
  2573. b"47494638376101000100800100000000"
  2574. b"ffffff2c00000000010001000002024c"
  2575. b"01003b"
  2576. )
  2577. # Resolution: 1×1, MIME type: image/bmp, Extension: bmp, Size: 54 B
  2578. image_data3 = unhexlify(
  2579. b"424d3a0000000000000036000000280000000100000001000000"
  2580. b"0100180000000000040000000000000000000000000000000000"
  2581. b"0000"
  2582. )
  2583. # create media and make sure they do not have the same timestamp
  2584. media1 = self._create_media_and_access(other_user_tok, image_data1, "image.png")
  2585. self.pump(1.0)
  2586. media2 = self._create_media_and_access(other_user_tok, image_data2, "image.gif")
  2587. self.pump(1.0)
  2588. media3 = self._create_media_and_access(other_user_tok, image_data3, "image.bmp")
  2589. self.pump(1.0)
  2590. # Mark one media as safe from quarantine.
  2591. self.get_success(self.store.mark_local_media_as_safe(media2))
  2592. # Quarantine one media
  2593. self.get_success(
  2594. self.store.quarantine_media_by_id("test", media3, self.admin_user)
  2595. )
  2596. # order by default ("created_ts")
  2597. # default is backwards
  2598. self._order_test([media3, media2, media1], None)
  2599. self._order_test([media1, media2, media3], None, "f")
  2600. self._order_test([media3, media2, media1], None, "b")
  2601. # sort by media_id
  2602. sorted_media = sorted([media1, media2, media3], reverse=False)
  2603. sorted_media_reverse = sorted(sorted_media, reverse=True)
  2604. # order by media_id
  2605. self._order_test(sorted_media, "media_id")
  2606. self._order_test(sorted_media, "media_id", "f")
  2607. self._order_test(sorted_media_reverse, "media_id", "b")
  2608. # order by upload_name
  2609. self._order_test([media3, media2, media1], "upload_name")
  2610. self._order_test([media3, media2, media1], "upload_name", "f")
  2611. self._order_test([media1, media2, media3], "upload_name", "b")
  2612. # order by media_type
  2613. # result is ordered by media_id
  2614. # because of uploaded media_type is always 'application/json'
  2615. self._order_test(sorted_media, "media_type")
  2616. self._order_test(sorted_media, "media_type", "f")
  2617. self._order_test(sorted_media, "media_type", "b")
  2618. # order by media_length
  2619. self._order_test([media2, media3, media1], "media_length")
  2620. self._order_test([media2, media3, media1], "media_length", "f")
  2621. self._order_test([media1, media3, media2], "media_length", "b")
  2622. # order by created_ts
  2623. self._order_test([media1, media2, media3], "created_ts")
  2624. self._order_test([media1, media2, media3], "created_ts", "f")
  2625. self._order_test([media3, media2, media1], "created_ts", "b")
  2626. # order by last_access_ts
  2627. self._order_test([media1, media2, media3], "last_access_ts")
  2628. self._order_test([media1, media2, media3], "last_access_ts", "f")
  2629. self._order_test([media3, media2, media1], "last_access_ts", "b")
  2630. # order by quarantined_by
  2631. # one media is in quarantine, others are ordered by media_ids
  2632. # Different sort order of SQlite and PostreSQL
  2633. # If a media is not in quarantine `quarantined_by` is NULL
  2634. # SQLite considers NULL to be smaller than any other value.
  2635. # PostreSQL considers NULL to be larger than any other value.
  2636. # self._order_test(sorted([media1, media2]) + [media3], "quarantined_by")
  2637. # self._order_test(sorted([media1, media2]) + [media3], "quarantined_by", "f")
  2638. # self._order_test([media3] + sorted([media1, media2]), "quarantined_by", "b")
  2639. # order by safe_from_quarantine
  2640. # one media is safe from quarantine, others are ordered by media_ids
  2641. self._order_test(sorted([media1, media3]) + [media2], "safe_from_quarantine")
  2642. self._order_test(
  2643. sorted([media1, media3]) + [media2], "safe_from_quarantine", "f"
  2644. )
  2645. self._order_test(
  2646. [media2] + sorted([media1, media3]), "safe_from_quarantine", "b"
  2647. )
  2648. def _create_media_for_user(self, user_token: str, number_media: int) -> List[str]:
  2649. """
  2650. Create a number of media for a specific user
  2651. Args:
  2652. user_token: Access token of the user
  2653. number_media: Number of media to be created for the user
  2654. Returns:
  2655. List of created media ID
  2656. """
  2657. media_ids = []
  2658. for _ in range(number_media):
  2659. media_ids.append(self._create_media_and_access(user_token, SMALL_PNG))
  2660. return media_ids
  2661. def _create_media_and_access(
  2662. self,
  2663. user_token: str,
  2664. image_data: bytes,
  2665. filename: str = "image1.png",
  2666. ) -> str:
  2667. """
  2668. Create one media for a specific user, access and returns `media_id`
  2669. Args:
  2670. user_token: Access token of the user
  2671. image_data: binary data of image
  2672. filename: The filename of the media to be uploaded
  2673. Returns:
  2674. The ID of the newly created media.
  2675. """
  2676. upload_resource = self.media_repo.children[b"upload"]
  2677. download_resource = self.media_repo.children[b"download"]
  2678. # Upload some media into the room
  2679. response = self.helper.upload_media(
  2680. upload_resource, image_data, user_token, filename, expect_code=HTTPStatus.OK
  2681. )
  2682. # Extract media ID from the response
  2683. server_and_media_id = response["content_uri"][6:] # Cut off 'mxc://'
  2684. media_id = server_and_media_id.split("/")[1]
  2685. # Try to access a media and to create `last_access_ts`
  2686. channel = make_request(
  2687. self.reactor,
  2688. FakeSite(download_resource, self.reactor),
  2689. "GET",
  2690. server_and_media_id,
  2691. shorthand=False,
  2692. access_token=user_token,
  2693. )
  2694. self.assertEqual(
  2695. HTTPStatus.OK,
  2696. channel.code,
  2697. msg=(
  2698. f"Expected to receive a HTTPStatus.OK on accessing media: {server_and_media_id}"
  2699. ),
  2700. )
  2701. return media_id
  2702. def _check_fields(self, content: List[JsonDict]) -> None:
  2703. """Checks that the expected user attributes are present in content
  2704. Args:
  2705. content: List that is checked for content
  2706. """
  2707. for m in content:
  2708. self.assertIn("media_id", m)
  2709. self.assertIn("media_type", m)
  2710. self.assertIn("media_length", m)
  2711. self.assertIn("upload_name", m)
  2712. self.assertIn("created_ts", m)
  2713. self.assertIn("last_access_ts", m)
  2714. self.assertIn("quarantined_by", m)
  2715. self.assertIn("safe_from_quarantine", m)
  2716. def _order_test(
  2717. self,
  2718. expected_media_list: List[str],
  2719. order_by: Optional[str],
  2720. dir: Optional[str] = None,
  2721. ) -> None:
  2722. """Request the list of media in a certain order. Assert that order is what
  2723. we expect
  2724. Args:
  2725. expected_media_list: The list of media_ids in the order we expect to get
  2726. back from the server
  2727. order_by: The type of ordering to give the server
  2728. dir: The direction of ordering to give the server
  2729. """
  2730. url = self.url + "?"
  2731. if order_by is not None:
  2732. url += f"order_by={order_by}&"
  2733. if dir is not None and dir in ("b", "f"):
  2734. url += f"dir={dir}"
  2735. channel = self.make_request(
  2736. "GET",
  2737. url,
  2738. access_token=self.admin_user_tok,
  2739. )
  2740. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2741. self.assertEqual(channel.json_body["total"], len(expected_media_list))
  2742. returned_order = [row["media_id"] for row in channel.json_body["media"]]
  2743. self.assertEqual(expected_media_list, returned_order)
  2744. self._check_fields(channel.json_body["media"])
  2745. class UserTokenRestTestCase(unittest.HomeserverTestCase):
  2746. """Test for /_synapse/admin/v1/users/<user>/login"""
  2747. servlets = [
  2748. synapse.rest.admin.register_servlets,
  2749. login.register_servlets,
  2750. sync.register_servlets,
  2751. room.register_servlets,
  2752. devices.register_servlets,
  2753. logout.register_servlets,
  2754. ]
  2755. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2756. self.store = hs.get_datastores().main
  2757. self.admin_user = self.register_user("admin", "pass", admin=True)
  2758. self.admin_user_tok = self.login("admin", "pass")
  2759. self.other_user = self.register_user("user", "pass")
  2760. self.other_user_tok = self.login("user", "pass")
  2761. self.url = "/_synapse/admin/v1/users/%s/login" % urllib.parse.quote(
  2762. self.other_user
  2763. )
  2764. def _get_token(self) -> str:
  2765. channel = self.make_request(
  2766. "POST", self.url, b"{}", access_token=self.admin_user_tok
  2767. )
  2768. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2769. return channel.json_body["access_token"]
  2770. def test_no_auth(self) -> None:
  2771. """Try to login as a user without authentication."""
  2772. channel = self.make_request("POST", self.url, b"{}")
  2773. self.assertEqual(HTTPStatus.UNAUTHORIZED, channel.code, msg=channel.json_body)
  2774. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2775. def test_not_admin(self) -> None:
  2776. """Try to login as a user as a non-admin user."""
  2777. channel = self.make_request(
  2778. "POST", self.url, b"{}", access_token=self.other_user_tok
  2779. )
  2780. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  2781. def test_send_event(self) -> None:
  2782. """Test that sending event as a user works."""
  2783. # Create a room.
  2784. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  2785. # Login in as the user
  2786. puppet_token = self._get_token()
  2787. # Test that sending works, and generates the event as the right user.
  2788. resp = self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  2789. event_id = resp["event_id"]
  2790. event = self.get_success(self.store.get_event(event_id))
  2791. self.assertEqual(event.sender, self.other_user)
  2792. def test_devices(self) -> None:
  2793. """Tests that logging in as a user doesn't create a new device for them."""
  2794. # Login in as the user
  2795. self._get_token()
  2796. # Check that we don't see a new device in our devices list
  2797. channel = self.make_request(
  2798. "GET", "devices", b"{}", access_token=self.other_user_tok
  2799. )
  2800. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2801. # We should only see the one device (from the login in `prepare`)
  2802. self.assertEqual(len(channel.json_body["devices"]), 1)
  2803. def test_logout(self) -> None:
  2804. """Test that calling `/logout` with the token works."""
  2805. # Login in as the user
  2806. puppet_token = self._get_token()
  2807. # Test that we can successfully make a request
  2808. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2809. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2810. # Logout with the puppet token
  2811. channel = self.make_request("POST", "logout", b"{}", access_token=puppet_token)
  2812. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2813. # The puppet token should no longer work
  2814. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2815. self.assertEqual(HTTPStatus.UNAUTHORIZED, channel.code, msg=channel.json_body)
  2816. # .. but the real user's tokens should still work
  2817. channel = self.make_request(
  2818. "GET", "devices", b"{}", access_token=self.other_user_tok
  2819. )
  2820. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2821. def test_user_logout_all(self) -> None:
  2822. """Tests that the target user calling `/logout/all` does *not* expire
  2823. the token.
  2824. """
  2825. # Login in as the user
  2826. puppet_token = self._get_token()
  2827. # Test that we can successfully make a request
  2828. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2829. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2830. # Logout all with the real user token
  2831. channel = self.make_request(
  2832. "POST", "logout/all", b"{}", access_token=self.other_user_tok
  2833. )
  2834. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2835. # The puppet token should still work
  2836. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2837. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2838. # .. but the real user's tokens shouldn't
  2839. channel = self.make_request(
  2840. "GET", "devices", b"{}", access_token=self.other_user_tok
  2841. )
  2842. self.assertEqual(HTTPStatus.UNAUTHORIZED, channel.code, msg=channel.json_body)
  2843. def test_admin_logout_all(self) -> None:
  2844. """Tests that the admin user calling `/logout/all` does expire the
  2845. token.
  2846. """
  2847. # Login in as the user
  2848. puppet_token = self._get_token()
  2849. # Test that we can successfully make a request
  2850. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2851. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2852. # Logout all with the admin user token
  2853. channel = self.make_request(
  2854. "POST", "logout/all", b"{}", access_token=self.admin_user_tok
  2855. )
  2856. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2857. # The puppet token should no longer work
  2858. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2859. self.assertEqual(HTTPStatus.UNAUTHORIZED, channel.code, msg=channel.json_body)
  2860. # .. but the real user's tokens should still work
  2861. channel = self.make_request(
  2862. "GET", "devices", b"{}", access_token=self.other_user_tok
  2863. )
  2864. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2865. @unittest.override_config(
  2866. {
  2867. "public_baseurl": "https://example.org/",
  2868. "user_consent": {
  2869. "version": "1.0",
  2870. "policy_name": "My Cool Privacy Policy",
  2871. "template_dir": "/",
  2872. "require_at_registration": True,
  2873. "block_events_error": "You should accept the policy",
  2874. },
  2875. "form_secret": "123secret",
  2876. }
  2877. )
  2878. def test_consent(self) -> None:
  2879. """Test that sending a message is not subject to the privacy policies."""
  2880. # Have the admin user accept the terms.
  2881. self.get_success(self.store.user_set_consent_version(self.admin_user, "1.0"))
  2882. # First, cheekily accept the terms and create a room
  2883. self.get_success(self.store.user_set_consent_version(self.other_user, "1.0"))
  2884. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  2885. self.helper.send_event(room_id, "com.example.test", tok=self.other_user_tok)
  2886. # Now unaccept it and check that we can't send an event
  2887. self.get_success(self.store.user_set_consent_version(self.other_user, "0.0"))
  2888. self.helper.send_event(
  2889. room_id,
  2890. "com.example.test",
  2891. tok=self.other_user_tok,
  2892. expect_code=HTTPStatus.FORBIDDEN,
  2893. )
  2894. # Login in as the user
  2895. puppet_token = self._get_token()
  2896. # Sending an event on their behalf should work fine
  2897. self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  2898. @override_config(
  2899. {"limit_usage_by_mau": True, "max_mau_value": 1, "mau_trial_days": 0}
  2900. )
  2901. def test_mau_limit(self) -> None:
  2902. # Create a room as the admin user. This will bump the monthly active users to 1.
  2903. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  2904. # Trying to join as the other user should fail due to reaching MAU limit.
  2905. self.helper.join(
  2906. room_id,
  2907. user=self.other_user,
  2908. tok=self.other_user_tok,
  2909. expect_code=HTTPStatus.FORBIDDEN,
  2910. )
  2911. # Logging in as the other user and joining a room should work, even
  2912. # though the MAU limit would stop the user doing so.
  2913. puppet_token = self._get_token()
  2914. self.helper.join(room_id, user=self.other_user, tok=puppet_token)
  2915. @parameterized_class(
  2916. ("url_prefix",),
  2917. [
  2918. ("/_synapse/admin/v1/whois/%s",),
  2919. ("/_matrix/client/r0/admin/whois/%s",),
  2920. ],
  2921. )
  2922. class WhoisRestTestCase(unittest.HomeserverTestCase):
  2923. servlets = [
  2924. synapse.rest.admin.register_servlets,
  2925. login.register_servlets,
  2926. ]
  2927. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2928. self.admin_user = self.register_user("admin", "pass", admin=True)
  2929. self.admin_user_tok = self.login("admin", "pass")
  2930. self.other_user = self.register_user("user", "pass")
  2931. self.url = self.url_prefix % self.other_user # type: ignore[attr-defined]
  2932. def test_no_auth(self) -> None:
  2933. """
  2934. Try to get information of an user without authentication.
  2935. """
  2936. channel = self.make_request("GET", self.url, b"{}")
  2937. self.assertEqual(HTTPStatus.UNAUTHORIZED, channel.code, msg=channel.json_body)
  2938. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2939. def test_requester_is_not_admin(self) -> None:
  2940. """
  2941. If the user is not a server admin, an error is returned.
  2942. """
  2943. self.register_user("user2", "pass")
  2944. other_user2_token = self.login("user2", "pass")
  2945. channel = self.make_request(
  2946. "GET",
  2947. self.url,
  2948. access_token=other_user2_token,
  2949. )
  2950. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  2951. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2952. def test_user_is_not_local(self) -> None:
  2953. """
  2954. Tests that a lookup for a user that is not a local returns a HTTPStatus.BAD_REQUEST
  2955. """
  2956. url = self.url_prefix % "@unknown_person:unknown_domain" # type: ignore[attr-defined]
  2957. channel = self.make_request(
  2958. "GET",
  2959. url,
  2960. access_token=self.admin_user_tok,
  2961. )
  2962. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  2963. self.assertEqual("Can only whois a local user", channel.json_body["error"])
  2964. def test_get_whois_admin(self) -> None:
  2965. """
  2966. The lookup should succeed for an admin.
  2967. """
  2968. channel = self.make_request(
  2969. "GET",
  2970. self.url,
  2971. access_token=self.admin_user_tok,
  2972. )
  2973. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2974. self.assertEqual(self.other_user, channel.json_body["user_id"])
  2975. self.assertIn("devices", channel.json_body)
  2976. def test_get_whois_user(self) -> None:
  2977. """
  2978. The lookup should succeed for a normal user looking up their own information.
  2979. """
  2980. other_user_token = self.login("user", "pass")
  2981. channel = self.make_request(
  2982. "GET",
  2983. self.url,
  2984. access_token=other_user_token,
  2985. )
  2986. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  2987. self.assertEqual(self.other_user, channel.json_body["user_id"])
  2988. self.assertIn("devices", channel.json_body)
  2989. class ShadowBanRestTestCase(unittest.HomeserverTestCase):
  2990. servlets = [
  2991. synapse.rest.admin.register_servlets,
  2992. login.register_servlets,
  2993. ]
  2994. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2995. self.store = hs.get_datastores().main
  2996. self.admin_user = self.register_user("admin", "pass", admin=True)
  2997. self.admin_user_tok = self.login("admin", "pass")
  2998. self.other_user = self.register_user("user", "pass")
  2999. self.url = "/_synapse/admin/v1/users/%s/shadow_ban" % urllib.parse.quote(
  3000. self.other_user
  3001. )
  3002. @parameterized.expand(["POST", "DELETE"])
  3003. def test_no_auth(self, method: str) -> None:
  3004. """
  3005. Try to get information of an user without authentication.
  3006. """
  3007. channel = self.make_request(method, self.url)
  3008. self.assertEqual(HTTPStatus.UNAUTHORIZED, channel.code, msg=channel.json_body)
  3009. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3010. @parameterized.expand(["POST", "DELETE"])
  3011. def test_requester_is_not_admin(self, method: str) -> None:
  3012. """
  3013. If the user is not a server admin, an error is returned.
  3014. """
  3015. other_user_token = self.login("user", "pass")
  3016. channel = self.make_request(method, self.url, access_token=other_user_token)
  3017. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  3018. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  3019. @parameterized.expand(["POST", "DELETE"])
  3020. def test_user_is_not_local(self, method: str) -> None:
  3021. """
  3022. Tests that shadow-banning for a user that is not a local returns a HTTPStatus.BAD_REQUEST
  3023. """
  3024. url = "/_synapse/admin/v1/whois/@unknown_person:unknown_domain"
  3025. channel = self.make_request(method, url, access_token=self.admin_user_tok)
  3026. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  3027. def test_success(self) -> None:
  3028. """
  3029. Shadow-banning should succeed for an admin.
  3030. """
  3031. # The user starts off as not shadow-banned.
  3032. other_user_token = self.login("user", "pass")
  3033. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  3034. self.assertFalse(result.shadow_banned)
  3035. channel = self.make_request("POST", self.url, access_token=self.admin_user_tok)
  3036. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  3037. self.assertEqual({}, channel.json_body)
  3038. # Ensure the user is shadow-banned (and the cache was cleared).
  3039. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  3040. self.assertTrue(result.shadow_banned)
  3041. # Un-shadow-ban the user.
  3042. channel = self.make_request(
  3043. "DELETE", self.url, access_token=self.admin_user_tok
  3044. )
  3045. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  3046. self.assertEqual({}, channel.json_body)
  3047. # Ensure the user is no longer shadow-banned (and the cache was cleared).
  3048. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  3049. self.assertFalse(result.shadow_banned)
  3050. class RateLimitTestCase(unittest.HomeserverTestCase):
  3051. servlets = [
  3052. synapse.rest.admin.register_servlets,
  3053. login.register_servlets,
  3054. ]
  3055. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3056. self.store = hs.get_datastores().main
  3057. self.admin_user = self.register_user("admin", "pass", admin=True)
  3058. self.admin_user_tok = self.login("admin", "pass")
  3059. self.other_user = self.register_user("user", "pass")
  3060. self.url = (
  3061. "/_synapse/admin/v1/users/%s/override_ratelimit"
  3062. % urllib.parse.quote(self.other_user)
  3063. )
  3064. @parameterized.expand(["GET", "POST", "DELETE"])
  3065. def test_no_auth(self, method: str) -> None:
  3066. """
  3067. Try to get information of a user without authentication.
  3068. """
  3069. channel = self.make_request(method, self.url, b"{}")
  3070. self.assertEqual(HTTPStatus.UNAUTHORIZED, channel.code, msg=channel.json_body)
  3071. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3072. @parameterized.expand(["GET", "POST", "DELETE"])
  3073. def test_requester_is_no_admin(self, method: str) -> None:
  3074. """
  3075. If the user is not a server admin, an error is returned.
  3076. """
  3077. other_user_token = self.login("user", "pass")
  3078. channel = self.make_request(
  3079. method,
  3080. self.url,
  3081. access_token=other_user_token,
  3082. )
  3083. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  3084. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  3085. @parameterized.expand(["GET", "POST", "DELETE"])
  3086. def test_user_does_not_exist(self, method: str) -> None:
  3087. """
  3088. Tests that a lookup for a user that does not exist returns a HTTPStatus.NOT_FOUND
  3089. """
  3090. url = "/_synapse/admin/v1/users/@unknown_person:test/override_ratelimit"
  3091. channel = self.make_request(
  3092. method,
  3093. url,
  3094. access_token=self.admin_user_tok,
  3095. )
  3096. self.assertEqual(HTTPStatus.NOT_FOUND, channel.code, msg=channel.json_body)
  3097. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3098. @parameterized.expand(
  3099. [
  3100. ("GET", "Can only look up local users"),
  3101. ("POST", "Only local users can be ratelimited"),
  3102. ("DELETE", "Only local users can be ratelimited"),
  3103. ]
  3104. )
  3105. def test_user_is_not_local(self, method: str, error_msg: str) -> None:
  3106. """
  3107. Tests that a lookup for a user that is not a local returns a HTTPStatus.BAD_REQUEST
  3108. """
  3109. url = (
  3110. "/_synapse/admin/v1/users/@unknown_person:unknown_domain/override_ratelimit"
  3111. )
  3112. channel = self.make_request(
  3113. method,
  3114. url,
  3115. access_token=self.admin_user_tok,
  3116. )
  3117. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  3118. self.assertEqual(error_msg, channel.json_body["error"])
  3119. def test_invalid_parameter(self) -> None:
  3120. """
  3121. If parameters are invalid, an error is returned.
  3122. """
  3123. # messages_per_second is a string
  3124. channel = self.make_request(
  3125. "POST",
  3126. self.url,
  3127. access_token=self.admin_user_tok,
  3128. content={"messages_per_second": "string"},
  3129. )
  3130. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  3131. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3132. # messages_per_second is negative
  3133. channel = self.make_request(
  3134. "POST",
  3135. self.url,
  3136. access_token=self.admin_user_tok,
  3137. content={"messages_per_second": -1},
  3138. )
  3139. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  3140. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3141. # burst_count is a string
  3142. channel = self.make_request(
  3143. "POST",
  3144. self.url,
  3145. access_token=self.admin_user_tok,
  3146. content={"burst_count": "string"},
  3147. )
  3148. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  3149. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3150. # burst_count is negative
  3151. channel = self.make_request(
  3152. "POST",
  3153. self.url,
  3154. access_token=self.admin_user_tok,
  3155. content={"burst_count": -1},
  3156. )
  3157. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  3158. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3159. def test_return_zero_when_null(self) -> None:
  3160. """
  3161. If values in database are `null` API should return an int `0`
  3162. """
  3163. self.get_success(
  3164. self.store.db_pool.simple_upsert(
  3165. table="ratelimit_override",
  3166. keyvalues={"user_id": self.other_user},
  3167. values={
  3168. "messages_per_second": None,
  3169. "burst_count": None,
  3170. },
  3171. )
  3172. )
  3173. # request status
  3174. channel = self.make_request(
  3175. "GET",
  3176. self.url,
  3177. access_token=self.admin_user_tok,
  3178. )
  3179. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  3180. self.assertEqual(0, channel.json_body["messages_per_second"])
  3181. self.assertEqual(0, channel.json_body["burst_count"])
  3182. def test_success(self) -> None:
  3183. """
  3184. Rate-limiting (set/update/delete) should succeed for an admin.
  3185. """
  3186. # request status
  3187. channel = self.make_request(
  3188. "GET",
  3189. self.url,
  3190. access_token=self.admin_user_tok,
  3191. )
  3192. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  3193. self.assertNotIn("messages_per_second", channel.json_body)
  3194. self.assertNotIn("burst_count", channel.json_body)
  3195. # set ratelimit
  3196. channel = self.make_request(
  3197. "POST",
  3198. self.url,
  3199. access_token=self.admin_user_tok,
  3200. content={"messages_per_second": 10, "burst_count": 11},
  3201. )
  3202. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  3203. self.assertEqual(10, channel.json_body["messages_per_second"])
  3204. self.assertEqual(11, channel.json_body["burst_count"])
  3205. # update ratelimit
  3206. channel = self.make_request(
  3207. "POST",
  3208. self.url,
  3209. access_token=self.admin_user_tok,
  3210. content={"messages_per_second": 20, "burst_count": 21},
  3211. )
  3212. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  3213. self.assertEqual(20, channel.json_body["messages_per_second"])
  3214. self.assertEqual(21, channel.json_body["burst_count"])
  3215. # request status
  3216. channel = self.make_request(
  3217. "GET",
  3218. self.url,
  3219. access_token=self.admin_user_tok,
  3220. )
  3221. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  3222. self.assertEqual(20, channel.json_body["messages_per_second"])
  3223. self.assertEqual(21, channel.json_body["burst_count"])
  3224. # delete ratelimit
  3225. channel = self.make_request(
  3226. "DELETE",
  3227. self.url,
  3228. access_token=self.admin_user_tok,
  3229. )
  3230. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  3231. self.assertNotIn("messages_per_second", channel.json_body)
  3232. self.assertNotIn("burst_count", channel.json_body)
  3233. # request status
  3234. channel = self.make_request(
  3235. "GET",
  3236. self.url,
  3237. access_token=self.admin_user_tok,
  3238. )
  3239. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  3240. self.assertNotIn("messages_per_second", channel.json_body)
  3241. self.assertNotIn("burst_count", channel.json_body)
  3242. class AccountDataTestCase(unittest.HomeserverTestCase):
  3243. servlets = [
  3244. synapse.rest.admin.register_servlets,
  3245. login.register_servlets,
  3246. ]
  3247. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3248. self.store = hs.get_datastores().main
  3249. self.admin_user = self.register_user("admin", "pass", admin=True)
  3250. self.admin_user_tok = self.login("admin", "pass")
  3251. self.other_user = self.register_user("user", "pass")
  3252. self.url = f"/_synapse/admin/v1/users/{self.other_user}/accountdata"
  3253. def test_no_auth(self) -> None:
  3254. """Try to get information of a user without authentication."""
  3255. channel = self.make_request("GET", self.url, {})
  3256. self.assertEqual(HTTPStatus.UNAUTHORIZED, channel.code, msg=channel.json_body)
  3257. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3258. def test_requester_is_no_admin(self) -> None:
  3259. """If the user is not a server admin, an error is returned."""
  3260. other_user_token = self.login("user", "pass")
  3261. channel = self.make_request(
  3262. "GET",
  3263. self.url,
  3264. access_token=other_user_token,
  3265. )
  3266. self.assertEqual(HTTPStatus.FORBIDDEN, channel.code, msg=channel.json_body)
  3267. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  3268. def test_user_does_not_exist(self) -> None:
  3269. """Tests that a lookup for a user that does not exist returns a 404"""
  3270. url = "/_synapse/admin/v1/users/@unknown_person:test/override_ratelimit"
  3271. channel = self.make_request(
  3272. "GET",
  3273. url,
  3274. access_token=self.admin_user_tok,
  3275. )
  3276. self.assertEqual(HTTPStatus.NOT_FOUND, channel.code, msg=channel.json_body)
  3277. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3278. def test_user_is_not_local(self) -> None:
  3279. """Tests that a lookup for a user that is not a local returns a 400"""
  3280. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/accountdata"
  3281. channel = self.make_request(
  3282. "GET",
  3283. url,
  3284. access_token=self.admin_user_tok,
  3285. )
  3286. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  3287. self.assertEqual("Can only look up local users", channel.json_body["error"])
  3288. def test_success(self) -> None:
  3289. """Request account data should succeed for an admin."""
  3290. # add account data
  3291. self.get_success(
  3292. self.store.add_account_data_for_user(self.other_user, "m.global", {"a": 1})
  3293. )
  3294. self.get_success(
  3295. self.store.add_account_data_to_room(
  3296. self.other_user, "test_room", "m.per_room", {"b": 2}
  3297. )
  3298. )
  3299. channel = self.make_request(
  3300. "GET",
  3301. self.url,
  3302. access_token=self.admin_user_tok,
  3303. )
  3304. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  3305. self.assertEqual(
  3306. {"a": 1}, channel.json_body["account_data"]["global"]["m.global"]
  3307. )
  3308. self.assertEqual(
  3309. {"b": 2},
  3310. channel.json_body["account_data"]["rooms"]["test_room"]["m.per_room"],
  3311. )