forked from josh/gh-audit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgh_audit.py
More file actions
1873 lines (1497 loc) · 49.2 KB
/
Copy pathgh_audit.py
File metadata and controls
1873 lines (1497 loc) · 49.2 KB
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import re
import subprocess
import tomllib
from collections.abc import Callable, Iterator
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from functools import cache
from pathlib import Path
from typing import Any, Final, Literal, NotRequired, TypedDict, cast
import click
import yaml
from github import Auth, Github, GithubException
from github.ContentFile import ContentFile
from github.Repository import Repository
logger = logging.getLogger(__name__)
def _gh_auth_token() -> str | None:
try:
p = subprocess.run(
["gh", "auth", "token"],
check=True,
capture_output=True,
encoding="utf-8",
)
return p.stdout.strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return None
class RuleParamType(click.ParamType):
name = "rule"
def convert(self, value: str, param: Any, ctx: Any) -> "Rule":
for rule in RULES:
if rule.name == value:
return rule
self.fail(f"Unknown rule: {value}", param, ctx)
_RULE_TYPE = RuleParamType()
@click.command()
@click.argument("repository", nargs=-1)
@click.option(
"--active", is_flag=True, help="Include all your non-archived repositories"
)
@click.option(
"--github-token",
envvar="GITHUB_TOKEN",
help="GitHub API token",
metavar="TOKEN",
required=True,
default=_gh_auth_token(),
)
@click.option("--verbose", is_flag=True, default=False, help="Enable debug logging")
@click.option(
"--rule",
"override_rules",
type=_RULE_TYPE,
multiple=True,
help="Specify rules to run",
)
@click.option(
"--format",
type=click.Choice(["repo", "rule"], case_sensitive=False),
default="repo",
required=True,
)
@click.version_option()
def main(
repository: list[str],
active: bool,
override_rules: tuple["Rule", ...],
format: Literal["repo", "rule"],
github_token: str,
verbose: bool,
) -> None:
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO)
rules: list[Rule] = RULES
if override_rules:
rules = list(override_rules)
logger.debug("Applying %d rules", len(rules))
global rule_message_format
if format == "repo":
rule_message_format = "{repo}: {level} {log_message} [{rule}]"
elif format == "rule":
rule_message_format = "{rule}: {level} {log_message} [{repo}]"
with Github(auth=Auth.Token(github_token)) as g:
user = g.get_user()
for name in repository:
repo = user.get_repo(name)
for rule in rules:
rule(repo=repo)
if active:
for repo in user.get_repos():
if repo.owner.login != user.login:
continue
if repo.archived or repo.fork:
continue
for rule in rules:
rule(repo=repo)
OK: Final = "OK"
SKIP: Final = "OK"
FAIL: Final = "FAIL"
RESULT = Literal["OK", "FAIL"]
rule_message_format = "{repo}: {level} {log_message} [{name}]"
@dataclass
class Rule:
name: str
log_message: str
level: Literal["error", "warning"]
check: Callable[[Repository], RESULT]
def __call__(self, repo: Repository) -> bool:
if self.check(repo) is FAIL:
if self.level == "warning":
level = "\033[33mwarn:\033[0m"
elif self.level == "error":
level = "\033[31merror:\033[0m"
formatted_message = rule_message_format.format(
rule=self.name,
repo=repo.full_name,
level=level,
log_message=self.log_message,
)
click.echo(formatted_message)
return False
return True
RULES: list[Rule] = []
def define_rule(**kwargs: Any) -> Callable[[Callable[[Repository], RESULT]], None]:
def _inner_define_rule(check: Callable[[Repository], RESULT]) -> None:
rule = Rule(check=check, **kwargs)
RULES.append(rule)
return _inner_define_rule
WorkflowStep = TypedDict(
"WorkflowStep",
{
"name": NotRequired[str],
"uses": NotRequired[str],
"run": NotRequired[str],
"with": NotRequired[dict[str, str]],
"env": NotRequired[dict[str, str]],
},
)
class WorkflowMatrixConfiguration(TypedDict):
include: NotRequired[list[str]]
exclude: NotRequired[list[str]]
class WorkflowStrategy(TypedDict):
matrix: dict[str, list[str]] | WorkflowMatrixConfiguration
WorkflowJob = TypedDict(
"WorkflowJob",
{
"runs-on": str,
"strategy": NotRequired[WorkflowStrategy],
"env": NotRequired[dict[str, str]],
"permissions": NotRequired[dict[str, str]],
"timeout-minutes": NotRequired[int],
"steps": list[WorkflowStep],
},
)
class Workflow(TypedDict):
name: str
on: str | list[str] | dict[str, Any]
permissions: NotRequired[dict[str, str]]
concurrency: NotRequired[Any]
env: NotRequired[dict[str, str]]
jobs: dict[str, WorkflowJob]
@define_rule(
name="missing-description",
log_message="Missing repository description",
level="error",
)
def _missing_description(repo: Repository) -> RESULT:
if repo.description:
return OK
return FAIL
@define_rule(
name="missing-license",
log_message="Missing license file",
level="error",
)
def _missing_license(repo: Repository) -> RESULT:
if repo.visibility == "private":
return SKIP
try:
if repo.get_license():
return OK
except GithubException:
pass
return FAIL
@define_rule(
name="non-mit-license",
log_message="Using non-MIT license",
level="warning",
)
def _non_mit_license(repo: Repository) -> RESULT:
if repo.visibility == "private":
return SKIP
if repo.license and repo.license.name != "MIT License":
return FAIL
return OK
@define_rule(
name="missing-readme",
log_message="Missing README file",
level="error",
)
def _missing_readme(repo: Repository) -> RESULT:
if _get_readme(repo):
return OK
return FAIL
@define_rule(
name="missing-agents",
log_message="Missing AGENTS.md file",
level="warning",
)
def _missing_agents(repo: Repository) -> RESULT:
if _get_contents(repo, path="AGENTS.md"):
return OK
return FAIL
@define_rule(
name="missing-topics",
log_message="Missing topics",
level="error",
)
def _missing_topics(repo: Repository) -> RESULT:
if len(repo.topics) == 0:
return FAIL
return OK
@define_rule(
name="too-few-topics",
log_message="Only one topic",
level="warning",
)
def _too_few_topics(repo: Repository) -> RESULT:
if len(repo.topics) == 1:
return FAIL
return OK
@define_rule(
name="has-issues",
log_message="Repository doesn't have Issues enabled",
level="warning",
)
def _has_issues(repo: Repository) -> RESULT:
if repo.has_issues:
return OK
return FAIL
@define_rule(
name="no-projects",
log_message="Repository has Projects enabled",
level="warning",
)
def _no_projects(repo: Repository) -> RESULT:
if repo.has_projects:
return FAIL
return OK
@define_rule(
name="no-wiki",
log_message="Repository has Wiki enabled",
level="error",
)
def _no_wiki(repo: Repository) -> RESULT:
if repo.has_wiki:
return FAIL
return OK
@define_rule(
name="no-discussions",
log_message="Repository has Discussions enabled",
level="error",
)
def _no_discussions(repo: Repository) -> RESULT:
if repo.has_discussions:
return FAIL
return OK
# Check if repo is larger than 1GB
@define_rule(
name="git-size",
log_message="Repository size is too large",
level="error",
)
def _git_size_error(repo: Repository) -> RESULT:
if repo.size > (1024 * 1024):
return FAIL
return OK
# Check if repo is larger than 50MB
@define_rule(
name="git-size",
log_message="Repository size is too large",
level="warning",
)
def _git_size_warning(repo: Repository) -> RESULT:
if repo.size > (50 * 1024):
return FAIL
return OK
def _get_readme(repo: Repository) -> ContentFile | None:
try:
return repo.get_readme()
except GithubException:
return None
def _get_contents(repo: Repository, path: str) -> ContentFile | None:
try:
contents = repo.get_contents(path=path)
except GithubException:
return None
if isinstance(contents, list):
return None
return contents
@cache
def _get_contents_text(repo: Repository, path: str) -> str:
if contents := _get_contents(repo, path=path):
return contents.decoded_content.decode("utf-8")
else:
return ""
@cache
def _ls_tree(repo: Repository) -> list[Path]:
return [Path(item.path) for item in repo.get_git_tree("HEAD", recursive=True).tree]
@cache
def _file_extnames(repo: Repository) -> set[str]:
return {path.suffix for path in _ls_tree(repo)} - {""}
@cache
def _load_pyproject(repo: Repository) -> dict[str, Any]:
logger.debug("Loading pyproject.toml for %s", repo.full_name)
contents = _get_contents(repo, path="pyproject.toml")
if not contents:
return dict()
try:
return tomllib.loads(contents.decoded_content.decode("utf-8"))
except tomllib.TOMLDecodeError:
return dict()
@define_rule(
name="missing-pyproject",
log_message="Missing pyproject.toml",
level="error",
)
def _missing_pyproject(repo: Repository) -> RESULT:
if repo.language != "Python":
return SKIP
if _load_pyproject(repo):
return OK
return FAIL
@define_rule(
name="missing-pyproject-project-name",
log_message="project.name missing in pyproject.toml",
level="error",
)
def _missing_pyproject_project_name(repo: Repository) -> RESULT:
pyproject = _load_pyproject(repo)
if not pyproject:
return SKIP
if pyproject.get("project", {}).get("name") is None:
return FAIL
return OK
def _pyproject_classifiers(repo: Repository) -> set[str]:
return set(_load_pyproject(repo).get("project", {}).get("classifiers", []))
_MIT_LICENSE_CLASSIFIER = "License :: OSI Approved :: MIT License"
@define_rule(
name="pyproject-mit-license-classifier",
log_message="License classifier missing in pyproject.toml",
level="error",
)
def _pyproject_mit_license_classifier(repo: Repository) -> RESULT:
pyproject = _load_pyproject(repo)
if not pyproject:
return SKIP
if not repo.license:
return SKIP
if repo.license.name != "MIT License":
return SKIP
if _MIT_LICENSE_CLASSIFIER in _pyproject_classifiers(repo):
return OK
return FAIL
def _pyproject_author_names(repo: Repository) -> set[str]:
names: set[str] = set()
for author in _load_pyproject(repo).get("project", {}).get("authors", []):
if name := author.get("name"):
names.add(name)
return names
def _pyproject_author_emails(repo: Repository) -> set[str]:
emails: set[str] = set()
for author in _load_pyproject(repo).get("project", {}).get("authors", []):
if email := author.get("email"):
emails.add(email)
return emails
@define_rule(
name="pyproject-omit-license",
log_message="License classifier should be omitted when using MIT License",
level="warning",
)
def _pyproject_omit_license(repo: Repository) -> RESULT:
pyproject = _load_pyproject(repo)
if not pyproject:
return SKIP
if not repo.license:
return SKIP
if repo.license.name != "MIT License":
return SKIP
if "license" in _load_pyproject(repo).get("project", {}):
return FAIL
return OK
@define_rule(
name="pyproject-author-name",
log_message="project.authors[0].name missing in pyproject.toml",
level="warn",
)
def _pyproject_author_name(repo: Repository) -> RESULT:
pyproject = _load_pyproject(repo)
if not pyproject:
return SKIP
if len(_pyproject_author_names(repo)) == 0:
return FAIL
return OK
@define_rule(
name="pyproject-omit-author-email",
log_message="project.authors[0].email should be omitted for privacy",
level="warning",
)
def _pyproject_omit_author_email(repo: Repository) -> RESULT:
pyproject = _load_pyproject(repo)
if not pyproject:
return SKIP
if len(_pyproject_author_emails(repo)) > 0:
return FAIL
return OK
@define_rule(
name="pyproject-readme",
log_message="project.readme missing in pyproject.toml",
level="error",
)
def _pyproject_readme(repo: Repository) -> RESULT:
pyproject = _load_pyproject(repo)
if not pyproject:
return SKIP
if pyproject.get("project", {}).get("readme") is None:
return FAIL
return OK
def _pyproject_requires_python(repo: Repository) -> str:
return cast(
str, _load_pyproject(repo).get("project", {}).get("requires-python", "")
)
@define_rule(
name="missing-pyproject-requires-python",
log_message="project.requires-python missing in pyproject.toml",
level="error",
)
def _missing_pyproject_requires_python(repo: Repository) -> RESULT:
pyproject = _load_pyproject(repo)
if not pyproject:
return SKIP
if _pyproject_requires_python(repo):
return OK
return FAIL
@cache
def _pyproject_all_dependencies(repo: Repository) -> set[str]:
deps: set[str] = set()
project = _load_pyproject(repo).get("project", {})
for dep in project.get("dependencies", []):
deps.add(dep)
for extra_deps in project.get("optional-dependencies", {}).values():
for dep in extra_deps:
deps.add(dep)
return deps
def _pydep_has_lower_bound(dep: str) -> bool:
return "==" in dep or ">" in dep or "~=" in dep or "@" in dep
@define_rule(
name="pyproject-dependency-lower-bound",
log_message="Dependencies should have lower bound",
level="error",
)
def _pyproject_dependency_lower_bound(repo: Repository) -> RESULT:
pyproject = _load_pyproject(repo)
if not pyproject:
return SKIP
for dep in _pyproject_all_dependencies(repo):
if not _pydep_has_lower_bound(dep):
return FAIL
return OK
@define_rule(
name="pyproject-optional-dependencies-name",
log_message="pyproject optional-dependencies should be named 'dev'",
level="warning",
)
def _project_optional_dependencies_name(repo: Repository) -> RESULT:
pyproject = _load_pyproject(repo)
if not pyproject:
return SKIP
deps = pyproject.get("project", {}).get("optional-dependencies", {})
if not deps:
return OK
if list(deps.keys()) != ["dev"]:
return FAIL
return OK
@define_rule(
name="pyproject-depends-on-requests",
log_message="Avoid requests dependency",
level="warning",
)
def _pyproject_depends_on_requests(repo: Repository) -> RESULT:
pyproject = _load_pyproject(repo)
if not pyproject:
return SKIP
for dep in _pyproject_all_dependencies(repo):
if dep.startswith("requests"):
return FAIL
return OK
@cache
def _ruff_extend_select(repo: Repository) -> list[str]:
return cast(
list[str],
_load_pyproject(repo)
.get("tool", {})
.get("ruff", {})
.get("lint", {})
.get("extend-select", []),
)
@define_rule(
name="missing-pyproject-ruff-isort-rules",
log_message="tool.ruff.lint.extend-select missing 'I' to enable isort rules",
level="error",
)
def _missing_pyproject_ruff_isort_rules(repo: Repository) -> RESULT:
pyproject = _load_pyproject(repo)
if not pyproject:
return SKIP
if "I" in _ruff_extend_select(repo):
return OK
return FAIL
@define_rule(
name="missing-pyproject-ruff-pyupgrade-rules",
log_message="tool.ruff.lint.extend-select missing 'UP' to enable pyupgrade rules",
level="error",
)
def _missing_pyproject_ruff_pyupgrade_rules(repo: Repository) -> RESULT:
pyproject = _load_pyproject(repo)
if not pyproject:
return SKIP
if "UP" in _ruff_extend_select(repo):
return OK
return FAIL
def _mypy_strict(repo: Repository) -> bool | None:
return cast(
bool | None,
_load_pyproject(repo).get("tool", {}).get("mypy", {}).get("strict"),
)
@define_rule(
name="mypy-strict-declared",
log_message="mypy strict mode is not declared",
level="error",
)
def _mypy_strict_declared(repo: Repository) -> RESULT:
pyproject = _load_pyproject(repo)
if not pyproject:
return SKIP
if _mypy_strict(repo) is None:
return FAIL
return OK
@define_rule(
name="mypy-strict",
log_message="mypy strict mode is not enabled",
level="warning",
)
def _mypy_strict_enabled(repo: Repository) -> RESULT:
pyproject = _load_pyproject(repo)
if not pyproject:
return SKIP
if _mypy_strict(repo) is False:
return FAIL
return OK
@define_rule(
name="requirements-txt-exact",
log_message="Use exact versions in requirements.txt",
level="error",
)
def _requirements_txt_exact(repo: Repository) -> RESULT:
if not _has_requirements_txt(repo):
return SKIP
if _requirements_txt_is_exact(repo) is False:
return FAIL
return OK
@define_rule(
name="requirements-txt-uv-compiled",
log_message="requirements.txt is not compiled by uv",
level="warning",
)
def _requirements_txt_uv_compiled(repo: Repository) -> RESULT:
if not _has_requirements_txt(repo):
return SKIP
if "uv pip compile" in _requirements_txt(repo):
return OK
return FAIL
@define_rule(
name="prefer-uv-lock",
log_message="Prefer uv.lock instead of requirements.txt",
level="warning",
)
def _prefer_uv_lock(repo: Repository) -> RESULT:
if not _has_requirements_txt(repo):
return SKIP
if _has_uv_lock(repo):
return OK
return FAIL
@cache
def _has_requirements_txt(repo: Repository) -> bool:
if _get_contents(repo, path="requirements.txt"):
return True
return False
@cache
def _has_uv_lock(repo: Repository) -> bool:
if _get_contents(repo, path="uv.lock"):
return True
return False
@cache
def _requirements_txt(repo: Repository) -> str:
return _get_contents_text(repo, path="requirements.txt")
@cache
def _requirements_txt_is_exact(repo: Repository) -> bool:
if text := _requirements_txt(repo):
for line in text.splitlines():
if line.lstrip().startswith("#"):
continue
if "@" in line:
continue
if "==" not in line:
return False
return True
else:
return True
@cache
def _requirements_txt_has_types(repo: Repository) -> bool:
if text := _requirements_txt(repo):
for line in text.splitlines():
if line.lstrip().startswith("#"):
continue
if "types-" in line:
return True
return False
else:
return False
@cache
def _requirements_txt_has_ruff(repo: Repository) -> bool:
if text := _requirements_txt(repo):
for line in text.splitlines():
if line.lstrip().startswith("#"):
continue
if "ruff==" in line:
return True
return False
@cache
def _dependabot_config(repo: Repository) -> dict[str, Any]:
logger.debug("Loading .github/dependabot.yml for %s", repo.full_name)
contents = _get_contents(repo, path=".github/dependabot.yml")
if not contents:
return dict()
try:
return cast(
dict[str, Any],
yaml.safe_load(contents.decoded_content.decode("utf-8")),
)
except yaml.YAMLError:
return dict()
def _dependabot_update_schedule_intervals(repo: Repository) -> set[str]:
return {
update.get("schedule", {}).get("interval")
for update in _dependabot_config(repo).get("updates", [])
}
@define_rule(
name="delete-branch-on-merge",
log_message="Repository should delete branches on merge",
level="error",
)
def _delete_branch_on_merge(repo: Repository) -> RESULT:
if repo.delete_branch_on_merge:
return OK
return FAIL
@define_rule(
name="allow-auto-merge",
log_message="Repository should allow auto-merge",
level="warning",
)
def _auto_merge(repo: Repository) -> RESULT:
if repo.fork:
return SKIP
if not _dependabot_config(repo):
return SKIP
if repo.allow_auto_merge:
return OK
return FAIL
@define_rule(
name="dependabot-auto-merge",
log_message="Set up Dependabot auto-merge",
level="warning",
)
def _dependabot_auto_merge(repo: Repository) -> RESULT:
if repo.fork:
return SKIP
if not _dependabot_config(repo):
return SKIP
if not _get_contents(repo, path=".github/workflows/merge.yml"):
return FAIL
return OK
@define_rule(
name="enable-merge-commit",
log_message="Repository should allow merge commits",
level="warning",
)
def _enable_merge_commit(repo: Repository) -> RESULT:
if repo.allow_merge_commit:
return OK
return FAIL
@define_rule(
name="dependabot-schedule-weekly",
log_message="Dependabot should be scheduled weekly",
level="warning",
)
def _dependabot_schedule_weekly(repo: Repository) -> RESULT:
if not _dependabot_config(repo):
return SKIP
if _dependabot_update_schedule_intervals(repo) != {"weekly"}:
return FAIL
return OK
@define_rule(
name="pip-dependabot",
log_message="Dependabot should be enabled for pip ecosystem",
level="error",
)
def _pip_dependabot(repo: Repository) -> RESULT:
if not _has_requirements_txt(repo):
return SKIP
for update in _dependabot_config(repo).get("updates", []):
if update.get("package-ecosystem") == "pip":
return OK
return FAIL
@define_rule(
name="pip-dependabot-ignore-types",
log_message="Dependabot should ignore types-* packages",
level="warning",
)
def _dependabot_ignores_pip_types(repo: Repository) -> RESULT:
if not _has_requirements_txt(repo):
return SKIP
if not _requirements_txt_has_types(repo):
return SKIP
for update in _dependabot_config(repo).get("updates", []):
if update.get("package-ecosystem") == "pip":
for ignored in update.get("ignore", []):
if ignored.get("dependency-name") == "types-*":
return OK
return FAIL
@define_rule(
name="pip-dependabot-ignore-ruff-patches",
log_message="Dependabot should ignore ruff patches",
level="warning",
)
def _dependabot_ignores_ruff_patches(repo: Repository) -> RESULT:
if not _has_requirements_txt(repo):
return SKIP
if not _requirements_txt_has_ruff(repo):
return SKIP
for update in _dependabot_config(repo).get("updates", []):
if update.get("package-ecosystem") == "pip":
for ignored in update.get("ignore", []):
if ignored.get("dependency-name") == "ruff":
return OK
return FAIL
@define_rule(
name="disable-actions",
log_message="Repository without workflows should disable Actions",
level="error",
)
def _disable_actions(repo: Repository) -> RESULT:
if _get_workflow_paths(repo):
return SKIP
permissions = _get_actions_permissions(repo)
if permissions["enabled"]:
return FAIL
else:
return OK
@define_rule(
name="disable-all-actions",
log_message="Repository should not allow all actions",
level="warning",
)
def _actions_allowed_actions_all(repo: Repository) -> RESULT:
if repo.visibility == "private":
return SKIP
permissions = _get_actions_permissions(repo)
if permissions["enabled"] is False:
return SKIP
allowed_actions = permissions.get("allowed_actions")
if allowed_actions == "all":
return FAIL
return OK
@define_rule(
name="allow-github-owned-actions",
log_message="Repository allow actions created by GitHub",
level="error",
)
def _actions_github_owned_allowed(repo: Repository) -> RESULT:
if not _workflow_step_uses(repo, re.compile("actions/")):
return SKIP
permissions = _get_actions_permissions(repo)
if permissions["enabled"] is False:
return SKIP
elif permissions.get("allowed_actions") == "all":
return OK
elif permissions.get("allowed_actions") == "local_only":
return FAIL
elif permissions.get("allowed_actions") == "selected":
selected_actions = _get_repo_actions_selected_actions(repo)
if selected_actions["github_owned_allowed"]:
return OK
else:
return FAIL
else:
return OK
def _allow_org_owned_actions(repo: Repository, trusted_org: str) -> RESULT:
org_pattern = re.compile(f"{trusted_org}/")