Repository navigation
Expand file tree
/
Copy pathcheck-dependency-security.py
More file actions
2428 lines (2321 loc) · 115 KB
/
Copy pathcheck-dependency-security.py
File metadata and controls
2428 lines (2321 loc) · 115 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
from __future__ import annotations
import io
import os
import re
import ast
import pathlib
import tokenize
import importlib
import subprocess
from typing import Any, TypeAlias, cast
MarkerClause: TypeAlias = tuple[str, str, str]
MarkerContext: TypeAlias = tuple[MarkerClause, ...]
StableRelease: TypeAlias = tuple[int, tuple[int, ...], int]
PublishedBound: TypeAlias = tuple[str, int, tuple[int, ...], int, bool]
DependencyContext: TypeAlias = tuple[str, str, tuple[str, ...], MarkerContext]
RequirementSource: TypeAlias = tuple[str, str, tuple[str, ...], str]
RequirementMap: TypeAlias = dict[str, set[str]]
ContextRequirements: TypeAlias = dict[DependencyContext, set[str]]
ContextsByName: TypeAlias = dict[str, ContextRequirements]
ContextReplacements: TypeAlias = dict[DependencyContext, ContextRequirements]
ResolutionDomains: TypeAlias = dict[MarkerContext, set[str]]
ResolutionsByName: TypeAlias = dict[str, ResolutionDomains]
tomllib: Any = importlib.import_module("tomllib")
base = os.environ.get("BASE_SHA", "")
if not re.fullmatch(r"[0-9a-f]{40}", base):
raise SystemExit("Untrusted security-update base commit")
origin = subprocess.check_output(["git", "remote", "get-url", "origin"], text=True).strip()
if origin not in {
"https://github.com/openai/openai-python",
"https://github.com/openai/openai-python.git",
"git@github.com:openai/openai-python.git",
"ssh://git@github.com/openai/openai-python.git",
}:
raise SystemExit("Untrusted security-update comparison origin")
subprocess.run(["git", "fetch", "--no-tags", "--depth=1", "origin", base], check=True)
def read_base(path: str) -> dict[str, Any]:
return cast(dict[str, Any], tomllib.loads(subprocess.check_output(["git", "show", base + ":" + path], text=True)))
def canonical(name: str) -> str:
return re.sub(r"[-_.]+", "-", name).lower()
def parse_marker_expression(marker: str) -> ast.expr:
tokens = list(tokenize.generate_tokens(io.StringIO(marker).readline))
lines = marker.splitlines(keepends=True)
offsets = [0]
for line in lines:
offsets.append(offsets[-1] + len(line))
replacements: list[tuple[int, int, str]] = []
for index, token in enumerate(tokens):
if token.type == tokenize.NAME and token.string == "is":
raise ValueError("Unsupported Python security dependency marker operator")
if token.type != tokenize.OP or index + 1 == len(tokens):
continue
following = tokens[index + 1]
if following.type != tokenize.OP or token.end != following.start or following.string != "=":
continue
if token.string == "~":
replacement = "is"
elif token.string == "==":
replacement = "is not"
else:
continue
start = offsets[token.start[0] - 1] + token.start[1]
stop = offsets[following.end[0] - 1] + following.end[1]
replacements.append((start, stop, replacement))
for start, stop, replacement in reversed(replacements):
marker = marker[:start] + replacement + marker[stop:]
return ast.parse(marker, mode="eval").body
def marker_clause(part: ast.expr) -> MarkerClause:
if (
not isinstance(part, ast.Compare)
or len(part.ops) != 1
or len(part.comparators) != 1
or type(part.ops[0])
not in {ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE, ast.In, ast.NotIn, ast.Is, ast.IsNot}
):
raise SystemExit("Ambiguous direct security dependency marker")
operator = {"Is": "Compatible", "IsNot": "ArbitraryEq"}.get(type(part.ops[0]).__name__, type(part.ops[0]).__name__)
right = part.comparators[0]
if isinstance(part.left, ast.Name) and isinstance(right, ast.Constant) and isinstance(right.value, str):
variable, value = part.left.id, right.value
elif (
isinstance(part.left, ast.Constant)
and isinstance(part.left.value, str)
and isinstance(right, ast.Name)
and operator in {"Eq", "NotEq", "Lt", "LtE", "Gt", "GtE", "In", "NotIn"}
):
variable, value = right.id, part.left.value
operator = {
"Eq": "Eq",
"NotEq": "NotEq",
"Lt": "Gt",
"LtE": "GtE",
"Gt": "Lt",
"GtE": "LtE",
"In": "ReverseIn",
"NotIn": "ReverseNotIn",
}[operator]
else:
raise SystemExit("Ambiguous direct security dependency marker")
return variable.lower(), operator, value
def marker_context(marker: str) -> MarkerContext:
if not marker.strip():
return ()
try:
if any(
token.type == tokenize.OP and token.string in {"(", ")"}
for token in tokenize.generate_tokens(io.StringIO(marker).readline)
):
raise ValueError("Parenthesized security dependency marker")
expression = parse_marker_expression(marker.strip())
except (SyntaxError, tokenize.TokenError, ValueError):
raise SystemExit("Ambiguous direct security dependency marker") from None
if isinstance(expression, ast.BoolOp):
if not isinstance(expression.op, ast.And):
raise SystemExit("Ambiguous direct security dependency marker")
parts = expression.values
else:
parts = [expression]
return tuple(sorted(marker_clause(part) for part in parts))
def direct_marker_contexts(marker: str) -> tuple[MarkerContext, ...]:
if not marker.strip():
return ((),)
if len(marker) > 1024:
raise SystemExit("Unbounded direct security dependency marker")
try:
expression = parse_marker_expression(marker.strip())
except (SyntaxError, tokenize.TokenError, ValueError):
raise SystemExit("Ambiguous direct security dependency marker") from None
if sum(1 for _ in ast.walk(expression)) > 256:
raise SystemExit("Unbounded direct security dependency marker")
def expand(node: ast.expr, depth: int = 0) -> list[MarkerContext]:
if depth > 32:
raise SystemExit("Unbounded direct security dependency marker")
if isinstance(node, ast.BoolOp):
values: list[MarkerContext]
if isinstance(node.op, ast.Or):
values = []
for child in node.values:
values.extend(expand(child, depth + 1))
if len(values) > 128:
raise SystemExit("Unbounded direct security dependency marker")
elif isinstance(node.op, ast.And):
values = [()]
for child in node.values:
current = expand(child, depth + 1)
if len(values) * len(current) > 128:
raise SystemExit("Unbounded direct security dependency marker")
values = [tuple(sorted(set(left + right))) for left in values for right in current]
else:
raise SystemExit("Ambiguous direct security dependency marker")
return values
context = (marker_clause(node),)
for option in marker_options(context):
simple_marker_overlap(option, ())
return [context]
expanded = expand(expression)
if sum(len(marker_options(context)) for context in expanded) > 128:
raise SystemExit("Unbounded direct security dependency marker")
unique: list[MarkerContext] = []
for context in sorted(set(expanded), key=lambda value: (len(value), value)):
if not marker_overlap(context, ()):
continue
if any(not uncovered_marker_fragments(context, [previous]) for previous in unique):
continue
unique = [previous for previous in unique if uncovered_marker_fragments(previous, [context])]
unique.append(context)
return tuple(unique)
def direct(project: dict[str, Any], *, protected: bool = False) -> tuple[RequirementMap, ContextsByName]:
if protected:
uv = project.get("tool", {}).get("uv", {})
groups = [
("uv-constraint", "", uv.get("constraint-dependencies", [])),
("uv-build-constraint", "", uv.get("build-constraint-dependencies", [])),
]
groups.extend(
("dependency-group", canonical(group), requirements)
for group, requirements in project.get("dependency-groups", {}).items()
)
else:
groups = [("runtime", "", project["project"].get("dependencies", []))]
groups.extend(
("optional", canonical(group), requirements)
for group, requirements in project["project"].get("optional-dependencies", {}).items()
)
result: RequirementMap = {}
contexts: ContextsByName = {}
for scope, group, requirements in groups:
for requirement in requirements:
match = re.fullmatch(r"\s*([A-Za-z0-9][A-Za-z0-9_.-]*)(\[[^\]]+\])?\s*(.*)", requirement)
if match is None:
raise SystemExit("Ambiguous direct security dependency requirement")
name = canonical(match.group(1))
extra = match.group(2)
requested: tuple[str, ...] = ()
if extra:
requested = tuple(sorted(canonical(value.strip()) for value in extra[1:-1].split(",")))
if any(not re.fullmatch(r"[a-z0-9][a-z0-9-]*", value) for value in requested):
raise SystemExit("Ambiguous direct security dependency extras")
normalized = name + (match.group(2) or "").lower() + re.sub(r"\s+", "", match.group(3)).lower()
result.setdefault(name, set()).add(normalized)
for marker in direct_marker_contexts(match.group(3).partition(";")[2]):
context = (scope, group, requested, marker)
contexts.setdefault(name, {}).setdefault(context, set()).add(normalized)
return result, contexts
def versions(lock: dict[str, Any]) -> tuple[RequirementMap, ResolutionsByName]:
result: RequirementMap = {}
contexts: ResolutionsByName = {}
for package in lock["package"]:
name = canonical(package["name"])
version = package["version"]
result.setdefault(name, set()).add(version)
markers = package.get("resolution-markers")
domains: list[MarkerContext]
if markers is None:
domains = [()]
else:
if (
not isinstance(markers, list)
or not markers
or any(not isinstance(marker, str) for marker in cast(list[object], markers))
):
raise SystemExit("Ambiguous locked security dependency resolution marker")
domains = [marker_context(marker) for marker in cast(list[str], markers)]
for domain in domains:
contexts.setdefault(name, {}).setdefault(domain, set()).add(version)
return result, contexts
def dependency_marker_options(marker: object, extras: tuple[str, ...]) -> list[MarkerContext]:
if marker is None:
return [()]
if not isinstance(marker, str) or not marker.strip() or len(marker) > 1024:
raise SystemExit("Ambiguous locked security dependency edge marker")
try:
expression = parse_marker_expression(marker)
except (SyntaxError, tokenize.TokenError, ValueError):
raise SystemExit("Ambiguous locked security dependency edge marker") from None
selected = extras or ("",)
if len(selected) > 128:
raise SystemExit("Unbounded locked security dependency edge extras")
work = 0
def options(node: ast.expr, extra: str) -> list[MarkerContext]:
nonlocal work
work += 1
if work > 8192:
raise SystemExit("Unbounded locked security dependency edge marker")
if isinstance(node, ast.BoolOp):
values: list[MarkerContext]
if isinstance(node.op, ast.Or):
values = [context for child in node.values for context in options(child, extra)]
elif isinstance(node.op, ast.And):
values = [()]
for child in node.values:
current = options(child, extra)
if len(values) * len(current) > 128:
raise SystemExit("Unbounded locked security dependency edge marker")
values = [tuple(sorted(set(left + right))) for left in values for right in current]
else:
raise SystemExit("Ambiguous locked security dependency edge marker")
if len(values) > 128:
raise SystemExit("Unbounded locked security dependency edge marker")
return values
context = (marker_clause(node),)
variable, operator, value = context[0]
if variable != "extra":
return [context]
normalized = canonical(value)
if operator in {"Eq", "GtE", "LtE"}:
accepted = extra == normalized
elif operator == "NotEq":
accepted = extra != normalized
elif operator in {"Gt", "Lt"}:
accepted = False
elif operator in {"In", "NotIn", "ReverseIn", "ReverseNotIn"}:
if len(value) > 256:
raise SystemExit("Unbounded locked security dependency edge extra")
if operator in {"ReverseIn", "ReverseNotIn"}:
accepted = (normalized in extra) == (operator == "ReverseIn")
else:
accepted = (extra in normalized) == (operator == "In")
else:
raise SystemExit("Ambiguous locked security dependency edge extra")
return [()] if accepted else []
result: list[MarkerContext] = []
seen: set[MarkerContext] = set()
for extra in selected:
for context in options(expression, extra):
if context in seen:
continue
seen.add(context)
result.append(context)
if len(result) > 128:
raise SystemExit("Unbounded locked security dependency edge marker")
return result
def published_reachability(
lock: dict[str, Any], contexts: ContextsByName
) -> dict[str, set[tuple[str, str, MarkerContext]]]:
packages: dict[str, list[dict[str, Any]]] = {}
for item in lock["package"]:
if not isinstance(item, dict):
raise SystemExit("Ambiguous locked security dependency identity")
package = cast(dict[str, Any], item)
if not isinstance(package.get("name"), str):
raise SystemExit("Ambiguous locked security dependency identity")
packages.setdefault(canonical(package["name"]), []).append(package)
pending: list[tuple[str, tuple[str, ...], str, str, MarkerContext, str | None]] = [
(name, context[2], context[0], context[1], context[3], None)
for name, requirements in contexts.items()
for context in requirements
]
visited: set[tuple[str, tuple[str, ...], str, str, MarkerContext, str | None]] = set()
reachable: dict[str, set[tuple[str, str, MarkerContext]]] = {}
while pending:
if len(pending) > 4096 or len(visited) > 8192:
raise SystemExit("Unbounded published security dependency graph")
name, extras, scope, group, context, selected_version = pending.pop()
state = name, extras, scope, group, context, selected_version
if state in visited:
continue
visited.add(state)
candidates = packages.get(name, [])
if not candidates:
raise SystemExit("Missing locked published security dependency identity for " + name)
matched = False
for package in candidates:
version = package.get("version")
if not isinstance(version, str):
raise SystemExit("Ambiguous locked published security dependency version")
if selected_version is not None and version != selected_version:
continue
resolutions = package.get("resolution-markers")
if resolutions is None:
domains: list[MarkerContext] = [()]
elif isinstance(resolutions, list) and resolutions:
values = cast(list[object], resolutions)
if not all(isinstance(value, str) for value in values):
raise SystemExit("Ambiguous locked published security dependency resolution")
domains = [marker_context(value) for value in cast(list[str], resolutions)]
else:
raise SystemExit("Ambiguous locked published security dependency resolution")
for domain in domains:
if not marker_overlap(context, domain):
continue
matched = True
combined = tuple(sorted(set(context + domain)))
reachable.setdefault(name, set()).add((scope, group, combined))
direct_edges = package.get("dependencies", [])
optional_edges = package.get("optional-dependencies", {})
if not isinstance(direct_edges, list) or not isinstance(optional_edges, dict):
raise SystemExit("Ambiguous locked published security dependency edges")
groups: dict[str, object] = {}
for optional, edges in cast(dict[object, object], optional_edges).items():
if not isinstance(optional, str):
raise SystemExit("Ambiguous locked published security dependency extra")
key = canonical(optional)
if key in groups:
raise SystemExit("Ambiguous locked published security dependency extra")
groups[key] = edges
edges_to_follow: list[object] = list(cast(list[object], direct_edges))
for extra in extras:
requested = groups.get(extra, [])
if not isinstance(requested, list):
raise SystemExit("Ambiguous locked published security dependency extra")
edges_to_follow.extend(cast(list[object], requested))
for item in edges_to_follow:
if not isinstance(item, dict):
raise SystemExit("Ambiguous locked published security dependency edge")
edge = cast(dict[str, Any], item)
if not isinstance(edge.get("name"), str):
raise SystemExit("Ambiguous locked published security dependency edge")
edge_name = canonical(edge["name"])
if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", edge_name):
raise SystemExit("Ambiguous locked published security dependency edge")
requested_extras = edge.get("extra", [])
if not isinstance(requested_extras, list) or any(
not isinstance(extra, str) for extra in cast(list[object], requested_extras)
):
raise SystemExit("Ambiguous locked published security dependency edge extra")
normalized_extras = tuple(sorted(canonical(extra) for extra in cast(list[str], requested_extras)))
if len(normalized_extras) != len(set(normalized_extras)) or any(
not re.fullmatch(r"[a-z0-9][a-z0-9-]*", extra) for extra in normalized_extras
):
raise SystemExit("Ambiguous locked published security dependency edge extra")
edge_version = edge.get("version")
if edge_version is not None and not isinstance(edge_version, str):
raise SystemExit("Ambiguous locked published security dependency edge version")
for edge_context in dependency_marker_options(edge.get("marker"), extras):
next_context = tuple(sorted(set(combined + edge_context)))
if not marker_overlap(next_context, ()):
continue
pending.append((edge_name, normalized_extras, scope, group, next_context, edge_version))
if not matched and selected_version is not None:
raise SystemExit("Missing selected locked published security dependency version for " + name)
return reachable
def requested_extra_reachability(
lock: dict[str, Any],
previous: ContextsByName,
current: ContextsByName,
requested: list[tuple[str, DependencyContext]],
) -> dict[str, set[tuple[str, str, MarkerContext]]]:
if len(requested) > 64:
raise SystemExit("Unbounded newly requested security dependency extras")
result: dict[str, set[tuple[str, str, MarkerContext]]] = {}
for root, context in requested:
selected = published_reachability(lock, {root: {context: current[root][context]}})
alternatives: ContextRequirements = {}
for original, requirements in previous.get(root, {}).items():
if (
original[:2] != context[:2]
or not set(original[2]).issubset(context[2])
or not marker_overlap(original[3], context[3])
):
continue
shared = tuple(sorted(set(original[3] + context[3])))
counterfactual = original[0], original[1], original[2], shared
alternatives.setdefault(counterfactual, set()).update(requirements)
without = published_reachability(lock, {root: alternatives}) if alternatives else {}
for name, audiences in selected.items():
for scope, group, marker in audiences:
prior = [
previous_marker
for previous_scope, previous_group, previous_marker in without.get(name, set())
if previous_scope == "runtime" or (previous_scope, previous_group) == (scope, group)
]
for uncovered in uncovered_marker_fragments(marker, prior):
result.setdefault(name, set()).add((scope, group, uncovered))
return result
def audience_covers(previous: tuple[str, str, MarkerContext], current: tuple[str, str, MarkerContext]) -> bool:
if previous[0] != "runtime" and previous[:2] != current[:2]:
return False
return not uncovered_marker_fragments(current[2], [previous[2]])
def stable_version(value: str) -> StableRelease:
match = re.fullmatch(r"(?:(\d+)!)?(\d+(?:\.\d+)*)(?:\.post(\d+))?", value)
if match is None:
raise SystemExit("Unsupported direct security dependency minimum")
release = tuple(int(part) for part in match.group(2).split("."))
while release and release[-1] == 0:
release = release[:-1]
post = -1 if match.group(3) is None else int(match.group(3))
return int(match.group(1) or 0), release, post
def is_numeric_platform_release(value: str) -> bool:
if len(value) > 256:
raise SystemExit("Unbounded platform security dependency marker")
return (
re.fullmatch(
r"v?(?:[0-9]+!)?[0-9]+(?:\.[0-9]+)*"
r"(?:[._-]?(?:alpha|a|beta|b|preview|pre|c|rc)[._-]?[0-9]*)?"
r"(?:(?:-[0-9]+)|(?:[._-]?(?:post|rev|r)[._-]?[0-9]*))?"
r"(?:[._-]?dev[._-]?[0-9]*)?"
r"(?:\+[a-z0-9]+(?:[._-][a-z0-9]+)*)?"
r"(?:\.\*)?",
value.strip(),
re.IGNORECASE,
)
is not None
)
def numeric_platform_release_candidate(value: str) -> str | None:
match = re.fullmatch(
r"v?(?P<release>[0-9]+(?:\.[0-9]+)*)"
r"(?:[._-]?(?P<stage>alpha|a|beta|b|preview|pre|c|rc)[._-]?(?P<serial>[0-9]*))?"
r"(?:(?:-(?P<implicit_post>[0-9]+))|"
r"(?:[._-]?(?P<post>post|rev|r)[._-]?(?P<post_serial>[0-9]*)))?"
r"(?:[._-]?dev[._-]?(?P<development>[0-9]*))?",
value.strip(),
re.IGNORECASE,
)
if match is None:
return None
result = match.group("release")
stage = match.group("stage")
if stage is not None:
result += {"alpha": "a", "a": "a", "beta": "b", "b": "b"}.get(stage.lower(), "rc")
result += match.group("serial") or "0"
if match.group("implicit_post") is not None:
result += ".post" + match.group("implicit_post")
elif match.group("post") is not None:
result += ".post" + (match.group("post_serial") or "0")
if match.group("development") is not None:
result += ".dev" + (match.group("development") or "0")
return result
def marker_version_bounds(
variable: str, value: str, *, release_width: int = 3
) -> tuple[tuple[int, ...], tuple[int, ...], bool, bool]:
match = re.fullmatch(
r"(\d+(?:\.\d+)*)(?:(a|b|rc)(\d+))?(?:\.post(\d+))?(?:\.dev(\d+))?(\.\*)?",
value.strip() if variable == "platform_release" else value,
)
if match is None:
raise SystemExit("Ambiguous Python security dependency marker")
components = match.group(1).split(".")
if len(components) > 32:
if variable == "platform_release":
raise SystemExit("Unbounded platform security dependency marker")
raise SystemExit("Unbounded Python security dependency marker")
if variable != "platform_release" and len(components) < 2:
raise SystemExit("Ambiguous Python security dependency marker")
if any(len(component) > 9 for component in components) or any(
len(match.group(index)) > 9 for index in (3, 4, 5) if match.group(index) is not None
):
raise SystemExit("Unbounded Python security dependency marker")
release = tuple(int(component) for component in components)
release += (0,) * max(0, release_width - len(release))
prerelease = match.group(2) is not None or match.group(5) is not None
wildcard = match.group(6) is not None
if wildcard and (prerelease or match.group(4) is not None):
raise SystemExit("Ambiguous wildcard security dependency marker")
if variable == "python_version" and (
any(component != 0 for component in release[2:]) or prerelease or match.group(4) is not None
):
raise SystemExit("Ambiguous Python security dependency marker")
phase = (
-4
if match.group(5) is not None and match.group(2) is None and match.group(4) is None
else {"a": -3, "b": -2, "rc": -1}.get(match.group(2) or "", 0)
)
serial = int(match.group(3) or 0)
post = -1 if match.group(4) is None else int(match.group(4))
development = -1 if match.group(5) is not None else 0
development_serial = int(match.group(5) or 0)
if variable == "python_version" or wildcard:
start = release + (-5, 0, -1, -1, 0)
prefix = 2 if variable == "python_version" else len(components)
stop = release[: prefix - 1] + (release[prefix - 1] + 1,) + (0,) * (len(release) - prefix)
stop += -5, 0, -1, -1, 0
else:
start = release + (phase, serial, post, development, development_serial)
stop = start[:-1] + (development_serial + 1,)
return start, stop, wildcard, prerelease
def simple_marker_overlap(requirement: MarkerContext, resolution: MarkerContext) -> bool:
clauses: dict[str, list[MarkerClause]] = {}
for variable, operator, value in requirement + resolution:
family = "python" if variable in {"python_version", "python_full_version"} else variable
clauses.setdefault(family, []).append((variable, operator, value))
for family, constraints in clauses.items():
platform_memberships = [
clause for clause in constraints if family == "platform_release" and clause[1] in {"In", "NotIn"}
]
platform_raw_equalities = [
clause for clause in constraints if family == "platform_release" and clause[1] == "ArbitraryEq"
]
platform_raw_exclusions = [
clause for clause in constraints if family == "platform_release" and clause[1] == "ArbitraryNotEq"
]
comparisons = [
clause
for clause in constraints
if family != "platform_release" or clause[1] not in {"In", "NotIn", "ArbitraryEq", "ArbitraryNotEq"}
]
numeric_platform_values = [
family == "platform_release" and is_numeric_platform_release(value) for _, _, value in comparisons
]
if family == "platform_release" and any(numeric_platform_values) and not all(numeric_platform_values):
if any(
not numeric and operator != "NotEq"
for numeric, (_, operator, _) in zip(numeric_platform_values, comparisons, strict=True)
):
return False
comparisons = [
clause for numeric, clause in zip(numeric_platform_values, comparisons, strict=True) if numeric
]
numeric_platform_values = [True] * len(comparisons)
numeric_platform_release = family == "platform_release" and bool(comparisons) and all(numeric_platform_values)
def platform_witness_matches(
candidate: str,
memberships: list[MarkerClause] = platform_memberships,
exclusions: list[MarkerClause] = platform_raw_exclusions,
) -> bool:
return all((candidate in value) == (operator == "In") for _, operator, value in memberships) and all(
candidate.lower() != value.lower() for _, _, value in exclusions
)
def anchored_platform_witness() -> str | None:
for context in (resolution, requirement):
equalities = [
value.strip()
for variable, operator, value in context
if variable == "platform_release" and operator == "Eq" and not value.rstrip().endswith(".*")
]
if not equalities:
continue
local = [
clause
for clause in context
if clause[0] == "platform_release" and clause[1] in {"In", "NotIn", "ArbitraryNotEq"}
]
for candidate in equalities:
if all(
(candidate in value) == (operator == "In")
if operator in {"In", "NotIn"}
else candidate.lower() != value.lower()
for _, operator, value in local
):
return candidate
return None
return None
if family == "platform_release" and (platform_raw_equalities or platform_raw_exclusions):
if any(len(value) > 256 for _, _, value in platform_raw_equalities + platform_raw_exclusions):
raise SystemExit("Unbounded platform security dependency marker")
if platform_raw_equalities:
raw_values = {value.lower() for _, _, value in platform_raw_equalities}
if len(raw_values) != 1:
return False
anchor = (
anchored_platform_witness()
if any(variable == "platform_release" and operator == "Eq" for variable, operator, _ in resolution)
and not any(
variable == "platform_release" and operator == "ArbitraryEq"
for variable, operator, _ in resolution
)
else None
)
selected = next(
(
value
for variable, operator, value in resolution
if variable == "platform_release" and operator == "ArbitraryEq"
),
platform_raw_equalities[0][2],
)
if anchor is not None:
if anchor.lower() not in raw_values:
return False
selected = anchor
if not platform_witness_matches(selected):
return False
if not comparisons:
continue
if numeric_platform_release:
normalized = numeric_platform_release_candidate(selected)
if normalized is None:
raise SystemExit("Ambiguous platform security dependency raw equality")
selected = normalized
if not simple_marker_overlap(tuple(comparisons), (("platform_release", "Eq", selected),)):
return False
continue
if numeric_platform_release and platform_memberships:
if any(len(value) > 256 for _, _, value in platform_memberships):
raise SystemExit("Unbounded platform security dependency marker")
anchor = anchored_platform_witness()
included = [value for _, operator, value in platform_memberships if operator == "In"]
if included:
shortest = min(included, key=len)
if len(shortest) > 128:
raise SystemExit("Unbounded platform security dependency membership")
candidates = {
shortest[start:stop]
for start in range(len(shortest) + 1)
for stop in range(start, len(shortest) + 1)
}
if len(candidates) > 4096:
raise SystemExit("Unbounded platform security dependency membership")
unsupported = False
matched = False
for membership_candidate in sorted(candidates):
if (
anchor is not None
and membership_candidate != anchor
or not platform_witness_matches(membership_candidate)
or not is_numeric_platform_release(membership_candidate)
):
continue
normalized = numeric_platform_release_candidate(membership_candidate)
if normalized is None:
unsupported = True
continue
try:
_, _, wildcard, _ = marker_version_bounds("platform_release", normalized)
except SystemExit:
unsupported = True
continue
if wildcard:
unsupported = True
continue
if simple_marker_overlap(tuple(comparisons), (("platform_release", "Eq", normalized),)):
matched = True
break
if not matched:
if unsupported:
raise SystemExit("Ambiguous platform security dependency membership")
return False
continue
if anchor is not None:
if not platform_witness_matches(anchor):
return False
normalized = numeric_platform_release_candidate(anchor)
if normalized is None:
raise SystemExit("Ambiguous platform security dependency membership")
if not simple_marker_overlap(tuple(comparisons), (("platform_release", "Eq", normalized),)):
return False
continue
equalities = [value for _, operator, value in comparisons if operator == "Eq" and not value.endswith(".*")]
if equalities:
if not simple_marker_overlap(tuple(comparisons), ()):
return False
matched = False
for numeric_equality in equalities:
normalized = numeric_platform_release_candidate(numeric_equality)
if normalized is None:
raise SystemExit("Ambiguous platform security dependency membership")
match = re.fullmatch(r"(\d+(?:\.\d+)*)(.*)", normalized)
if match is None:
raise SystemExit("Ambiguous platform security dependency membership")
release, suffix = match.groups()
components = release.split(".")
if len(components) > 32:
raise SystemExit("Unbounded platform security dependency membership")
for trailing in range(33 - len(components)):
for leading in range(10 - len(components[0])):
raw_candidate = "0" * leading + release + ".0" * trailing + suffix
if len(raw_candidate) > 256 or not platform_witness_matches(raw_candidate):
continue
if simple_marker_overlap(tuple(comparisons), (("platform_release", "Eq", normalized),)):
matched = True
break
if matched:
break
if matched:
break
if not matched:
raise SystemExit("Ambiguous platform security dependency membership")
continue
elif numeric_platform_release and platform_raw_exclusions:
anchor = anchored_platform_witness()
if anchor is not None and not platform_witness_matches(anchor):
return False
if family in {"python", "implementation_version"} or numeric_platform_release:
if numeric_platform_release:
constraints = comparisons
release_width = max(
3,
max(
(
len(match.group().split("."))
for _, _, value in constraints
if (match := re.match(r"\d+(?:\.\d+)*", value.strip() if numeric_platform_release else value))
),
default=3,
),
)
lower: tuple[int, ...] = (0,) * release_width + (-5, 0, -1, -1, 0)
upper: tuple[int, ...] | None = None
excluded: list[tuple[tuple[int, ...], tuple[int, ...]]] = []
for variable, operator, value in constraints:
start, stop, wildcard, prerelease = marker_version_bounds(variable, value, release_width=release_width)
if wildcard and operator not in {"Eq", "NotEq"}:
raise SystemExit("Ambiguous wildcard security dependency marker")
if operator == "Eq":
lower = max(lower, start)
upper = stop if upper is None else min(upper, stop)
elif operator == "NotEq":
excluded.append((start, stop))
elif operator in {"Lt", "RawLt"}:
ceiling = start
if operator == "Lt" and variable != "python_version" and not prerelease:
if start[-3] == -1:
ceiling = start[:-5] + (-5, 0, -1, -1, 0)
else:
ceiling = start[:-2] + (-1, 0)
upper = ceiling if upper is None else min(upper, ceiling)
elif operator in {"LtE", "RawLtE"}:
ceiling = stop
if operator == "RawLtE" and variable != "python_version" and start[-3] == -1 and start[-2] == 0:
if prerelease:
ceiling = start[:-4] + (start[-4] + 1, -1, -1, 0)
else:
ceiling = start[:-6] + (start[-6] + 1, -5, 0, -1, -1, 0)
upper = ceiling if upper is None else min(upper, ceiling)
elif operator in {"Gt", "RawGt"}:
floor = stop
if operator == "Gt" and variable != "python_version" and start[-3] == -1 and start[-2] == 0:
if prerelease:
floor = start[:-4] + (start[-4] + 1, -1, -1, 0)
else:
floor = start[:-6] + (start[-6] + 1, -5, 0, -1, -1, 0)
lower = max(lower, floor)
elif operator in {"GtE", "RawGtE"}:
floor = start
if operator == "RawGtE" and variable != "python_version" and not prerelease:
if start[-3] == -1:
floor = start[:-5] + (-5, 0, -1, -1, 0)
else:
floor = start[:-2] + (-1, 0)
lower = max(lower, floor)
else:
raise SystemExit("Ambiguous Python security dependency marker")
if upper is not None and lower >= upper:
return False
candidate = lower
for start, stop in sorted(excluded):
if start <= candidate < stop:
candidate = stop
if upper is not None and candidate >= upper:
return False
else:
if family not in {
"sys_platform",
"os_name",
"platform_system",
"platform_machine",
"platform_release",
"platform_version",
"platform_python_implementation",
"implementation_name",
"extra",
}:
raise SystemExit("Unsupported security dependency marker variable")
equality: str | None = None
memberships: list[str] = []
required_substrings: list[str] = []
for _, operator, value in constraints:
if len(value) > 256:
raise SystemExit("Unbounded platform security dependency marker")
if operator in {"Eq", "GtE", "LtE"}:
if equality is not None and equality != value:
return False
equality = value
elif operator in {"Gt", "Lt"}:
return False
elif operator == "In":
memberships.append(value)
elif operator == "ReverseIn":
required_substrings.append(value)
elif operator not in {"NotEq", "NotIn", "ReverseNotIn", "ArbitraryNotEq"}:
raise SystemExit("Ambiguous platform security dependency marker")
def matches(platform_candidate: str, terms: list[MarkerClause] = constraints) -> bool:
for _, operator, value in terms:
if (
operator in {"Eq", "GtE", "LtE"}
and platform_candidate != value
or operator == "NotEq"
and platform_candidate == value
or operator == "ArbitraryNotEq"
and platform_candidate.lower() == value.lower()
or operator in {"Lt", "Gt"}
or operator == "In"
and platform_candidate not in value
or operator == "NotIn"
and platform_candidate in value
or operator == "ReverseIn"
and value not in platform_candidate
or operator == "ReverseNotIn"
and value in platform_candidate
):
return False
return True
if equality is not None:
if not matches(equality):
return False
elif memberships:
shortest = min(memberships, key=len)
if len(shortest) > 128:
raise SystemExit("Unbounded platform security dependency membership")
candidates = {
shortest[start:stop]
for start in range(len(shortest) + 1)
for stop in range(start, len(shortest) + 1)
}
if len(candidates) > 4096:
raise SystemExit("Unbounded platform security dependency membership")
if not any(matches(platform_candidate) for platform_candidate in candidates):
return False
else:
if sum(map(len, required_substrings)) > 4096:
raise SystemExit("Unbounded platform security dependency substring")
if any(
forbidden in required
for _, operator, forbidden in constraints
if operator == "ReverseNotIn"
for required in required_substrings
) or any(operator == "ReverseNotIn" and not value for _, operator, value in constraints):
return False
platform_candidate = "\x00".join(required_substrings)
for _ in range(258):
if matches(platform_candidate):
break
platform_candidate += "\x00"
else:
raise SystemExit("Ambiguous platform security dependency marker")
return True
def marker_options(context: MarkerContext) -> list[MarkerContext]:
options: list[MarkerContext] = [()]
allowed_platforms = {
"sys_platform",
"os_name",
"platform_system",
"platform_machine",
"platform_release",
"platform_version",
"platform_python_implementation",
"implementation_name",
"extra",
}
for variable, operator, value in context:
if operator in {"ReverseIn", "ReverseNotIn"}:
if variable not in allowed_platforms or variable == "platform_release":
raise SystemExit("Unsupported reversed security dependency membership marker")
if len(value) > 256 or value and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", value) is None:
raise SystemExit("Ambiguous reversed security dependency membership marker")
options = [option + ((variable, operator, value),) for option in options]
continue
if operator == "Compatible":
if variable not in {"python_version", "python_full_version", "implementation_version", "platform_release"}:
raise SystemExit("Unsupported compatible security dependency marker")
compatible = re.fullmatch(
r"(\d+(?:\.\d+)+)"
r"((?:(?:a|b|rc)\d+)?(?:\.post\d+)?(?:\.dev\d+)?)",
value,
)
if compatible is None:
raise SystemExit("Ambiguous compatible security dependency marker")
components = compatible.group(1).split(".")
if len(components) > 32 or any(len(component) > 9 for component in components):
raise SystemExit("Ambiguous compatible security dependency marker")
ceiling = [int(component) for component in components[:-1]]
ceiling[-1] += 1
if len(ceiling) == 1:
ceiling.append(0)
upper = ".".join(str(component) for component in ceiling)
if variable == "python_version":
minor = int(components[1])
lower = f"{int(components[0])}.{minor}"
width = max(3, len(components))
projected = marker_version_bounds("platform_release", lower, release_width=width)[0]
actual = marker_version_bounds("platform_release", value, release_width=width)[0]
if projected < actual:
lower = f"{int(components[0])}.{minor + 1}"
if len(ceiling) > 2 and any(component != 0 for component in ceiling[2:]):
upper = f"{ceiling[0]}.{ceiling[1] + 1}"
else:
upper = f"{ceiling[0]}.{ceiling[1]}"
value = lower
options = [option + ((variable, "GtE", value), (variable, "Lt", upper)) for option in options]
continue
if operator == "ArbitraryEq":
if variable == "python_version":
pattern = r"(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)"
elif variable in {"python_full_version", "implementation_version"}:
pattern = (
r"(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)"
r"(?:(?:a|b|rc)(?:0|[1-9]\d*))?(?:\.post(?:0|[1-9]\d*))?(?:\.dev(?:0|[1-9]\d*))?"
)
elif variable == "platform_release":
if len(value) > 256 or re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.!+-]*", value.strip()) is None:
raise SystemExit("Ambiguous platform security dependency raw equality")
options = [option + ((variable, operator, value.strip()),) for option in options]
continue
else:
raise SystemExit("Unsupported arbitrary security dependency marker variable")
if re.fullmatch(pattern, value) is None:
return []
operator = "Eq"