gerrit_util.py 74 KB

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