1"""Hash-checking related pip exceptions."""
2
3from __future__ import annotations
4
5from itertools import chain, groupby, repeat
6from typing import TYPE_CHECKING
7
8from pip._internal.exceptions._base import InstallationError
9
10if TYPE_CHECKING:
11 from hashlib import _Hash
12
13 from pip._internal.req.req_install import InstallRequirement
14
15
16class HashErrors(InstallationError):
17 """Multiple HashError instances rolled into one for reporting"""
18
19 def __init__(self) -> None:
20 self.errors: list[HashError] = []
21
22 def append(self, error: HashError) -> None:
23 self.errors.append(error)
24
25 def __str__(self) -> str:
26 lines = []
27 self.errors.sort(key=lambda e: e.order)
28 for cls, errors_of_cls in groupby(self.errors, lambda e: e.__class__):
29 lines.append(cls.head)
30 lines.extend(e.body() for e in errors_of_cls)
31 if lines:
32 return "\n".join(lines)
33 return ""
34
35 def __bool__(self) -> bool:
36 return bool(self.errors)
37
38
39class HashError(InstallationError):
40 """
41 A failure to verify a package against known-good hashes
42
43 :cvar order: An int sorting hash exception classes by difficulty of
44 recovery (lower being harder), so the user doesn't bother fretting
45 about unpinned packages when he has deeper issues, like VCS
46 dependencies, to deal with. Also keeps error reports in a
47 deterministic order.
48 :cvar head: A section heading for display above potentially many
49 exceptions of this kind
50 :ivar req: The InstallRequirement that triggered this error. This is
51 pasted on after the exception is instantiated, because it's not
52 typically available earlier.
53
54 """
55
56 req: InstallRequirement | None = None
57 head = ""
58 order: int = -1
59
60 def body(self) -> str:
61 """Return a summary of me for display under the heading.
62
63 This default implementation simply prints a description of the
64 triggering requirement.
65
66 :param req: The InstallRequirement that provoked this error, with
67 its link already populated by the resolver's _populate_link().
68
69 """
70 return f" {self._requirement_name()}"
71
72 def __str__(self) -> str:
73 return f"{self.head}\n{self.body()}"
74
75 def _requirement_name(self) -> str:
76 """Return a description of the requirement that triggered me.
77
78 This default implementation returns long description of the req, with
79 line numbers
80
81 """
82 return str(self.req) if self.req else "unknown package"
83
84
85class VcsHashUnsupported(HashError):
86 """A hash was provided for a version-control-system-based requirement, but
87 we don't have a method for hashing those."""
88
89 order = 0
90 head = (
91 "Can't verify hashes for these requirements because we don't "
92 "have a way to hash version control repositories:"
93 )
94
95
96class DirectoryUrlHashUnsupported(HashError):
97 """A hash was provided for a version-control-system-based requirement, but
98 we don't have a method for hashing those."""
99
100 order = 1
101 head = (
102 "Can't verify hashes for these file:// requirements because they "
103 "point to directories:"
104 )
105
106
107class HashMissing(HashError):
108 """A hash was needed for a requirement but is absent."""
109
110 order = 2
111 head = (
112 "Hashes are required in --require-hashes mode, but they are "
113 "missing from some requirements. Here is a list of those "
114 "requirements along with the hashes their downloaded archives "
115 "actually had. Add lines like these to your requirements files to "
116 "prevent tampering. (If you did not enable --require-hashes "
117 "manually, note that it turns on automatically when any package "
118 "has a hash.)"
119 )
120
121 def __init__(self, gotten_hash: str) -> None:
122 """
123 :param gotten_hash: The hash of the (possibly malicious) archive we
124 just downloaded
125 """
126 self.gotten_hash = gotten_hash
127
128 def body(self) -> str:
129 # Dodge circular import.
130 from pip._internal.utils.hashes import FAVORITE_HASH
131
132 package = None
133 if self.req:
134 # In the case of URL-based requirements, display the original URL
135 # seen in the requirements file rather than the package name,
136 # so the output can be directly copied into the requirements file.
137 package = (
138 self.req.original_link
139 if self.req.is_direct
140 # In case someone feeds something downright stupid
141 # to InstallRequirement's constructor.
142 else getattr(self.req, "req", None)
143 )
144 return " {} --hash={}:{}".format(
145 package or "unknown package", FAVORITE_HASH, self.gotten_hash
146 )
147
148
149class HashUnpinned(HashError):
150 """A requirement had a hash specified but was not pinned to a specific
151 version."""
152
153 order = 3
154 head = (
155 "In --require-hashes mode, all requirements must have their "
156 "versions pinned with ==. These do not:"
157 )
158
159
160class HashMismatch(HashError):
161 """
162 Distribution file hash values don't match.
163
164 :ivar package_name: The name of the package that triggered the hash
165 mismatch. Feel free to write to this after the exception is raise to
166 improve its error message.
167
168 """
169
170 order = 4
171 head = (
172 "THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS "
173 "FILE. If you have updated the package versions, please update "
174 "the hashes. Otherwise, examine the package contents carefully; "
175 "someone may have tampered with them."
176 )
177
178 def __init__(self, allowed: dict[str, list[str]], gots: dict[str, _Hash]) -> None:
179 """
180 :param allowed: A dict of algorithm names pointing to lists of allowed
181 hex digests
182 :param gots: A dict of algorithm names pointing to hashes we
183 actually got from the files under suspicion
184 """
185 self.allowed = allowed
186 self.gots = gots
187
188 def body(self) -> str:
189 return f" {self._requirement_name()}:\n{self._hash_comparison()}"
190
191 def _hash_comparison(self) -> str:
192 """
193 Return a comparison of actual and expected hash values.
194
195 Example::
196
197 Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
198 or 123451234512345123451234512345123451234512345
199 Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef
200
201 """
202
203 def hash_then_or(hash_name: str) -> chain[str]:
204 # For now, all the decent hashes have 6-char names, so we can get
205 # away with hard-coding space literals.
206 return chain([hash_name], repeat(" or"))
207
208 lines: list[str] = []
209 for hash_name, expecteds in self.allowed.items():
210 prefix = hash_then_or(hash_name)
211 lines.extend((f" Expected {next(prefix)} {e}") for e in expecteds)
212 lines.append(
213 f" Got {self.gots[hash_name].hexdigest()}\n"
214 )
215 return "\n".join(lines)