-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathallowlist.py
430 lines (373 loc) · 14.8 KB
/
allowlist.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
import logging
from typing import Any, Iterable, Optional, Union, Callable, List, Tuple, Dict, Type
from fasjson_client import Client
from fasjson_client.errors import APIError
from ogr.abstract import GitProject
from packit.api import PackitAPI
from packit.config.job_config import JobConfig, JobType
from packit.exceptions import PackitException, PackitCommandFailedError
from packit_service.config import ServiceConfig
from packit_service.constants import (
FASJSON_URL,
NAMESPACE_NOT_ALLOWED_MARKDOWN_DESCRIPTION,
NAMESPACE_NOT_ALLOWED_MARKDOWN_ISSUE_INSTRUCTIONS,
NOTIFICATION_REPO,
DOCS_APPROVAL_URL,
)
from packit_service.models import AllowlistModel, AllowlistStatus
from packit_service.worker.events import (
EventData,
AbstractCoprBuildEvent,
InstallationEvent,
IssueCommentEvent,
IssueCommentGitlabEvent,
KojiTaskEvent,
MergeRequestCommentGitlabEvent,
MergeRequestGitlabEvent,
PullRequestCommentGithubEvent,
PullRequestCommentPagureEvent,
PullRequestGithubEvent,
PullRequestPagureEvent,
PushGitHubEvent,
PushGitlabEvent,
PushPagureEvent,
ReleaseEvent,
TestingFarmResultsEvent,
CheckRerunEvent,
)
from packit_service.worker.events.gitlab import ReleaseGitlabEvent
from packit_service.worker.events.koji import KojiBuildEvent
from packit_service.worker.events.new_hotness import NewHotnessUpdateEvent
from packit_service.worker.helpers.build import CoprBuildJobHelper
from packit_service.worker.helpers.testing_farm import TestingFarmJobHelper
from packit_service.worker.reporting import BaseCommitStatus
logger = logging.getLogger(__name__)
UncheckedEvent = Union[
PushPagureEvent,
PullRequestPagureEvent,
PullRequestCommentPagureEvent,
AbstractCoprBuildEvent,
TestingFarmResultsEvent,
InstallationEvent,
KojiTaskEvent,
KojiBuildEvent,
CheckRerunEvent,
NewHotnessUpdateEvent,
]
class Allowlist:
def __init__(self, service_config: ServiceConfig):
self.service_config = service_config
@staticmethod
def _strip_protocol_and_add_git(url: Optional[str]) -> Optional[str]:
"""
Remove the protocol from the URL and add .git suffix.
Args:
url (Optional[str]): URL to remove protocol from and add .git suffix to.
Returns:
URL without the protocol with added .git suffix. If not given URL returns
None.
"""
if not url:
return None
return url.split("://")[1] + ".git"
def init_kerberos_ticket(self):
"""
Try to init kerberos ticket.
Returns:
Whether the initialisation was successful.
"""
try:
logger.debug("Initialising Kerberos ticket so that we can use fasjson API.")
PackitAPI(
config=self.service_config, package_config=None
).init_kerberos_ticket()
except PackitCommandFailedError as ex:
msg = f"Kerberos authentication error: {ex.stderr_output}"
logger.error(msg)
return False
return True
def is_github_username_from_fas_account_matching(self, fas_account, sender_login):
"""
Compares the Github username from the FAS account
to the username of the one who triggered the installation.
Args:
fas_account: FAS account for which we will get the account info.
sender_login: Login of the user that will be checked for be match
against info from FAS.
Returns:
True if there was a match found. False if we were not able to run kinit or
the check for match was not successful.
"""
if not self.init_kerberos_ticket():
return False
logger.info(
f"Going to check match for Github username from FAS account {fas_account} and"
f" Github account {sender_login}."
)
client = Client(FASJSON_URL)
try:
user_info = client.get_user(username=fas_account).result
# e.g. User not found
except APIError as e:
logger.debug(f"We were not able to get the user: {e}")
return False
is_private = user_info.get("is_private")
if is_private:
logger.debug("The account is private.")
return False
github_username = user_info.get("github_username")
if github_username:
logger.debug(
f"github_username from FAS account {fas_account}: {github_username}"
)
return github_username == sender_login
logger.debug("github_username not set.")
return False
@staticmethod
def approve_namespace(namespace: str):
"""
Approve namespace manually.
Args:
namespace (str): Namespace in the format of `github.com/namespace` or
`github.com/namespace/repository.git`.
"""
AllowlistModel.add_namespace(
namespace=namespace, status=AllowlistStatus.approved_manually.value
)
logger.info(f"Account {namespace!r} approved successfully.")
@staticmethod
def is_approved(namespace: str) -> bool:
"""
Checks if namespace is approved in the allowlist.
Args:
namespace (str): Namespace in format `example.com/namespace/repository.git`,
where `/repository.git` is optional.
Returns:
`True` if namespace is approved, `False` otherwise.
"""
if not namespace:
return False
separated_path = [namespace, None]
while len(separated_path) > 1:
if matching_namespace := AllowlistModel.get_namespace(separated_path[0]):
status = AllowlistStatus(matching_namespace.status)
if status != AllowlistStatus.waiting:
return status in (
AllowlistStatus.approved_automatically,
AllowlistStatus.approved_manually,
)
separated_path = separated_path[0].rsplit("/", 1)
logger.info(f"Could not find entry for: {namespace}")
return False
@staticmethod
def remove_namespace(namespace: str) -> bool:
"""
Remove namespace from the allowlist.
Args:
namespace (str): Namespace to be removed in format of `github.com/namespace`
or `github.com/namespace/repository.git` if for specific repository.
Returns:
`True` if the namespace was in the allowlist before, `False` otherwise.
"""
if not AllowlistModel.get_namespace(namespace):
logger.info(f"Namespace {namespace!r} does not exist!")
return False
AllowlistModel.remove_namespace(namespace)
logger.info(f"Namespace {namespace!r} removed from allowlist!")
return True
@staticmethod
def waiting_namespaces() -> List[str]:
"""
Get namespaces waiting for approval.
Returns:
List of namespaces that are waiting for approval.
"""
return [
account.namespace
for account in AllowlistModel.get_namespaces_by_status(
AllowlistStatus.waiting.value
)
]
def _check_unchecked_event(
self,
event: UncheckedEvent,
project: GitProject,
job_configs: Iterable[JobConfig],
) -> bool:
# Allowlist checks do not apply to CentOS (Pagure, GitLab) and distgit commit event.
logger.info(f"{type(event)} event does not require allowlist checks.")
return True
def _check_release_push_event(
self,
event: Union[ReleaseEvent, PushGitHubEvent, PushGitlabEvent],
project: GitProject,
job_configs: Iterable[JobConfig],
) -> bool:
# TODO: modify event hierarchy so we can use some abstract classes instead
project_url = self._strip_protocol_and_add_git(event.project_url)
if not project_url:
raise KeyError(f"Failed to get namespace from {type(event)!r}")
if self.is_approved(project_url):
return True
logger.info("Refusing release event on not allowlisted repo namespace.")
return False
def _check_pr_event(
self,
event: Union[
PullRequestGithubEvent,
PullRequestCommentGithubEvent,
MergeRequestGitlabEvent,
MergeRequestCommentGitlabEvent,
],
project: GitProject,
job_configs: Iterable[JobConfig],
) -> bool:
actor_name = event.actor
if not actor_name:
raise KeyError(f"Failed to get login of the actor from {type(event)}")
project_url = self._strip_protocol_and_add_git(event.project_url)
namespace_approved = self.is_approved(project_url)
user_approved = (
project.can_merge_pr(actor_name)
or project.get_pr(event.pr_id).author == actor_name
)
if namespace_approved and user_approved:
# TODO: clear failing check when present
return True
msg = (
f"Project {project_url} is not on our allowlist! "
"See https://packit.dev/docs/guide/#2-approval"
if not namespace_approved
else f"Account {actor_name} has no write access nor is author of PR!"
)
logger.debug(msg)
if isinstance(
event, (PullRequestCommentGithubEvent, MergeRequestCommentGitlabEvent)
):
project.get_pr(event.pr_id).comment(msg)
else:
for job_config in job_configs:
job_helper_kls: Type[Union[TestingFarmJobHelper, CoprBuildJobHelper]]
if job_config.type == JobType.tests:
job_helper_kls = TestingFarmJobHelper
else:
job_helper_kls = CoprBuildJobHelper
job_helper = job_helper_kls(
service_config=self.service_config,
package_config=event.get_package_config(),
project=project,
metadata=EventData.from_event_dict(event.get_dict()),
db_trigger=event.db_trigger,
job_config=job_config,
build_targets_override=event.build_targets_override,
tests_targets_override=event.tests_targets_override,
)
msg = (
f"{project.service.hostname}/{project.namespace} not allowed!"
if not namespace_approved
else "User cannot trigger!"
)
issue_url = self.get_approval_issue(namespace=project.namespace)
job_helper.report_status_to_configured_job(
description=msg,
state=BaseCommitStatus.neutral,
url=issue_url or DOCS_APPROVAL_URL,
markdown_content=NAMESPACE_NOT_ALLOWED_MARKDOWN_DESCRIPTION.format(
instructions=NAMESPACE_NOT_ALLOWED_MARKDOWN_ISSUE_INSTRUCTIONS.format(
issue_url=issue_url
)
if issue_url
else ""
),
)
return False
def _check_issue_comment_event(
self,
event: Union[IssueCommentEvent, IssueCommentGitlabEvent],
project: GitProject,
job_configs: Iterable[JobConfig],
) -> bool:
actor_name = event.actor
if not actor_name:
raise KeyError(f"Failed to get login of the actor from {type(event)}")
project_url = self._strip_protocol_and_add_git(event.project_url)
namespace_approved = self.is_approved(project_url)
user_approved = project.can_merge_pr(actor_name)
if namespace_approved and user_approved:
return True
msg = (
f"Project {project_url} is not on our allowlist! "
"See https://packit.dev/docs/guide/#2-approval"
if not namespace_approved
else f"Account {actor_name} has no write access!"
)
logger.debug(msg)
project.get_issue(event.issue_id).comment(msg)
return False
def check_and_report(
self,
event: Optional[Any],
project: GitProject,
job_configs: Iterable[JobConfig],
) -> bool:
"""
Check if account is approved and report status back in case of PR
:param event: PullRequest and Release TODO: handle more
:param project: GitProject
:param job_configs: iterable of jobconfigs - so we know how to update status of the PR
:return:
"""
CALLBACKS: Dict[
Union[type, Tuple[Union[type, Tuple[Any, ...]], ...]], Callable
] = {
( # events that are not checked against allowlist
PushPagureEvent,
PullRequestPagureEvent,
PullRequestCommentPagureEvent,
AbstractCoprBuildEvent,
TestingFarmResultsEvent,
InstallationEvent,
KojiTaskEvent,
KojiBuildEvent,
CheckRerunEvent,
NewHotnessUpdateEvent,
): self._check_unchecked_event,
(
ReleaseEvent,
ReleaseGitlabEvent,
PushGitHubEvent,
PushGitlabEvent,
): self._check_release_push_event,
(
PullRequestGithubEvent,
PullRequestCommentGithubEvent,
MergeRequestGitlabEvent,
MergeRequestCommentGitlabEvent,
): self._check_pr_event,
(
IssueCommentEvent,
IssueCommentGitlabEvent,
): self._check_issue_comment_event,
}
# Administrators
user_login = getattr( # some old events with user_login can still be there
event, "user_login", None
) or getattr(event, "actor", None)
if user_login and user_login in self.service_config.admins:
logger.info(f"{user_login} is admin, you shall pass.")
return True
for related_events, callback in CALLBACKS.items():
if isinstance(event, related_events):
return callback(event, project, job_configs)
msg = f"Failed to validate account: Unrecognized event type {type(event)!r}."
logger.error(msg)
raise PackitException(msg)
def get_approval_issue(self, namespace) -> Optional[str]:
for issue in self.service_config.get_project(
url=NOTIFICATION_REPO
).get_issue_list(author=self.service_config.get_github_account_name()):
if issue.title.strip().endswith(f" {namespace} needs to be approved."):
return issue.url
return None