gerrit_util.py 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886
  1. # Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """
  5. Utilities for requesting information for a Gerrit server via HTTPS.
  6. https://gerrit-review.googlesource.com/Documentation/rest-api.html
  7. """
  8. from __future__ import annotations
  9. import base64
  10. import contextlib
  11. import functools
  12. import http.cookiejar
  13. import json
  14. import logging
  15. import os
  16. import random
  17. import re
  18. import shutil
  19. import socket
  20. import subprocess
  21. import sys
  22. import tempfile
  23. import threading
  24. import time
  25. import urllib.parse
  26. from dataclasses import dataclass
  27. from io import StringIO
  28. from multiprocessing.pool import ThreadPool
  29. from typing import Any, Container, Dict, List, Optional
  30. from typing import Tuple, TypedDict, cast
  31. import httplib2
  32. import httplib2.socks
  33. import auth
  34. import gclient_utils
  35. import metrics
  36. import metrics_utils
  37. import newauth
  38. import scm
  39. import subprocess2
  40. # HACK: httplib2 has significant bugs with its proxy support in
  41. # python3. All httplib2 code should be rewritten to just use python
  42. # stdlib which does not have these bugs.
  43. #
  44. # Prior to that, however, we will directly patch the buggy
  45. # implementation of httplib2.socks.socksocket.__rewriteproxy which does
  46. # not properly expect bytes as its argument instead of str.
  47. #
  48. # Note that __rewriteproxy is inherently buggy, as it relies on the
  49. # python stdlib client to send the entire request header in a single
  50. # call to socket.sendall, which is not explicitly guaranteed.
  51. #
  52. # Changes:
  53. # * all string literals changed to bytes literals.
  54. # * added more http methods to recognize.
  55. # * all __symbols changed to _socksocket__symbols (Python __ munging).
  56. # * Type annotations added to function signature.
  57. def __fixed_rewrite_proxy(self: httplib2.socks.socksocket, header: bytes):
  58. """ rewrite HTTP request headers to support non-tunneling proxies
  59. (i.e. those which do not support the CONNECT method).
  60. This only works for HTTP (not HTTPS) since HTTPS requires tunneling.
  61. """
  62. host, endpt = None, None
  63. hdrs = header.split(b"\r\n")
  64. for hdr in hdrs:
  65. if hdr.lower().startswith(b"host:"):
  66. host = hdr
  67. elif hdr.lower().split(b" ")[0] in (b"get", b"head", b"post", b"put",
  68. b"patch"):
  69. endpt = hdr
  70. if host and endpt:
  71. hdrs.remove(host)
  72. hdrs.remove(endpt)
  73. host = host.split(b" ")[1]
  74. endpt = endpt.split(b" ")
  75. if self._socksocket__proxy[4] != None \
  76. and self._socksocket__proxy[5] != None:
  77. hdrs.insert(0, self._socksocket__getauthheader())
  78. hdrs.insert(0, b"Host: %s" % host)
  79. hdrs.insert(0,
  80. b"%s http://%s%s %s" % (endpt[0], host, endpt[1], endpt[2]))
  81. return b"\r\n".join(hdrs)
  82. httplib2.socks.socksocket._socksocket__rewriteproxy = __fixed_rewrite_proxy
  83. # TODO: Should fix these warnings.
  84. # pylint: disable=line-too-long
  85. LOGGER = logging.getLogger()
  86. # With a starting sleep time of 12.0 seconds, x <= [1.8-2.2]x backoff, and six
  87. # total tries, the sleep time between the first and last tries will be ~6 min
  88. # (excluding time for each try).
  89. TRY_LIMIT = 6
  90. SLEEP_TIME = 12.0
  91. MAX_BACKOFF = 2.2
  92. MIN_BACKOFF = 1.8
  93. # Controls the transport protocol used to communicate with Gerrit.
  94. # This is parameterized primarily to enable GerritTestCase.
  95. GERRIT_PROTOCOL = 'https'
  96. # Controls how many concurrent Gerrit connections there can be.
  97. MAX_CONCURRENT_CONNECTION = 20
  98. def time_sleep(seconds):
  99. # Use this so that it can be mocked in tests without interfering with python
  100. # system machinery.
  101. return time.sleep(seconds)
  102. def time_time():
  103. # Use this so that it can be mocked in tests without interfering with python
  104. # system machinery.
  105. return time.time()
  106. def log_retry_and_sleep(seconds, attempt, try_limit):
  107. LOGGER.info('Will retry in %d seconds (%d more times)...', seconds,
  108. try_limit - attempt - 1)
  109. time_sleep(seconds)
  110. return seconds * random.uniform(MIN_BACKOFF, MAX_BACKOFF)
  111. class GerritError(Exception):
  112. """Exception class for errors commuicating with the gerrit-on-borg service."""
  113. def __init__(self, http_status, message, *args, **kwargs):
  114. super(GerritError, self).__init__(*args, **kwargs)
  115. self.http_status = http_status
  116. self.message = '(%d) %s' % (self.http_status, message)
  117. def __str__(self):
  118. return self.message
  119. def _QueryString(params, first_param=None):
  120. """Encodes query parameters in the key:val[+key:val...] format specified here:
  121. https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
  122. """
  123. q = [urllib.parse.quote(first_param)] if first_param else []
  124. q.extend(['%s:%s' % (key, val.replace(" ", "+")) for key, val in params])
  125. return '+'.join(q)
  126. class SSOHelper(object):
  127. """SSOHelper finds a Google-internal SSO helper."""
  128. _sso_cmd: Optional[str] = None
  129. def find_cmd(self) -> str:
  130. """Returns the cached command-line to invoke git-remote-sso.
  131. If git-remote-sso is not in $PATH, returns None.
  132. """
  133. if self._sso_cmd is not None:
  134. return self._sso_cmd
  135. cmd = shutil.which('git-remote-sso')
  136. if cmd is None:
  137. cmd = ''
  138. self._sso_cmd = cmd
  139. return cmd
  140. # Global instance
  141. ssoHelper = SSOHelper()
  142. @functools.lru_cache(maxsize=None)
  143. def ShouldUseSSO(host: str, email: str) -> bool:
  144. """Return True if we should use SSO for the given Gerrit host and user."""
  145. LOGGER.debug("Determining whether we should use SSO...")
  146. if not newauth.Enabled():
  147. LOGGER.debug("SSO=False: not opted in")
  148. return False
  149. if not host.endswith('.googlesource.com'):
  150. LOGGER.debug("SSO=False: non-googlesource host %r", host)
  151. return False
  152. if newauth.SkipSSO():
  153. LOGGER.debug("SSO=False: set skip SSO config")
  154. return False
  155. if not ssoHelper.find_cmd():
  156. LOGGER.debug("SSO=False: no SSO command")
  157. return False
  158. if not email:
  159. LOGGER.debug(
  160. "SSO=True: email is empty or missing (and SSO command available)")
  161. return True
  162. if email.endswith('@google.com'):
  163. LOGGER.debug("SSO=True: email is google.com")
  164. return True
  165. if not email.endswith('@chromium.org'):
  166. LOGGER.debug("SSO=False: not chromium.org")
  167. return False
  168. authenticator = SSOAuthenticator()
  169. records = GetAccountEmails(host, 'self', authenticator=authenticator)
  170. if any(email == r['email'] for r in records):
  171. LOGGER.debug("SSO=True: email is linked to google.com")
  172. return True
  173. LOGGER.debug("SSO=False: unlinked chromium.org")
  174. return False
  175. class _Authenticator(object):
  176. """Base authenticator class for authenticator implementations to subclass."""
  177. # Cached _Authenticator subclass instance, resolved via get().
  178. _resolved: Optional[_Authenticator] = None
  179. _resolved_lock = threading.Lock()
  180. def authenticate(self, conn: HttpConn):
  181. """Adds authentication information to the HttpConn."""
  182. raise NotImplementedError()
  183. def debug_summary_state(self) -> str:
  184. """If this _Authenticator has any debugging information about its state,
  185. _WriteGitPushTraces will call this to include in the git push traces.
  186. Return value is any relevant debugging information with all PII/secrets
  187. redacted.
  188. """
  189. raise NotImplementedError()
  190. @classmethod
  191. def is_applicable(cls, *, conn: Optional[HttpConn] = None) -> bool:
  192. """Must return True if this Authenticator is available in the current
  193. environment.
  194. If conn is not None, return True if this Authenticator is
  195. applicable to the given conn in the current environment.
  196. """
  197. raise NotImplementedError()
  198. def ensure_authenticated(self, gerrit_host: str, git_host: str) -> Tuple[bool, str]:
  199. """Returns (bypassable, error message).
  200. If the error message is empty, there is no error to report.
  201. If bypassable is true, the caller will allow the user to continue past the
  202. error.
  203. """
  204. return (True, '')
  205. @classmethod
  206. def get(cls):
  207. """Returns: (_Authenticator) The identified _Authenticator to use.
  208. Probes the local system and its environment and identifies the
  209. _Authenticator instance to use.
  210. The resolved _Authenticator instance is cached as a class variable.
  211. """
  212. with cls._resolved_lock:
  213. if ret := cls._resolved:
  214. return ret
  215. use_new_auth = newauth.Enabled()
  216. # Allow skipping SSOAuthenticator for local testing purposes.
  217. skip_sso = newauth.SkipSSO()
  218. if use_new_auth:
  219. LOGGER.debug('_Authenticator.get: using new auth stack')
  220. if LuciContextAuthenticator.is_applicable():
  221. LOGGER.debug(
  222. '_Authenticator.get: using LUCI context authenticator')
  223. ret = LuciContextAuthenticator()
  224. else:
  225. LOGGER.debug(
  226. '_Authenticator.get: using chained authenticator')
  227. a = [
  228. SSOAuthenticator(),
  229. # GCE detection can't distinguish cloud workstations.
  230. GceAuthenticator(),
  231. LuciAuthAuthenticator(),
  232. ]
  233. if skip_sso:
  234. LOGGER.debug(
  235. 'Authenticator.get: skipping SSOAuthenticator.')
  236. a = a[1:]
  237. ret = ChainedAuthenticator(a)
  238. cls._resolved = ret
  239. return ret
  240. authenticators = [
  241. LuciContextAuthenticator,
  242. GceAuthenticator,
  243. CookiesAuthenticator,
  244. ]
  245. for candidate in authenticators:
  246. if candidate.is_applicable():
  247. LOGGER.debug('_Authenticator.get: Selected %s.',
  248. candidate.__name__)
  249. ret = candidate()
  250. cls._resolved = ret
  251. return ret
  252. auth_names = ', '.join(a.__name__ for a in authenticators)
  253. raise ValueError(
  254. f"Could not find suitable authenticator, tried: [{auth_names}]."
  255. )
  256. def debug_auth() -> Tuple[str, str]:
  257. """Returns the name of the chosen auth scheme and any additional debugging
  258. information for that authentication scheme. """
  259. authn = _Authenticator.get()
  260. return authn.__class__.__name__, authn.debug_summary_state()
  261. def ensure_authenticated(gerrit_host: str, git_host: str) -> Tuple[bool, str]:
  262. """Returns (bypassable, error message).
  263. If the error message is empty, there is no error to report. If bypassable is
  264. true, the caller will allow the user to continue past the error.
  265. """
  266. return _Authenticator.get().ensure_authenticated(gerrit_host, git_host)
  267. class SSOAuthenticator(_Authenticator):
  268. """SSOAuthenticator implements a Google-internal authentication scheme.
  269. TEMPORARY configuration for Googlers (one `url` block for each Gerrit host):
  270. [url "sso://chromium/"]
  271. insteadOf = https://chromium.googlesource.com/
  272. insteadOf = http://chromium.googlesource.com/
  273. [depot-tools]
  274. useNewAuthStack = 1
  275. """
  276. # This is set to true in tests, allows _parse_config to consume expired
  277. # cookies.
  278. _testing_load_expired_cookies = False
  279. # How long we should wait for the sso helper to write and close stdout.
  280. # Overridden in tests.
  281. _timeout_secs = 5
  282. @dataclass
  283. class SSOInfo:
  284. proxy: httplib2.ProxyInfo
  285. cookies: http.cookiejar.CookieJar
  286. headers: Dict[str, str]
  287. # SSOInfo is a cached blob of information used by the `authenticate` method.
  288. _sso_info: Optional[SSOInfo] = None
  289. _sso_info_lock = threading.Lock()
  290. @classmethod
  291. def _resolve_sso_cmd(cls) -> Tuple[str, ...]:
  292. """Returns the cached command-line to invoke git-remote-sso.
  293. If git-remote-sso is not in $PATH, returns ().
  294. """
  295. cmd = ssoHelper.find_cmd()
  296. if not cmd:
  297. return ()
  298. return (
  299. cmd,
  300. '-print_config',
  301. 'sso://*.git.corp.google.com',
  302. )
  303. @classmethod
  304. def is_applicable(cls, *, conn: Optional[HttpConn] = None) -> bool:
  305. if not cls._resolve_sso_cmd():
  306. return False
  307. email: str = scm.GIT.GetConfig(os.getcwd(), 'user.email', default='')
  308. if conn is not None:
  309. return ShouldUseSSO(conn.host, email)
  310. return email.endswith('@google.com')
  311. @classmethod
  312. def _parse_config(cls, config: str) -> SSOInfo:
  313. parsed: Dict[str, str] = dict(line.strip().split('=', 1)
  314. for line in config.splitlines())
  315. fullAuthHeader = cast(
  316. str,
  317. scm.GIT.Capture([
  318. 'config',
  319. '-f',
  320. parsed['include.path'],
  321. 'http.extraHeader',
  322. ]))
  323. headerKey, headerValue = fullAuthHeader.split(':', 1)
  324. headers = {headerKey.strip(): headerValue.strip()}
  325. proxy_host, proxy_port = parsed['http.proxy'].split(':', 1)
  326. cfpath = parsed['http.cookiefile']
  327. cj = http.cookiejar.MozillaCookieJar(cfpath)
  328. # NOTE: python3.8 doesn't support httponly cookie lines, so we parse
  329. # this manually. Once we move to python3.10+, this hack can be removed.
  330. with open(cfpath) as cf:
  331. cookiedata = cf.read().replace('#HttpOnly_', '')
  332. # _really_load is the way that MozillaCookieJar subclasses
  333. # FileCookieJar. Calling this directly is better than reimplementing the
  334. # entire _really_load function manually.
  335. cj._really_load(
  336. StringIO(cookiedata),
  337. cfpath,
  338. ignore_discard=False,
  339. ignore_expires=cls._testing_load_expired_cookies,
  340. )
  341. return cls.SSOInfo(proxy=httplib2.ProxyInfo(
  342. httplib2.socks.PROXY_TYPE_HTTP_NO_TUNNEL, proxy_host.encode(),
  343. int(proxy_port)),
  344. cookies=cj,
  345. headers=headers)
  346. @classmethod
  347. def _launch_sso_helper(cls) -> SSOInfo:
  348. """Launches the git-remote-sso process and extracts the parsed SSOInfo.
  349. Raises an exception if something goes wrong.
  350. """
  351. cmd = cls._resolve_sso_cmd()
  352. with tempdir() as tdir:
  353. tf = os.path.join(tdir, 'git-remote-sso.stderr')
  354. with open(tf, mode='w') as stderr_file:
  355. # NOTE: The git-remote-sso helper does the following:
  356. #
  357. # 1. writes files to disk.
  358. # 2. writes config to stdout, referencing those files.
  359. # 3. closes stdout (thus sending EOF to us, allowing
  360. # sys.stdout.read() to complete).
  361. # 4. waits for stdin to close.
  362. # 5. deletes files on disk (which is why we make sys.stdin a PIPE
  363. # instead of closing it outright).
  364. #
  365. # NOTE: the http.proxy value in the emitted config points to
  366. # a socket which is owned by a system service, not `proc` itself.
  367. with subprocess2.Popen(cmd,
  368. stdout=subprocess2.PIPE,
  369. stderr=stderr_file,
  370. stdin=subprocess2.PIPE,
  371. encoding='utf-8') as proc:
  372. stderr_file.close() # we can close after process starts.
  373. timedout = False
  374. def _fire_timeout():
  375. nonlocal timedout
  376. timedout = True
  377. proc.kill()
  378. timer = threading.Timer(cls._timeout_secs, _fire_timeout)
  379. timer.start()
  380. try:
  381. stdout_data = proc.stdout.read()
  382. finally:
  383. timer.cancel()
  384. if timedout:
  385. LOGGER.error(
  386. 'SSOAuthenticator: Timeout: %r: reading config.',
  387. cmd)
  388. raise subprocess.TimeoutExpired(
  389. cmd=cmd, timeout=cls._timeout_secs)
  390. # if the process already ended, then something is wrong.
  391. retcode = proc.poll()
  392. # if stdout was closed without any data, we need to wait for
  393. # end-of-process here and hope for an error message - the
  394. # poll above is racy in this case (we could see stdout EOF
  395. # but the process may not have quit yet).
  396. if not retcode and not stdout_data:
  397. retcode = proc.wait(timeout=cls._timeout_secs)
  398. # We timed out while doing `wait` - we can't safely open
  399. # stderr on windows, so just emit a generic timeout
  400. # exception.
  401. if retcode is None:
  402. LOGGER.error(
  403. 'SSOAuthenticator: Timeout: %r: waiting error output.',
  404. cmd)
  405. raise subprocess.TimeoutExpired(
  406. cmd=cmd, timeout=cls._timeout_secs)
  407. # Finally, if the poll or wait ended up getting the retcode,
  408. # it means the process failed, so we can read the stderr
  409. # file and reflect it back to the user.
  410. if retcode is not None:
  411. # process failed - we should be able to read the tempfile.
  412. with open(tf, encoding='utf-8') as stderr:
  413. sys.exit(
  414. f'SSOAuthenticator: exit {retcode}: {stderr.read().strip()}'
  415. )
  416. return cls._parse_config(stdout_data)
  417. @classmethod
  418. def _get_sso_info(cls) -> SSOInfo:
  419. with cls._sso_info_lock:
  420. info = cls._sso_info
  421. if not info:
  422. info = cls._launch_sso_helper()
  423. # HACK: `git-remote-sso` doesn't always properly warm up the
  424. # cookies - in this case, run a canned git operation against
  425. # a public repo to cause `git-remote-sso` to warm the cookies
  426. # up, and then try pulling config again.
  427. #
  428. # BUG: b/342644760
  429. if not any(c.domain == '.google.com' for c in info.cookies):
  430. LOGGER.debug('SSO: Refreshing .google.com cookies.')
  431. scm.GIT.Capture(['ls-remote', 'sso://chromium/All-Projects'])
  432. info = cls._launch_sso_helper()
  433. if not any(c.domain == '.google.com' for c in info.cookies):
  434. raise ValueError('Unable to extract .google.com cookie.')
  435. cls._sso_info = info
  436. return info
  437. def authenticate(self, conn: HttpConn):
  438. sso_info = self._get_sso_info()
  439. conn.proxy_info = sso_info.proxy
  440. conn.req_headers.update(sso_info.headers)
  441. # Now we must rewrite:
  442. # https://xxx.googlesource.com ->
  443. # http://xxx.git.corp.google.com
  444. parsed = urllib.parse.urlparse(conn.req_uri)
  445. parsed = parsed._replace(scheme='http')
  446. if (hostname :=
  447. parsed.hostname) and hostname.endswith('.googlesource.com'):
  448. assert not parsed.port, "SSOAuthenticator: netloc: port not supported"
  449. assert not parsed.username, "SSOAuthenticator: netloc: username not supported"
  450. assert not parsed.password, "SSOAuthenticator: netloc: password not supported"
  451. hostname_parts = hostname.rsplit('.', 2) # X, googlesource, com
  452. conn.req_host = hostname_parts[0] + '.git.corp.google.com'
  453. parsed = parsed._replace(netloc=conn.req_host)
  454. conn.req_uri = parsed.geturl()
  455. # Finally, add cookies
  456. sso_info.cookies.add_cookie_header(conn)
  457. assert 'Cookie' in conn.req_headers, (
  458. 'sso_info.cookies.add_cookie_header failed to add Cookie.')
  459. def debug_summary_state(self) -> str:
  460. return ''
  461. class CookiesAuthenticator(_Authenticator):
  462. """_Authenticator implementation that uses ".gitcookies" for token.
  463. Expected case for developer workstations.
  464. """
  465. _EMPTY = object()
  466. def __init__(self):
  467. # Credentials will be loaded lazily on first use. This ensures
  468. # _Authenticator get() can always construct an authenticator, even if
  469. # something is broken. This allows 'creds-check' to proceed to actually
  470. # checking creds later, rigorously (instead of blowing up with a cryptic
  471. # error if they are wrong).
  472. self._gitcookies = self._EMPTY
  473. @classmethod
  474. def is_applicable(cls, *, conn: Optional[HttpConn] = None) -> bool:
  475. # We consider CookiesAuthenticator always applicable for now.
  476. return True
  477. @property
  478. def gitcookies(self):
  479. if self._gitcookies is self._EMPTY:
  480. self._gitcookies = self._get_gitcookies()
  481. return self._gitcookies
  482. @classmethod
  483. def get_new_password_url(cls, host):
  484. assert not host.startswith('http')
  485. # Assume *.googlesource.com pattern.
  486. parts = host.split('.')
  487. # remove -review suffix if present.
  488. if parts[0].endswith('-review'):
  489. parts[0] = parts[0][:-len('-review')]
  490. return 'https://%s/new-password' % ('.'.join(parts))
  491. @classmethod
  492. def _get_new_password_message(cls, host):
  493. if host is None:
  494. return ('Git host for Gerrit upload is unknown. Check your remote '
  495. 'and the branch your branch is tracking. This tool assumes '
  496. 'that you are using a git server at *.googlesource.com.')
  497. url = cls.get_new_password_url(host)
  498. return 'You can (re)generate your credentials by visiting %s' % url
  499. @classmethod
  500. def get_gitcookies_path(cls) -> str:
  501. if envVal := os.getenv('GIT_COOKIES_PATH'):
  502. return envVal
  503. return os.path.expanduser(
  504. scm.GIT.GetConfig(os.getcwd(), 'http.cookiefile',
  505. os.path.join('~', '.gitcookies')))
  506. @classmethod
  507. def _get_gitcookies(cls):
  508. gitcookies = {}
  509. path = cls.get_gitcookies_path()
  510. if not os.path.exists(path):
  511. return gitcookies
  512. try:
  513. f = gclient_utils.FileRead(path, 'rb').splitlines()
  514. except IOError:
  515. return gitcookies
  516. for line in f:
  517. try:
  518. fields = line.strip().split('\t')
  519. if line.strip().startswith('#') or len(fields) != 7:
  520. continue
  521. domain, xpath, key, value = fields[0], fields[2], fields[
  522. 5], fields[6]
  523. if xpath == '/' and key == 'o':
  524. if value.startswith('git-'):
  525. login, secret_token = value.split('=', 1)
  526. gitcookies[domain] = (login, secret_token)
  527. else:
  528. gitcookies[domain] = ('', value)
  529. except (IndexError, ValueError, TypeError) as exc:
  530. LOGGER.warning(exc)
  531. return gitcookies
  532. def _get_auth_for_host(self, host):
  533. for domain, creds in self.gitcookies.items():
  534. if http.cookiejar.domain_match(host, domain):
  535. return (creds[0], creds[1])
  536. return None
  537. def authenticate(self, conn: HttpConn):
  538. a = self._get_auth_for_host(conn.req_host)
  539. if a:
  540. login, cred = a
  541. if login:
  542. secret = base64.b64encode(f'{login}:{cred}'.encode('utf-8'))
  543. conn.req_headers[
  544. 'Authorization'] = f'Basic {secret.decode("utf-8")}'
  545. else:
  546. conn.req_headers['Authorization'] = f'Bearer {cred}'
  547. def ensure_authenticated(self, gerrit_host: str, git_host: str) -> Tuple[bool, str]:
  548. """Returns (bypassable, error message).
  549. If the error message is empty, there is no error to report.
  550. If bypassable is true, the caller will allow the user to continue past the
  551. error.
  552. """
  553. # Lazy-loader to identify Gerrit and Git hosts.
  554. gerrit_auth = self._get_auth_for_host(gerrit_host)
  555. git_auth = self._get_auth_for_host(git_host)
  556. if gerrit_auth and git_auth:
  557. if gerrit_auth == git_auth:
  558. return True, ''
  559. all_gsrc = self._get_auth_for_host('d0esN0tEx1st.googlesource.com')
  560. print(
  561. 'WARNING: You have different credentials for Gerrit and git hosts:\n'
  562. ' %s\n'
  563. ' %s\n'
  564. ' Consider running the following command:\n'
  565. ' git cl creds-check\n'
  566. ' %s\n'
  567. ' %s' %
  568. (git_host, gerrit_host,
  569. ('Hint: delete creds for .googlesource.com' if all_gsrc else
  570. ''), self._get_new_password_message(git_host)))
  571. return True, 'If you know what you are doing'
  572. missing = (([] if gerrit_auth else [gerrit_host]) +
  573. ([] if git_auth else [git_host]))
  574. return False, ('Credentials for the following hosts are required:\n'
  575. ' %s\n'
  576. 'These are read from %s\n'
  577. '%s' % ('\n '.join(missing), self.get_gitcookies_path(),
  578. self._get_new_password_message(git_host)))
  579. # Used to redact the cookies from the gitcookies file.
  580. GITCOOKIES_REDACT_RE = re.compile(r'1/.*')
  581. def debug_summary_state(self) -> str:
  582. gitcookies_path = self.get_gitcookies_path()
  583. if os.path.isfile(gitcookies_path):
  584. gitcookies = gclient_utils.FileRead(gitcookies_path)
  585. return self.GITCOOKIES_REDACT_RE.sub('REDACTED', gitcookies)
  586. return ''
  587. def get_auth_email(self, host):
  588. """Best effort parsing of email to be used for auth for the given host."""
  589. a = self._get_auth_for_host(host)
  590. if not a:
  591. return None
  592. login = a[0]
  593. # login typically looks like 'git-xxx.example.com'
  594. if not login.startswith('git-') or '.' not in login:
  595. return None
  596. username, domain = login[len('git-'):].split('.', 1)
  597. return '%s@%s' % (username, domain)
  598. class GceAuthenticator(_Authenticator):
  599. """_Authenticator implementation that uses GCE metadata service for token.
  600. """
  601. _INFO_URL = 'http://metadata.google.internal'
  602. _ACQUIRE_URL = ('%s/computeMetadata/v1/instance/'
  603. 'service-accounts/default/token' % _INFO_URL)
  604. _ACQUIRE_HEADERS = {"Metadata-Flavor": "Google"}
  605. _cache_is_gce = None
  606. _token_cache = None
  607. _token_expiration = None
  608. @classmethod
  609. def is_applicable(cls, *, conn: Optional[HttpConn] = None):
  610. if os.getenv('SKIP_GCE_AUTH_FOR_GIT'):
  611. return False
  612. if cls._cache_is_gce is None:
  613. cls._cache_is_gce = cls._test_is_gce()
  614. return cls._cache_is_gce
  615. @classmethod
  616. def _test_is_gce(cls):
  617. # Based on https://cloud.google.com/compute/docs/metadata#runninggce
  618. resp, _ = cls._get(cls._INFO_URL)
  619. if resp is None:
  620. return False
  621. return resp.get('metadata-flavor') == 'Google'
  622. @staticmethod
  623. def _get(url, **kwargs):
  624. next_delay_sec = 1.0
  625. for i in range(TRY_LIMIT):
  626. p = urllib.parse.urlparse(url)
  627. if p.scheme not in ('http', 'https'):
  628. raise RuntimeError("Don't know how to work with protocol '%s'" %
  629. p.scheme)
  630. try:
  631. resp, contents = httplib2.Http().request(url, 'GET', **kwargs)
  632. except (socket.error, httplib2.HttpLib2Error,
  633. httplib2.socks.ProxyError) as e:
  634. LOGGER.debug('GET [%s] raised %s', url, e)
  635. return None, None
  636. LOGGER.debug('GET [%s] #%d/%d (%d)', url, i + 1, TRY_LIMIT,
  637. resp.status)
  638. if resp.status < 500:
  639. return (resp, contents)
  640. # Retry server error status codes.
  641. LOGGER.warning('Encountered server error')
  642. if TRY_LIMIT - i > 1:
  643. next_delay_sec = log_retry_and_sleep(next_delay_sec, i,
  644. TRY_LIMIT)
  645. return None, None
  646. @classmethod
  647. def _get_token_dict(cls):
  648. # If cached token is valid for at least 25 seconds, return it.
  649. if cls._token_cache and time_time() + 25 < cls._token_expiration:
  650. return cls._token_cache
  651. resp, contents = cls._get(cls._ACQUIRE_URL,
  652. headers=cls._ACQUIRE_HEADERS)
  653. if resp is None or resp.status != 200:
  654. return None
  655. cls._token_cache = json.loads(contents)
  656. cls._token_expiration = cls._token_cache['expires_in'] + time_time()
  657. return cls._token_cache
  658. def authenticate(self, conn: HttpConn):
  659. token_dict = self._get_token_dict()
  660. if not token_dict:
  661. return
  662. conn.req_headers[
  663. 'Authorization'] = '%(token_type)s %(access_token)s' % token_dict
  664. def debug_summary_state(self) -> str:
  665. # TODO(b/343230702) - report ambient account name.
  666. return ''
  667. class LuciContextAuthenticator(_Authenticator):
  668. """_Authenticator implementation that uses LUCI_CONTEXT ambient local auth.
  669. """
  670. @staticmethod
  671. def is_applicable(*, conn: Optional[HttpConn] = None):
  672. return auth.has_luci_context_local_auth()
  673. def __init__(self):
  674. self._authenticator = auth.Authenticator(' '.join(
  675. [auth.OAUTH_SCOPE_EMAIL, auth.OAUTH_SCOPE_GERRIT]))
  676. def authenticate(self, conn: HttpConn):
  677. conn.req_headers[
  678. 'Authorization'] = f'Bearer {self._authenticator.get_access_token().token}'
  679. def debug_summary_state(self) -> str:
  680. # TODO(b/343230702) - report ambient account name.
  681. return ''
  682. class LuciAuthAuthenticator(LuciContextAuthenticator):
  683. """_Authenticator implementation that uses `luci-auth` credentials.
  684. This is the same as LuciContextAuthenticator, except that it is for local
  685. non-google.com developer credentials.
  686. """
  687. @staticmethod
  688. def is_applicable(*, conn: Optional[HttpConn] = None):
  689. return True
  690. class ChainedAuthenticator(_Authenticator):
  691. """_Authenticator that delegates to others in sequence.
  692. Authenticators should implement the method `is_applicable_for`.
  693. """
  694. def __init__(self, authenticators: List[_Authenticator]):
  695. self.authenticators = list(authenticators)
  696. def is_applicable(self, *, conn: Optional[HttpConn] = None) -> bool:
  697. return bool(any(
  698. a.is_applicable(conn=conn) for a in self.authenticators))
  699. def authenticate(self, conn: HttpConn):
  700. for a in self.authenticators:
  701. if a.is_applicable(conn=conn):
  702. a.authenticate(conn)
  703. break
  704. else:
  705. raise ValueError(
  706. f'{self!r} has no applicable authenticator for {conn!r}')
  707. def debug_summary_state(self) -> str:
  708. return ''
  709. class ReqParams(TypedDict):
  710. uri: str
  711. method: str
  712. headers: Dict[str, str]
  713. body: Optional[str]
  714. class HttpConn(httplib2.Http):
  715. """HttpConn is an httplib2.Http with additional request-specific fields."""
  716. def __init__(self, *args, req_host: str, req_uri: str, req_method: str,
  717. req_headers: Dict[str, str], req_body: Optional[str],
  718. **kwargs) -> None:
  719. self.req_host = req_host
  720. self.req_uri = req_uri
  721. self.req_method = req_method
  722. self.req_headers = req_headers
  723. self.req_body = req_body
  724. super().__init__(*args, **kwargs)
  725. @property
  726. def req_params(self) -> ReqParams:
  727. return {
  728. 'uri': self.req_uri,
  729. 'method': self.req_method,
  730. 'headers': self.req_headers,
  731. 'body': self.req_body,
  732. }
  733. # NOTE: We want to use HttpConn with CookieJar.add_cookie_header, so have
  734. # compatible interface for that here.
  735. #
  736. # NOTE: Someone should really normalize this 'HttpConn' and httplib2
  737. # implementation to just be plain python3 stdlib instead. All of this was
  738. # written during the bad old days of python2.6/2.7, pre-vpython.
  739. def has_header(self, header: str) -> bool:
  740. return header in self.req_headers
  741. def get_full_url(self) -> str:
  742. return self.req_uri
  743. def get_header(self,
  744. header: str,
  745. default: Optional[str] = None) -> Optional[str]:
  746. return self.req_headers.get(header, default)
  747. def add_unredirected_header(self, header: str, value: str):
  748. # NOTE: httplib2 does not support unredirected headers.
  749. self.req_headers[header] = value
  750. @property
  751. def unverifiable(self) -> bool:
  752. return False
  753. @property
  754. def origin_req_host(self) -> str:
  755. return self.req_host
  756. @property
  757. def type(self) -> str:
  758. return urllib.parse.urlparse(self.req_uri).scheme
  759. @property
  760. def host(self) -> str:
  761. return self.req_host
  762. def CreateHttpConn(host: str,
  763. path: str,
  764. reqtype='GET',
  765. headers: Optional[Dict[str, str]] = None,
  766. body: Optional[Dict] = None,
  767. timeout=300,
  768. *,
  769. authenticator: Optional[_Authenticator] = None) -> HttpConn:
  770. """Opens an HTTPS connection to a Gerrit service, and sends a request."""
  771. headers = headers or {}
  772. bare_host = host.partition(':')[0]
  773. url = path
  774. if not url.startswith('/'):
  775. url = '/' + url
  776. if not url.startswith('/a/'):
  777. url = '/a%s' % url
  778. rendered_body: Optional[str] = None
  779. if body:
  780. rendered_body = json.dumps(body, sort_keys=True)
  781. headers.setdefault('Content-Type', 'application/json')
  782. uri = urllib.parse.urljoin(f'{GERRIT_PROTOCOL}://{host}', url)
  783. conn = HttpConn(timeout=timeout,
  784. req_host=host,
  785. req_uri=uri,
  786. req_method=reqtype,
  787. req_headers=headers,
  788. req_body=rendered_body)
  789. if authenticator is None:
  790. authenticator = _Authenticator.get()
  791. # TODO(crbug.com/1059384): Automatically detect when running on cloudtop.
  792. if isinstance(authenticator, GceAuthenticator):
  793. print('If you\'re on a cloudtop instance, export '
  794. 'SKIP_GCE_AUTH_FOR_GIT=1 in your env.')
  795. authenticator.authenticate(conn)
  796. if 'Authorization' not in conn.req_headers:
  797. LOGGER.debug('No authorization found for %s.' % bare_host)
  798. if LOGGER.isEnabledFor(logging.DEBUG):
  799. LOGGER.debug('%s %s', conn.req_method, conn.req_uri)
  800. LOGGER.debug('conn.proxy_info=%r', conn.proxy_info)
  801. for key, val in conn.req_headers.items():
  802. if key in ('Authorization', 'Cookie'):
  803. val = 'HIDDEN'
  804. LOGGER.debug('%s: %s', key, val)
  805. if conn.req_body:
  806. LOGGER.debug(conn.req_body)
  807. return conn
  808. def ReadHttpResponse(conn: HttpConn,
  809. accept_statuses: Container[int] = frozenset([200]),
  810. max_tries=TRY_LIMIT):
  811. """Reads an HTTP response from a connection into a string buffer.
  812. Args:
  813. conn: An Http object created by CreateHttpConn above.
  814. accept_statuses: Treat any of these statuses as success. Default: [200]
  815. Common additions include 204, 400, and 404.
  816. max_tries: The maximum number of times the request should be attempted.
  817. Returns:
  818. A string buffer containing the connection's reply.
  819. """
  820. response = contents = None
  821. sleep_time = SLEEP_TIME
  822. for idx in range(max_tries):
  823. before_response = time.time()
  824. try:
  825. response, contents = conn.request(**conn.req_params)
  826. except socket.timeout:
  827. if idx < max_tries - 1:
  828. sleep_time = log_retry_and_sleep(sleep_time, idx, max_tries)
  829. continue
  830. raise
  831. contents = contents.decode('utf-8', 'replace')
  832. response_time = time.time() - before_response
  833. metrics.collector.add_repeated(
  834. 'http_requests',
  835. metrics_utils.extract_http_metrics(conn.req_params['uri'],
  836. conn.req_params['method'],
  837. response.status, response_time))
  838. # If response.status is an accepted status,
  839. # or response.status < 500 then the result is final; break retry loop.
  840. # If the response is 404/409 it might be because of replication lag,
  841. # so keep trying anyway. If it is 429, it is generally ok to retry after
  842. # a backoff.
  843. if (response.status in accept_statuses or response.status < 500
  844. and response.status not in [404, 409, 429]):
  845. LOGGER.debug('got response %d for %s %s', response.status,
  846. conn.req_params['method'], conn.req_params['uri'])
  847. # If 404 was in accept_statuses, then it's expected that the file
  848. # might not exist, so don't return the gitiles error page because
  849. # that's not the "content" that was actually requested.
  850. if response.status == 404:
  851. contents = ''
  852. break
  853. # A status >=500 is assumed to be a possible transient error; retry.
  854. http_version = 'HTTP/%s' % ('1.1' if response.version == 11 else '1.0')
  855. LOGGER.warning(
  856. 'A transient error occurred while querying %s:\n'
  857. '%s %s %s\n'
  858. '%s %d %s\n'
  859. '%s', conn.req_host, conn.req_params['method'],
  860. conn.req_params['uri'], http_version, http_version, response.status,
  861. response.reason, contents)
  862. if idx < max_tries - 1:
  863. sleep_time = log_retry_and_sleep(sleep_time, idx, max_tries)
  864. # end of retries loop
  865. # Help the type checker a bit here - it can't figure out the `except` logic
  866. # in the loop above.
  867. assert response, (
  868. 'Impossible: End of retry loop without response or exception.')
  869. if response.status in accept_statuses:
  870. return StringIO(contents)
  871. if response.status in (302, 401, 403):
  872. www_authenticate = response.get('www-authenticate')
  873. if not www_authenticate:
  874. print('Your Gerrit credentials might be misconfigured.')
  875. else:
  876. auth_match = re.search('realm="([^"]+)"', www_authenticate, re.I)
  877. host = auth_match.group(1) if auth_match else conn.req_host
  878. new_password_url = CookiesAuthenticator.get_new_password_url(host)
  879. print('Authentication failed. Please make sure your .gitcookies '
  880. f'file has credentials for {host}.')
  881. print(f'(Re)generate credentials here: {new_password_url}')
  882. print('Try:\n git cl creds-check')
  883. reason = '%s: %s' % (response.reason, contents)
  884. raise GerritError(response.status, reason)
  885. def ReadHttpJsonResponse(conn,
  886. accept_statuses: Container[int] = frozenset([200]),
  887. max_tries=TRY_LIMIT) -> dict:
  888. """Parses an https response as json."""
  889. fh = ReadHttpResponse(conn, accept_statuses, max_tries)
  890. # The first line of the response should always be: )]}'
  891. s = fh.readline()
  892. if s and s.rstrip() != ")]}'":
  893. raise GerritError(200, 'Unexpected json output: %s' % s[:100])
  894. s = fh.read()
  895. if not s:
  896. return {}
  897. return json.loads(s)
  898. def CallGerritApi(host, path, **kwargs):
  899. """Helper for calling a Gerrit API that returns a JSON response."""
  900. conn_kwargs = {}
  901. conn_kwargs.update(
  902. (k, kwargs[k]) for k in ['reqtype', 'headers', 'body'] if k in kwargs)
  903. conn = CreateHttpConn(host, path, **conn_kwargs)
  904. read_kwargs = {}
  905. read_kwargs.update(
  906. (k, kwargs[k]) for k in ['accept_statuses'] if k in kwargs)
  907. return ReadHttpJsonResponse(conn, **read_kwargs)
  908. def QueryChanges(host,
  909. params,
  910. first_param=None,
  911. limit=None,
  912. o_params=None,
  913. start=None):
  914. """
  915. Queries a gerrit-on-borg server for changes matching query terms.
  916. Args:
  917. params: A list of key:value pairs for search parameters, as documented
  918. here (e.g. ('is', 'owner') for a parameter 'is:owner'):
  919. https://gerrit-review.googlesource.com/Documentation/user-search.html#search-operators
  920. first_param: A change identifier
  921. limit: Maximum number of results to return.
  922. start: how many changes to skip (starting with the most recent)
  923. o_params: A list of additional output specifiers, as documented here:
  924. https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
  925. Returns:
  926. A list of json-decoded query results.
  927. """
  928. # Note that no attempt is made to escape special characters; YMMV.
  929. if not params and not first_param:
  930. raise RuntimeError('QueryChanges requires search parameters')
  931. path = 'changes/?q=%s' % _QueryString(params, first_param)
  932. if start:
  933. path = '%s&start=%s' % (path, start)
  934. if limit:
  935. path = '%s&n=%d' % (path, limit)
  936. if o_params:
  937. path = '%s&%s' % (path, '&'.join(['o=%s' % p for p in o_params]))
  938. return ReadHttpJsonResponse(CreateHttpConn(host, path, timeout=30))
  939. def GenerateAllChanges(host,
  940. params,
  941. first_param=None,
  942. limit=500,
  943. o_params=None,
  944. start=None):
  945. """Queries a gerrit-on-borg server for all the changes matching the query
  946. terms.
  947. WARNING: this is unreliable if a change matching the query is modified while
  948. this function is being called.
  949. A single query to gerrit-on-borg is limited on the number of results by the
  950. limit parameter on the request (see QueryChanges) and the server maximum
  951. limit.
  952. Args:
  953. params, first_param: Refer to QueryChanges().
  954. limit: Maximum number of requested changes per query.
  955. o_params: Refer to QueryChanges().
  956. start: Refer to QueryChanges().
  957. Returns:
  958. A generator object to the list of returned changes.
  959. """
  960. already_returned = set()
  961. def at_most_once(cls):
  962. for cl in cls:
  963. if cl['_number'] not in already_returned:
  964. already_returned.add(cl['_number'])
  965. yield cl
  966. start = start or 0
  967. cur_start = start
  968. more_changes = True
  969. while more_changes:
  970. # This will fetch changes[start..start+limit] sorted by most recently
  971. # updated. Since the rank of any change in this list can be changed any
  972. # time (say user posting comment), subsequent calls may overalp like
  973. # this: > initial order ABCDEFGH query[0..3] => ABC > E gets updated.
  974. # New order: EABCDFGH query[3..6] => CDF # C is a dup query[6..9] =>
  975. # GH # E is missed.
  976. page = QueryChanges(host, params, first_param, limit, o_params,
  977. cur_start)
  978. for cl in at_most_once(page):
  979. yield cl
  980. more_changes = [cl for cl in page if '_more_changes' in cl]
  981. if len(more_changes) > 1:
  982. raise GerritError(
  983. 200,
  984. 'Received %d changes with a _more_changes attribute set but should '
  985. 'receive at most one.' % len(more_changes))
  986. if more_changes:
  987. cur_start += len(page)
  988. # If we paged through, query again the first page which in most
  989. # circumstances will fetch all changes that were modified while this
  990. # function was run.
  991. if start != cur_start:
  992. page = QueryChanges(host, params, first_param, limit, o_params, start)
  993. for cl in at_most_once(page):
  994. yield cl
  995. def MultiQueryChanges(host,
  996. params,
  997. change_list,
  998. limit=None,
  999. o_params=None,
  1000. start=None):
  1001. """Initiate a query composed of multiple sets of query parameters."""
  1002. if not change_list:
  1003. raise RuntimeError(
  1004. "MultiQueryChanges requires a list of change numbers/id's")
  1005. q = [
  1006. 'q=%s' % '+OR+'.join([urllib.parse.quote(str(x)) for x in change_list])
  1007. ]
  1008. if params:
  1009. q.append(_QueryString(params))
  1010. if limit:
  1011. q.append('n=%d' % limit)
  1012. if start:
  1013. q.append('S=%s' % start)
  1014. if o_params:
  1015. q.extend(['o=%s' % p for p in o_params])
  1016. path = 'changes/?%s' % '&'.join(q)
  1017. try:
  1018. result = ReadHttpJsonResponse(CreateHttpConn(host, path))
  1019. except GerritError as e:
  1020. msg = '%s:\n%s' % (e.message, path)
  1021. raise GerritError(e.http_status, msg)
  1022. return result
  1023. def GetGerritFetchUrl(host):
  1024. """Given a Gerrit host name returns URL of a Gerrit instance to fetch from."""
  1025. return '%s://%s/' % (GERRIT_PROTOCOL, host)
  1026. def GetCodeReviewTbrScore(host, project):
  1027. """Given a Gerrit host name and project, return the Code-Review score for TBR.
  1028. """
  1029. conn = CreateHttpConn(host,
  1030. '/projects/%s' % urllib.parse.quote(project, ''))
  1031. project = ReadHttpJsonResponse(conn)
  1032. if ('labels' not in project or 'Code-Review' not in project['labels']
  1033. or 'values' not in project['labels']['Code-Review']):
  1034. return 1
  1035. return max([int(x) for x in project['labels']['Code-Review']['values']])
  1036. def GetChangePageUrl(host, change_number):
  1037. """Given a Gerrit host name and change number, returns change page URL."""
  1038. return '%s://%s/#/c/%d/' % (GERRIT_PROTOCOL, host, change_number)
  1039. def GetChangeUrl(host, change):
  1040. """Given a Gerrit host name and change ID, returns a URL for the change."""
  1041. return '%s://%s/a/changes/%s' % (GERRIT_PROTOCOL, host, change)
  1042. def GetChange(host, change, accept_statuses: Container[int] = frozenset([200])):
  1043. """Queries a Gerrit server for information about a single change."""
  1044. path = 'changes/%s' % change
  1045. return ReadHttpJsonResponse(CreateHttpConn(host, path),
  1046. accept_statuses=accept_statuses)
  1047. def GetChangeDetail(host, change, o_params=None):
  1048. """Queries a Gerrit server for extended information about a single change."""
  1049. path = 'changes/%s/detail' % change
  1050. if o_params:
  1051. path += '?%s' % '&'.join(['o=%s' % p for p in o_params])
  1052. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1053. def GetChangeCommit(host: str, change: str, revision: str = 'current') -> dict:
  1054. """Query a Gerrit server for a revision associated with a change."""
  1055. path = 'changes/%s/revisions/%s/commit?links' % (change, revision)
  1056. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1057. def GetChangeCurrentRevision(host, change):
  1058. """Get information about the latest revision for a given change."""
  1059. return QueryChanges(host, [], change, o_params=('CURRENT_REVISION', ))
  1060. def GetChangeRevisions(host, change):
  1061. """Gets information about all revisions associated with a change."""
  1062. return QueryChanges(host, [], change, o_params=('ALL_REVISIONS', ))
  1063. def GetChangeReview(host, change, revision=None):
  1064. """Gets the current review information for a change."""
  1065. if not revision:
  1066. jmsg = GetChangeRevisions(host, change)
  1067. if not jmsg:
  1068. return None
  1069. if len(jmsg) > 1:
  1070. raise GerritError(
  1071. 200, 'Multiple changes found for ChangeId %s.' % change)
  1072. revision = jmsg[0]['current_revision']
  1073. path = 'changes/%s/revisions/%s/review'
  1074. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1075. def GetChangeComments(host, change):
  1076. """Get the line- and file-level comments on a change."""
  1077. path = 'changes/%s/comments' % change
  1078. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1079. def GetChangeRobotComments(host, change):
  1080. """Gets the line- and file-level robot comments on a change."""
  1081. path = 'changes/%s/robotcomments' % change
  1082. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1083. def GetRelatedChanges(host, change, revision='current'):
  1084. """Gets the related changes for a given change and revision."""
  1085. path = 'changes/%s/revisions/%s/related' % (change, revision)
  1086. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1087. def AbandonChange(host, change, msg=''):
  1088. """Abandons a Gerrit change."""
  1089. path = 'changes/%s/abandon' % change
  1090. body = {'message': msg} if msg else {}
  1091. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1092. return ReadHttpJsonResponse(conn)
  1093. def MoveChange(host, change, destination_branch):
  1094. """Move a Gerrit change to different destination branch."""
  1095. path = 'changes/%s/move' % change
  1096. body = {'destination_branch': destination_branch, 'keep_all_votes': True}
  1097. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1098. return ReadHttpJsonResponse(conn)
  1099. def RestoreChange(host, change, msg=''):
  1100. """Restores a previously abandoned change."""
  1101. path = 'changes/%s/restore' % change
  1102. body = {'message': msg} if msg else {}
  1103. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1104. return ReadHttpJsonResponse(conn)
  1105. def RebaseChange(host, change, base=None):
  1106. """Rebases a change."""
  1107. path = f'changes/{change}/rebase'
  1108. body = {'base': base} if base else {}
  1109. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1110. # If a rebase fails due to a merge conflict, Gerrit returns 409. Retrying
  1111. # more than once probably won't help since the merge conflict will still
  1112. # exist.
  1113. return ReadHttpJsonResponse(conn, max_tries=2)
  1114. def SubmitChange(host, change):
  1115. """Submits a Gerrit change via Gerrit."""
  1116. path = 'changes/%s/submit' % change
  1117. conn = CreateHttpConn(host, path, reqtype='POST')
  1118. return ReadHttpJsonResponse(conn)
  1119. def GetChangesSubmittedTogether(host, change):
  1120. """Get all changes submitted with the given one."""
  1121. path = 'changes/%s/submitted_together?o=NON_VISIBLE_CHANGES' % change
  1122. conn = CreateHttpConn(host, path, reqtype='GET')
  1123. return ReadHttpJsonResponse(conn)
  1124. def PublishChangeEdit(host, change, notify=True):
  1125. """Publish a Gerrit change edit."""
  1126. path = 'changes/%s/edit:publish' % change
  1127. body = {'notify': 'ALL' if notify else 'NONE'}
  1128. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1129. return ReadHttpJsonResponse(conn, accept_statuses=(204, ))
  1130. def ChangeEdit(host, change, path, data):
  1131. """Puts content of a file into a change edit."""
  1132. path = 'changes/%s/edit/%s' % (change, urllib.parse.quote(path, ''))
  1133. body = {
  1134. 'binary_content':
  1135. 'data:text/plain;base64,%s' %
  1136. base64.b64encode(data.encode('utf-8')).decode('utf-8')
  1137. }
  1138. conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
  1139. return ReadHttpJsonResponse(conn, accept_statuses=(204, 409))
  1140. def SetChangeEditMessage(host, change, message):
  1141. """Sets the commit message of a change edit."""
  1142. path = 'changes/%s/edit:message' % change
  1143. body = {'message': message}
  1144. conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
  1145. return ReadHttpJsonResponse(conn, accept_statuses=(204, 409))
  1146. def HasPendingChangeEdit(host, change):
  1147. conn = CreateHttpConn(host, 'changes/%s/edit' % change)
  1148. try:
  1149. ReadHttpResponse(conn)
  1150. except GerritError as e:
  1151. # 204 No Content means no pending change.
  1152. if e.http_status == 204:
  1153. return False
  1154. raise
  1155. return True
  1156. def DeletePendingChangeEdit(host, change):
  1157. conn = CreateHttpConn(host, 'changes/%s/edit' % change, reqtype='DELETE')
  1158. # On success, Gerrit returns status 204; if the edit was already deleted it
  1159. # returns 404. Anything else is an error.
  1160. ReadHttpResponse(conn, accept_statuses=[204, 404])
  1161. def CherryPick(host, change, destination, revision='current', message=None):
  1162. """Create a cherry-pick commit from the given change, onto the given
  1163. destination.
  1164. """
  1165. path = 'changes/%s/revisions/%s/cherrypick' % (change, revision)
  1166. body = {'destination': destination}
  1167. if message:
  1168. body['message'] = message
  1169. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1170. # If a cherry pick fails due to a merge conflict, Gerrit returns 409.
  1171. # Retrying more than once probably won't help since the merge conflict will
  1172. # still exist.
  1173. return ReadHttpJsonResponse(conn, max_tries=2)
  1174. def CherryPickCommit(host, project, commit, destination):
  1175. """Cherry-pick a commit from a project to a destination branch."""
  1176. project = urllib.parse.quote(project, '')
  1177. path = f'projects/{project}/commits/{commit}/cherrypick'
  1178. body = {'destination': destination}
  1179. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1180. return ReadHttpJsonResponse(conn)
  1181. def GetFileContents(host, change, path):
  1182. """Get the contents of a file with the given path in the given revision.
  1183. Returns:
  1184. A bytes object with the file's contents.
  1185. """
  1186. path = 'changes/%s/revisions/current/files/%s/content' % (
  1187. change, urllib.parse.quote(path, ''))
  1188. conn = CreateHttpConn(host, path, reqtype='GET')
  1189. return base64.b64decode(ReadHttpResponse(conn).read())
  1190. def SetCommitMessage(host, change, description, notify='ALL'):
  1191. """Updates a commit message."""
  1192. assert notify in ('ALL', 'NONE')
  1193. path = 'changes/%s/message' % change
  1194. body = {'message': description, 'notify': notify}
  1195. conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
  1196. try:
  1197. ReadHttpResponse(conn, accept_statuses=[200, 204])
  1198. except GerritError as e:
  1199. raise GerritError(
  1200. e.http_status,
  1201. 'Received unexpected http status while editing message '
  1202. 'in change %s' % change)
  1203. def GetCommitIncludedIn(host, project, commit):
  1204. """Retrieves the branches and tags for a given commit.
  1205. https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-included-in
  1206. Returns:
  1207. A JSON object with keys of 'branches' and 'tags'.
  1208. """
  1209. path = 'projects/%s/commits/%s/in' % (urllib.parse.quote(project,
  1210. ''), commit)
  1211. conn = CreateHttpConn(host, path, reqtype='GET')
  1212. return ReadHttpJsonResponse(conn, accept_statuses=[200])
  1213. def IsCodeOwnersEnabledOnHost(host):
  1214. """Check if the code-owners plugin is enabled for the host."""
  1215. path = 'config/server/capabilities'
  1216. capabilities = ReadHttpJsonResponse(CreateHttpConn(host, path))
  1217. return 'code-owners-checkCodeOwner' in capabilities
  1218. def IsCodeOwnersEnabledOnRepo(host, repo):
  1219. """Check if the code-owners plugin is enabled for the repo."""
  1220. repo = PercentEncodeForGitRef(repo)
  1221. path = '/projects/%s/code_owners.project_config' % repo
  1222. config = ReadHttpJsonResponse(CreateHttpConn(host, path))
  1223. return not config['status'].get('disabled', False)
  1224. def GetOwnersForFile(host,
  1225. project,
  1226. branch,
  1227. path,
  1228. limit=100,
  1229. resolve_all_users=True,
  1230. highest_score_only=False,
  1231. seed=None,
  1232. o_params=('DETAILS', )):
  1233. """Gets information about owners attached to a file."""
  1234. path = 'projects/%s/branches/%s/code_owners/%s' % (urllib.parse.quote(
  1235. project, ''), urllib.parse.quote(branch,
  1236. ''), urllib.parse.quote(path, ''))
  1237. q = ['resolve-all-users=%s' % json.dumps(resolve_all_users)]
  1238. if highest_score_only:
  1239. q.append('highest-score-only=%s' % json.dumps(highest_score_only))
  1240. if seed:
  1241. q.append('seed=%d' % seed)
  1242. if limit:
  1243. q.append('n=%d' % limit)
  1244. if o_params:
  1245. q.extend(['o=%s' % p for p in o_params])
  1246. if q:
  1247. path = '%s?%s' % (path, '&'.join(q))
  1248. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1249. def GetReviewers(host, change):
  1250. """Gets information about all reviewers attached to a change."""
  1251. path = 'changes/%s/reviewers' % change
  1252. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1253. def GetReview(host, change, revision):
  1254. """Gets review information about a specific revision of a change."""
  1255. path = 'changes/%s/revisions/%s/review' % (change, revision)
  1256. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1257. def AddReviewers(host,
  1258. change,
  1259. reviewers=None,
  1260. ccs=None,
  1261. notify=True,
  1262. accept_statuses: Container[int] = frozenset([200, 400, 422])):
  1263. """Add reviewers to a change."""
  1264. if not reviewers and not ccs:
  1265. return None
  1266. if not change:
  1267. return None
  1268. reviewers = frozenset(reviewers or [])
  1269. ccs = frozenset(ccs or [])
  1270. path = 'changes/%s/revisions/current/review' % change
  1271. body = {
  1272. 'drafts': 'KEEP',
  1273. 'reviewers': [],
  1274. 'notify': 'ALL' if notify else 'NONE',
  1275. }
  1276. for r in sorted(reviewers | ccs):
  1277. state = 'REVIEWER' if r in reviewers else 'CC'
  1278. body['reviewers'].append({
  1279. 'reviewer': r,
  1280. 'state': state,
  1281. 'notify': 'NONE', # We handled `notify` argument above.
  1282. })
  1283. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1284. # Gerrit will return 400 if one or more of the requested reviewers are
  1285. # unprocessable. We read the response object to see which were rejected,
  1286. # warn about them, and retry with the remainder.
  1287. resp = ReadHttpJsonResponse(conn, accept_statuses=accept_statuses)
  1288. errored = set()
  1289. for result in resp.get('reviewers', {}).values():
  1290. r = result.get('input')
  1291. state = 'REVIEWER' if r in reviewers else 'CC'
  1292. if result.get('error'):
  1293. errored.add(r)
  1294. LOGGER.warning('Note: "%s" not added as a %s' % (r, state.lower()))
  1295. if errored:
  1296. # Try again, adding only those that didn't fail, and only accepting 200.
  1297. AddReviewers(host,
  1298. change,
  1299. reviewers=(reviewers - errored),
  1300. ccs=(ccs - errored),
  1301. notify=notify,
  1302. accept_statuses=[200])
  1303. def SetReview(host, change, msg=None, labels=None, notify=None, ready=None):
  1304. """Sets labels and/or adds a message to a code review."""
  1305. if not msg and not labels:
  1306. return
  1307. path = 'changes/%s/revisions/current/review' % change
  1308. body: Dict[str, Any] = {'drafts': 'KEEP'}
  1309. if msg:
  1310. body['message'] = msg
  1311. if labels:
  1312. body['labels'] = labels
  1313. if notify is not None:
  1314. body['notify'] = 'ALL' if notify else 'NONE'
  1315. if ready:
  1316. body['ready'] = True
  1317. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1318. response = ReadHttpJsonResponse(conn)
  1319. if labels:
  1320. for key, val in labels.items():
  1321. if ('labels' not in response or key not in response['labels']
  1322. or int(response['labels'][key] != int(val))):
  1323. raise GerritError(
  1324. 200,
  1325. 'Unable to set "%s" label on change %s.' % (key, change))
  1326. return response
  1327. def ResetReviewLabels(host,
  1328. change,
  1329. label,
  1330. value='0',
  1331. message=None,
  1332. notify=None):
  1333. """Resets the value of a given label for all reviewers on a change."""
  1334. # This is tricky, because we want to work on the "current revision", but
  1335. # there's always the risk that "current revision" will change in between
  1336. # API calls. So, we check "current revision" at the beginning and end; if
  1337. # it has changed, raise an exception.
  1338. jmsg = GetChangeCurrentRevision(host, change)
  1339. if not jmsg:
  1340. raise GerritError(
  1341. 200, 'Could not get review information for change "%s"' % change)
  1342. value = str(value)
  1343. revision = jmsg[0]['current_revision']
  1344. path = 'changes/%s/revisions/%s/review' % (change, revision)
  1345. message = message or ('%s label set to %s programmatically.' %
  1346. (label, value))
  1347. jmsg = GetReview(host, change, revision)
  1348. if not jmsg:
  1349. raise GerritError(
  1350. 200, 'Could not get review information for revision %s '
  1351. 'of change %s' % (revision, change))
  1352. for review in jmsg.get('labels', {}).get(label, {}).get('all', []):
  1353. if str(review.get('value', value)) != value:
  1354. body = {
  1355. 'drafts': 'KEEP',
  1356. 'message': message,
  1357. 'labels': {
  1358. label: value
  1359. },
  1360. 'on_behalf_of': review['_account_id'],
  1361. }
  1362. if notify:
  1363. body['notify'] = notify
  1364. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1365. response = ReadHttpJsonResponse(conn)
  1366. if str(response['labels'][label]) != value:
  1367. username = review.get('email', jmsg.get('name', ''))
  1368. raise GerritError(
  1369. 200, 'Unable to set %s label for user "%s"'
  1370. ' on change %s.' % (label, username, change))
  1371. jmsg = GetChangeCurrentRevision(host, change)
  1372. if not jmsg:
  1373. raise GerritError(
  1374. 200, 'Could not get review information for change "%s"' % change)
  1375. if jmsg[0]['current_revision'] != revision:
  1376. raise GerritError(
  1377. 200, 'While resetting labels on change "%s", '
  1378. 'a new patchset was uploaded.' % change)
  1379. def CreateChange(host, project, branch='main', subject='', params=()):
  1380. """
  1381. Creates a new change.
  1382. Args:
  1383. params: A list of additional ChangeInput specifiers, as documented here:
  1384. (e.g. ('is_private', 'true') to mark the change private.
  1385. https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#change-input
  1386. Returns:
  1387. ChangeInfo for the new change.
  1388. """
  1389. path = 'changes/'
  1390. body = {'project': project, 'branch': branch, 'subject': subject}
  1391. body.update(dict(params))
  1392. for key in 'project', 'branch', 'subject':
  1393. if not body[key]:
  1394. raise GerritError(200, '%s is required' % key.title())
  1395. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1396. return ReadHttpJsonResponse(conn, accept_statuses=[201])
  1397. def CreateGerritBranch(host, project, branch, commit):
  1398. """Creates a new branch from given project and commit
  1399. https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-branch
  1400. Returns:
  1401. A JSON object with 'ref' key.
  1402. """
  1403. path = 'projects/%s/branches/%s' % (project, branch)
  1404. body = {'revision': commit}
  1405. conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
  1406. response = ReadHttpJsonResponse(conn, accept_statuses=[201, 409])
  1407. if response:
  1408. return response
  1409. raise GerritError(200, 'Unable to create gerrit branch')
  1410. def CreateGerritTag(host, project, tag, commit):
  1411. """Creates a new tag at the given commit.
  1412. https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-tag
  1413. Returns:
  1414. A JSON object with 'ref' key.
  1415. """
  1416. path = 'projects/%s/tags/%s' % (project, tag)
  1417. body = {'revision': commit}
  1418. conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
  1419. response = ReadHttpJsonResponse(conn, accept_statuses=[201])
  1420. if response:
  1421. return response
  1422. raise GerritError(200, 'Unable to create gerrit tag')
  1423. def GetHead(host, project):
  1424. """Retrieves current HEAD of Gerrit project
  1425. https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-head
  1426. Returns:
  1427. A JSON object with 'ref' key.
  1428. """
  1429. path = 'projects/%s/HEAD' % (project)
  1430. conn = CreateHttpConn(host, path, reqtype='GET')
  1431. response = ReadHttpJsonResponse(conn, accept_statuses=[200])
  1432. if response:
  1433. return response
  1434. raise GerritError(200, 'Unable to update gerrit HEAD')
  1435. def UpdateHead(host, project, branch):
  1436. """Updates Gerrit HEAD to point to branch
  1437. https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-head
  1438. Returns:
  1439. A JSON object with 'ref' key.
  1440. """
  1441. path = 'projects/%s/HEAD' % (project)
  1442. body = {'ref': branch}
  1443. conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
  1444. response = ReadHttpJsonResponse(conn, accept_statuses=[200])
  1445. if response:
  1446. return response
  1447. raise GerritError(200, 'Unable to update gerrit HEAD')
  1448. def GetGerritBranch(host, project, branch):
  1449. """Gets a branch info from given project and branch name.
  1450. See:
  1451. https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-branch
  1452. Returns:
  1453. A JSON object with 'revision' key if the branch exists, otherwise None.
  1454. """
  1455. path = 'projects/%s/branches/%s' % (project, branch)
  1456. conn = CreateHttpConn(host, path, reqtype='GET')
  1457. return ReadHttpJsonResponse(conn, accept_statuses=[200, 404])
  1458. def GetProjectHead(host, project):
  1459. conn = CreateHttpConn(host,
  1460. '/projects/%s/HEAD' % urllib.parse.quote(project, ''))
  1461. return ReadHttpJsonResponse(conn, accept_statuses=[200])
  1462. def GetAccountDetails(host, account_id='self'):
  1463. """Returns details of the account.
  1464. If account_id is not given, uses magic value 'self' which corresponds to
  1465. whichever account user is authenticating as.
  1466. Documentation:
  1467. https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account
  1468. Returns None if account is not found (i.e., Gerrit returned 404).
  1469. """
  1470. conn = CreateHttpConn(host, '/accounts/%s' % account_id)
  1471. return ReadHttpJsonResponse(conn, accept_statuses=[200, 404])
  1472. class EmailRecord(TypedDict):
  1473. email: str
  1474. preferred: bool # This should be NotRequired[bool] in 3.11+
  1475. def GetAccountEmails(host,
  1476. account_id='self',
  1477. *,
  1478. authenticator: Optional[_Authenticator] = None
  1479. ) -> Optional[List[EmailRecord]]:
  1480. """Returns all emails for this account, and an indication of which of these
  1481. is preferred.
  1482. If account_id is not given, uses magic value 'self' which corresponds to
  1483. whichever account user is authenticating as.
  1484. Requires Modify Account permission to view emails other than 'self'.
  1485. Documentation:
  1486. https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-account-emails
  1487. Returns None if account is not found (i.e. Gerrit returned 404).
  1488. """
  1489. conn = CreateHttpConn(host,
  1490. '/accounts/%s/emails' % account_id,
  1491. authenticator=authenticator)
  1492. resp = ReadHttpJsonResponse(conn, accept_statuses=[200, 404])
  1493. if resp is None:
  1494. return None
  1495. return cast(List[EmailRecord], resp)
  1496. def ValidAccounts(host, accounts, max_threads=10):
  1497. """Returns a mapping from valid account to its details.
  1498. Invalid accounts, either not existing or without unique match,
  1499. are not present as returned dictionary keys.
  1500. """
  1501. assert not isinstance(accounts, str), type(accounts)
  1502. accounts = list(set(accounts))
  1503. if not accounts:
  1504. return {}
  1505. def get_one(account):
  1506. try:
  1507. return account, GetAccountDetails(host, account)
  1508. except GerritError:
  1509. return None, None
  1510. valid = {}
  1511. with contextlib.closing(ThreadPool(min(max_threads,
  1512. len(accounts)))) as pool:
  1513. for account, details in pool.map(get_one, accounts):
  1514. if account and details:
  1515. valid[account] = details
  1516. return valid
  1517. def PercentEncodeForGitRef(original):
  1518. """Applies percent-encoding for strings sent to Gerrit via git ref metadata.
  1519. The encoding used is based on but stricter than URL encoding (Section 2.1 of
  1520. RFC 3986). The only non-escaped characters are alphanumerics, and 'SPACE'
  1521. (U+0020) can be represented as 'LOW LINE' (U+005F) or 'PLUS SIGN' (U+002B).
  1522. For more information, see the Gerrit docs here:
  1523. https://gerrit-review.googlesource.com/Documentation/user-upload.html#message
  1524. """
  1525. safe = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '
  1526. encoded = ''.join(c if c in safe else '%%%02X' % ord(c) for c in original)
  1527. # Spaces are not allowed in git refs; gerrit will interpret either '_' or
  1528. # '+' (or '%20') as space. Use '_' since that has been supported the
  1529. # longest.
  1530. return encoded.replace(' ', '_')
  1531. @contextlib.contextmanager
  1532. def tempdir():
  1533. tdir = None
  1534. try:
  1535. tdir = tempfile.mkdtemp(suffix='gerrit_util')
  1536. yield tdir
  1537. finally:
  1538. if tdir:
  1539. gclient_utils.rmtree(tdir)
  1540. def ChangeIdentifier(project, change_number):
  1541. """Returns change identifier "project~number" suitable for |change| arg of
  1542. this module API.
  1543. Such format is allows for more efficient Gerrit routing of HTTP requests,
  1544. comparing to specifying just change_number.
  1545. """
  1546. assert int(change_number)
  1547. return '%s~%s' % (urllib.parse.quote(project, ''), change_number)