forked from 3rd-party-integrations/github-team-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
402 lines (358 loc) · 12.6 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import atexit
from operator import truediv
import os
import time
import json
import github3
from distutils.util import strtobool
import threading
import sys
import traceback
from concurrent.futures import ThreadPoolExecutor
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from flask import Flask
from githubapp import (
GitHubApp,
DirectoryClient,
CRON_INTERVAL,
TEST_MODE,
ADD_MEMBER,
REMOVE_ORG_MEMBERS_WITHOUT_TEAM,
USER_SYNC_ATTRIBUTE,
SYNCMAP_ONLY,
)
app = Flask(__name__)
github_app = GitHubApp(app)
# Schedule a full sync
scheduler = BackgroundScheduler(daemon=True)
scheduler.start()
atexit.register(lambda: scheduler.shutdown(wait=False))
@github_app.on("team.created")
def sync_new_team():
"""
Sync a new team when it is created
:return:
"""
owner = github_app.payload["organization"]["login"]
team_id = github_app.payload["team"]["id"]
if os.environ["USER_DIRECTORY"].upper() == "AAD":
# Azure APIs don't currently support case insensitive searching
slug = github_app.payload["team"]["name"].replace(" ", "-")
else:
slug = github_app.payload["team"]["slug"]
client = github_app.installation_client
sync_team(client=client, owner=owner, team_id=team_id, slug=slug)
def sync_team(client=None, owner=None, team_id=None, slug=None):
"""
Prepare the team sync
:param client:
:param owner:
:param team_id:
:param slug:
:return:
"""
print("-------------------------------")
print(f"Processing Team: {slug}")
try:
org = client.organization(owner)
team = org.team(team_id)
custom_map, group_prefix, ignore_users = load_custom_map()
try:
directory_group = get_directory_from_slug(slug, custom_map, org)
# If we're filtering on group prefix, skip if the group doesn't match
if len(group_prefix) > 0 and not directory_group.startswith(
tuple(group_prefix)
):
print(f"skipping team {team.slug} - not in group prefix")
return
directory_members = directory_group_members(group=directory_group)
except Exception as e:
directory_members = []
traceback.print_exc(file=sys.stderr)
team_members = github_team_members(
client=client,
owner=owner,
team_id=team_id,
attribute=USER_SYNC_ATTRIBUTE,
ignore_users=ignore_users,
)
compare = compare_members(
group=directory_members, team=team_members, attribute=USER_SYNC_ATTRIBUTE
)
if TEST_MODE:
print(f"TEST_MODE: Pending changes for team {team.slug}:")
print(json.dumps(compare, indent=2))
else:
try:
execute_sync(org=org, team=team, slug=slug, state=compare)
except (AssertionError, ValueError) as e:
if strtobool(os.environ["OPEN_ISSUE_ON_FAILURE"]):
open_issue(client=client, slug=slug, message=e)
raise Exception(f"Team {team.slug} sync failed: {e}")
print(f"Processing Team Successful: {team.slug}")
except Exception:
traceback.print_exc(file=sys.stderr)
raise
def directory_group_members(group=None):
"""
Look up members of a group in your user directory
:param group: The name of the group to query in your directory server
:type group: str
:return: group_members
:rtype: list
"""
try:
directory = DirectoryClient()
members = directory.get_group_members(group_name=group)
group_members = [member for member in members]
except Exception as e:
group_members = []
traceback.print_exc(file=sys.stderr)
return group_members
def github_team_info(client=None, owner=None, team_id=None):
"""
Look up team info in GitHub
:param client:
:param owner:
:param team_id:
:return:
"""
org = client.organization(owner)
return org.team(team_id)
def github_team_members(
client=None, owner=None, team_id=None, attribute="username", ignore_users=[]
):
"""
Look up members of a given team in GitHub
:param client:
:param owner:
:param team_id:
:param attribute:
:type owner: str
:type team_id: int
:type attribute: str
:return: team_members
:rtype: list
"""
team_members = []
team = github_team_info(client=client, owner=owner, team_id=team_id)
if attribute == "email":
for m in team.members():
user = client.user(m.login)
team_members.append(
{
"username": str(user.login),
"email": str(user.email),
}
)
else:
for member in team.members():
team_members.append({"username": str(member), "email": ""})
return [m for m in team_members if m["username"] not in ignore_users]
def compare_members(group, team, attribute="username"):
"""
Compare users in GitHub and the User Directory to see which users need to be added or removed
:param group:
:param team:
:param attribute:
:return: sync_state
:rtype: dict
"""
directory_list = [x[attribute].casefold() for x in group]
github_list = [x[attribute].casefold() for x in team]
add_users = list(set(directory_list) - set(github_list))
remove_users = list(set(github_list) - set(directory_list))
sync_state = {
"directory": group,
"github": team,
"action": {"add": add_users, "remove": remove_users},
}
return sync_state
def execute_sync(org, team, slug, state):
"""
Perform the synchronization
:param org:
:param team:
:param slug:
:param state:
:return:
"""
total_changes = len(state["action"]["remove"]) + len(state["action"]["add"])
if len(state["directory"]) == 0:
message = f"{os.environ.get('USER_DIRECTORY', 'LDAP').upper()} group returned empty: {slug}"
raise ValueError(message)
elif int(total_changes) > int(os.environ.get("CHANGE_THRESHOLD", 25)):
message = "Skipping sync for {}.<br>".format(slug)
message += "Total number of changes ({}) would exceed the change threshold ({}).".format(
str(total_changes), str(os.environ.get("CHANGE_THRESHOLD", 25))
)
message += "<br>Please investigate this change and increase your threshold if this is accurate."
raise AssertionError(message)
else:
for user in state["action"]["add"]:
# Validate that user is in org
if org.is_member(user) or ADD_MEMBER:
try:
print(f"Adding {user} to {slug}")
team.add_or_update_membership(user)
except github3.exceptions.NotFoundError:
print(f"User: {user} not found")
pass
else:
print(f"Skipping {user} as they are not part of the org")
for user in state["action"]["remove"]:
print(f"Removing {user} from {slug}")
team.revoke_membership(user)
def open_issue(client, slug, message):
"""
Open an issue with the failed sync details
:param client: Our installation client
:param slug: Team slug
:param message: Error message to detail
:return:
"""
repo_for_issues = os.environ["REPO_FOR_ISSUES"]
owner = repo_for_issues.split("/")[0]
repository = repo_for_issues.split("/")[1]
assignee = os.environ["ISSUE_ASSIGNEE"]
client.create_issue(
owner=owner,
repository=repository,
assignee=assignee,
title="Team sync failed for @{}/{}".format(owner, slug),
body=str(message),
)
def load_custom_map(file="syncmap.yml"):
"""
Custom team synchronization
:param file:
:return:
"""
syncmap = {}
ignore_users = []
if os.path.isfile(file):
from yaml import load, Loader
with open(file, "r") as f:
data = load(f, Loader=Loader)
for d in data["mapping"]:
if "org" in d:
syncmap[(d["org"], d["github"])] = d["directory"]
else:
syncmap[d["github"]] = d["directory"]
group_prefix = data.get("group_prefix", [])
ignore_users = data.get("ignore_users", [])
return (syncmap, group_prefix, ignore_users)
def get_app_installations():
"""
Get a list of installations for this app
:return:
"""
with app.app_context() as ctx:
try:
c = ctx.push()
gh = GitHubApp(c)
installations = gh.app_client.app_installations
finally:
ctx.pop()
return installations
@scheduler.scheduled_job(
trigger=CronTrigger.from_crontab(CRON_INTERVAL), id="sync_all_teams"
)
def sync_all_teams():
"""
Lookup teams in a GitHub org and synchronize all teams with your user directory
:return:
"""
print(f'Syncing all teams: {time.strftime("%A, %d. %B %Y %I:%M:%S %p")}')
installations = get_app_installations()
custom_map, _ = load_custom_map()
futures = []
install_count = 0
with ThreadPoolExecutor(max_workers=10) as exe:
for i in installations():
install_count += 1
print("========================================================")
print(f"## Processing Organization: {i.account['login']}")
print("========================================================")
with app.app_context() as ctx:
try:
gh = GitHubApp(ctx.push())
client = gh.app_installation(installation_id=i.id)
org = client.organization(i.account["login"])
for team in org.teams():
futures.append(
exe.submit(sync_team_helper, team, custom_map, client, org)
)
except Exception as e:
print(f"DEBUG: {e}")
finally:
ctx.pop()
if not install_count:
raise Exception(f"No installation defined for APP_ID {os.getenv('APP_ID')}")
for future in futures:
future.result()
if REMOVE_ORG_MEMBERS_WITHOUT_TEAM:
remove_org_members_without_team(installations)
print(f'Syncing all teams successful: {time.strftime("%A, %d. %B %Y %I:%M:%S %p")}')
def remove_org_members_without_team(installations):
for i in installations():
with app.app_context() as ctx:
try:
gh = GitHubApp(ctx.push())
client = gh.app_installation(installation_id=i.id)
org = client.organization(i.account["login"])
org_members = [member for member in org.members()]
team_members = [
member for team in org.teams() for member in team.members()
]
remove_members = list(set(org_members) - set(team_members))
for member in remove_members:
print(f"Removing {member}")
if not TEST_MODE:
org.remove_membership(str(member))
except Exception as e:
print(f"DEBUG: {e}")
finally:
ctx.pop()
def sync_team_helper(team, custom_map, client, org):
print(f"Organization: {org.login}")
try:
if SYNCMAP_ONLY and not is_team_in_map(team.slug, custom_map, org):
print(f"skipping team {team.slug} - not in sync map")
return
sync_team(
client=client,
owner=org.login,
team_id=team.id,
slug=team.slug,
)
except Exception as e:
print(f"Organization: {org.login}")
print(f"Unable to sync team: {team.slug}")
print(f"DEBUG: {e}")
def is_team_in_map(slug, custom_map, org):
key_with_org = (org.login, slug)
key_without_org = slug
if key_with_org in custom_map or key_without_org in custom_map:
return True
else:
return False
def get_directory_from_slug(slug, custom_map, org):
if not is_team_in_map(slug, custom_map, org):
return slug
elif (org.login, slug) in custom_map:
return custom_map[(org.login, slug)]
elif slug in custom_map:
return custom_map[slug]
if "FLASK_APP" in os.environ:
thread = threading.Thread(target=sync_all_teams)
thread.start()
if __name__ == "__main__":
if "FLASK_APP" in os.environ:
app.run(
host=os.environ.get("FLASK_RUN_HOST", "0.0.0.0"),
port=os.environ.get("FLASK_RUN_PORT", "5000"),
)
else:
sync_all_teams()