gerrit_util.py 74 KB

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