1
0

test_user.py 173 KB

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