blob: 78f6e191d53b82a0038f1e66084fd8ec676d397a [file] [log] [blame]
Zack Williams7f87d3e2020-06-05 12:36:39 -07001#!/usr/bin/env python3
2
3# SPDX-FileCopyrightText: © 2020 Open Networking Foundation <support@opennetworking.org>
4# SPDX-License-Identifier: Apache-2.0
5
6from __future__ import absolute_import
7
8import argparse
9import json
10import logging
11import urllib.request
12import urllib.parse
13import base64
14
15# create shared logger
16logging.basicConfig()
17logger = logging.getLogger("cg")
18
19# global dict of jsonpath expressions -> compiled jsonpath parsers, as
20# reparsing expressions in each loop results in 100x longer execution time
21gjpaths = {}
22
23# gerrit headers is cached
24gerrit_headers = []
25
26# gerrit_groups is a cache of groups, to prevent multiple lookups
27gerrit_groups = {}
28
29
30def parse_crowdgroups_args():
31 """
32 parse CLI arguments
33 """
34
35 parser = argparse.ArgumentParser(description="Crowd-Gerrit group sync")
36
37 # Positional args
38 parser.add_argument(
39 "settings", type=argparse.FileType("r"), help="JSON settings file",
40 )
41
42 parser.add_argument(
43 "--debug", action="store_true", help="Print additional debugging information"
44 )
45
46 return parser.parse_args()
47
48
49def basic_auth_header(username, password):
50 """
51 returns a tuple containing a http basic auth header
52 """
53 creds_str = "%s:%s" % (username, password)
54 creds_b64 = base64.standard_b64encode(creds_str.encode("utf-8"))
55
56 return ("Authorization", "Basic %s" % creds_b64.decode("utf-8"))
57
58
59def json_api_get(url, headers, data=None, trim_prefix=False, allow_failure=False):
60 """
61 Call JSON API endpoint, return data as a dict
62 """
63
64 # if data included, encode it as JSON
65 if data:
66 data_enc = str(json.dumps(data)).encode("utf-8")
67
68 request = urllib.request.Request(url, data=data_enc, method="POST")
69 request.add_header("Content-Type", "application/json; charset=UTF-8")
70 else:
71 request = urllib.request.Request(url)
72
73 # add headers tuples
74 for header in headers:
75 request.add_header(*header)
76
77 try:
78 response = urllib.request.urlopen(request)
79 except urllib.error.HTTPError:
80 # asking for data that doesn't exist results in a 404, just return nothing
81 if allow_failure:
82 return None
83 logger.exception("Server encountered an HTTPError at URL: '%s'", url)
84 except urllib.error.URLError:
85 logger.exception("An URLError occurred at URL: '%s'", url)
86 else:
87 # docs: https://docs.python.org/3/library/json.html
88 jsondata = response.read()
89 logger.debug("API response: %s", jsondata)
90
91 # optionally remove the gerrit "magic prefix" - docs:
92 # https://gerrit-review.googlesource.com/Documentation/rest-api.html#output
93 if trim_prefix:
94 jsondata = jsondata.lstrip(b")]}'\n")
95
96 try:
97 data = json.loads(jsondata)
98 except json.decoder.JSONDecodeError:
99 # allow return of no data
100 if allow_failure:
101 return None
102 logger.exception("Unable to decode JSON")
103 else:
104 logger.debug("JSON decoded: %s", data)
105
106 return data
107
108
109def crowd_users_list(crowd_settings, groupname):
110 """
111 Returns dict of email addresses mapped to usernames from Crowd, given a
112 group name
113 """
114
115 url = "%s/rest/usermanagement/1/group/user/direct?groupname=%s&expand=user" % (
116 crowd_settings["url"],
117 groupname,
118 )
119
120 crowd_headers = [
121 basic_auth_header(crowd_settings["username"], crowd_settings["password"]),
122 ("Accept", "application/json"),
123 ]
124
125 cout = json_api_get(url, crowd_headers)
126
127 userlist = {}
128
129 for user in cout["users"]:
130 userlist[user["email"]] = user["name"]
131
132 return userlist
133
134
135def gerrit_group_id_by_name(gerrit_settings, groupname):
136 """
137 Returns a gerrit group ID given the name of a group
138 Note - this is the "id" not the "group_id" in the dict.
139 """
140
141 # read from cache if found
142 if groupname not in gerrit_groups:
143
144 gurl = "%s/groups/?m=%s" % (gerrit_settings["url"], groupname)
145 gout = json_api_get(gurl, gerrit_headers, None, True)
146
147 gerrit_groups[groupname] = gout[groupname]["id"]
148
149 logger.debug(
150 "Group: '%s' has group-id: '%s'", groupname, gerrit_groups[groupname]
151 )
152
153 return gerrit_groups[groupname]
154
155
156def gerrit_users_list(gerrit_settings, groupname):
157 """
158 Returns dict of lists of usernames and emails from Gerrit, given a group name
159 """
160
161 gid = gerrit_group_id_by_name(gerrit_settings, groupname)
162
163 gurl = "%s/groups/%s/members" % (gerrit_settings["url"], gid)
164 gout = json_api_get(gurl, gerrit_headers, None, True)
165
166 userlist = {}
167
168 for user in gout:
169 userlist[user["email"]] = {
170 "_account_id": user.get("_account_id"),
171 "username": user.get("username", None),
172 }
173
174 return userlist
175
176
177def gerrit_check_crowd_id(gerrit_settings, aid, crowdusername):
178 """
179 checks if a gerrit account has an external CrowdID identity string
180 """
181
182 gurl = "%s/accounts/%s/external_ids" % (gerrit_settings["url"], aid)
183 gout = json_api_get(gurl, gerrit_headers, None, True)
184
185 crowd_id_string = (
186 "https://crowd.opennetworking.org/openidserver/users/%s" % crowdusername
187 )
188
189 for identity in gout:
190 if identity["identity"] == crowd_id_string:
191 return aid
192
193 return None
194
195
196def gerrit_find_account_id(gerrit_settings, email, crowdusername):
197 """
198 Returns a gerrit account ID given the email address of a user and the
199 corresponding crowd username, or None if no account exists.
200 """
201
202 gurl = "%s/accounts/?q=email:%s" % (gerrit_settings["url"], email)
203 gout = json_api_get(gurl, gerrit_headers, None, True, True)
204
205 # check for users with multiple email addresses
206 if len(gout) > 1:
207 logger.warning("Email: '%s' register for more than one Gerrit account", email)
208 return None
209
210 # may not have an account, return None if no account
211 if len(gout) == 0:
212 logger.warning("Email: '%s' doesn't have a Gerrit account", email)
213 return None
214
215 aid_dict = gout[0]
216 logger.debug("Email: '%s' has account-id: '%s'", email, aid_dict["_account_id"])
217
218 return aid_dict["_account_id"]
219
220
221def gerrit_lookup_account_ids(gerrit_settings, users):
222 """
223 Returns a list of account-ids given a list of user tuples
224 """
225
226 account_ids = []
227
228 for user in users:
229 aid = gerrit_find_account_id(gerrit_settings, *user)
230
231 if aid:
232 account_ids.append(aid)
233
234 return account_ids
235
236
237def gerrit_add_accounts_to_group(gerrit_settings, groupname, account_ids):
238 """
239 Given a group name and a list of account-ids, add accounts from group
240 """
241
242 gid = gerrit_group_id_by_name(gerrit_settings, groupname)
243
244 # https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#_add_group_members
245 members = {"members": account_ids}
246
247 gurl = "%s/groups/%s/members.add" % (gerrit_settings["url"], gid)
248 gout = json_api_get(gurl, gerrit_headers, members, True)
249
250 logger.debug("output of adding accounts to group: %s", gout)
251
252
253def gerrit_remove_accounts_from_group(gerrit_settings, groupname, account_ids):
254 """
255 Given a group name and a list of account-ids, remove accounts from group
256 """
257
258 gid = gerrit_group_id_by_name(gerrit_settings, groupname)
259
260 # https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#_add_group_members
261 members = {"members": account_ids}
262
263 gurl = "%s/groups/%s/members.delete" % (gerrit_settings["url"], gid)
264 gout = json_api_get(gurl, gerrit_headers, members, True, True)
265
266 logger.debug("output of removing accounts to group: %s", gout)
267
268
269def sync_group(settings, groupname):
270 """
271 sync a group from Crowd to Gerrit
272 """
273
274 cusers = crowd_users_list(settings["crowd"], groupname)
275
276 gusers = gerrit_users_list(settings["gerrit"], groupname)
277
278 logger.info("Crowd users: %s" % cusers)
279 logger.info("Gerrit users: %s" % gusers)
280
281 # lists of users to add or remove from gerrit
282 add_g = []
283 rem_g = list(gusers.keys()) # default to removing all users
284
285 # go through list of crowd users by email
286 for cemail, cuserid in cusers.items():
287 # if a user is found, remove from rem_g list
288 if cemail in gusers:
289 rem_g.remove(cemail)
290 else:
291 add_g.append((cemail, cuserid))
292
293 logger.info("Users to add: %s" % add_g)
294 logger.info("Users to remove: %s" % rem_g)
295
296 add_aids = gerrit_lookup_account_ids(settings["gerrit"], add_g)
297
298 logger.info("Account-ids to add: %s" % add_aids)
299
300 gerrit_aids = [gusers[e]["_account_id"] for e in gusers.keys()]
301
302 logger.info("All Gerrit account-ids: %s" % gerrit_aids)
303
304 aa_nodupes = [a for a in add_aids if a not in gerrit_aids]
305
306 logger.info("Duplicates removed: %s" % aa_nodupes)
307
308 if aa_nodupes:
309 gerrit_add_accounts_to_group(settings["gerrit"], groupname, aa_nodupes)
310
311 remove_aids = [gusers[e]["_account_id"] for e in rem_g]
312
313 # user with a different primary email could be in both add and remove lists
314 rem_filtered = [a for a in remove_aids if a not in add_aids]
315
316 logger.info("Account-ids to remove: %s" % rem_filtered)
317
318 if rem_filtered:
319 gerrit_remove_accounts_from_group(settings["gerrit"], groupname, rem_filtered)
320
321
322# main function that calls other functions
323if __name__ == "__main__":
324
325 args = parse_crowdgroups_args()
326
327 # only print log messages if debugging
328 if args.debug:
329 logger.setLevel(logging.DEBUG)
330 else:
331 logger.setLevel(logging.CRITICAL)
332
333 # load settings from JSON file
334 settings = json.loads(args.settings.read())
335
336 # global, so this isn't run multiple times
337 gerrit_headers = [
338 basic_auth_header(
339 settings["gerrit"]["username"], settings["gerrit"]["password"]
340 ),
341 ]
342
343 # sync each group
344 for groupname in settings["groups"]:
345 sync_group(settings, groupname)