Debian Codegraph @

in_toto/resolver/_resolver.py

raw
1 """Resolver interface and default file resolver implementation. """
2 import logging
3 import os
4 from abc import ABCMeta, abstractmethod
5 from itertools import combinations
6 from os.path import exists, isdir, isfile, join, normpath
7
8 from pathspec import GitIgnoreSpec
9 from securesystemslib.hash import digest_filename
10
11 from in_toto.exceptions import PrefixError
12
13 logger = logging.getLogger(__name__)
14
15 _HASH_ALGORITHM = "sha256"
16
17 RESOLVER_FOR_URI_SCHEME = {}
18
19
20 class Resolver(metaclass=ABCMeta):
21 """Resolver interface and factory."""
22
23 @classmethod
24 def for_uri(cls, uri):
25 """Return registered resolver instance for passed URI."""
26 scheme, match, _ = uri.partition(":")
27
28 if not match or scheme not in RESOLVER_FOR_URI_SCHEME:
29 scheme = FileResolver.SCHEME
30
31 return RESOLVER_FOR_URI_SCHEME[scheme]
32
33 @abstractmethod
34 def hash_artifacts(self, uris):
35 """Return hash dictionary for passed list of artifact URIs."""
36 raise NotImplementedError
37
38
39 class FileResolver(Resolver):
40 """File resolver implementation.
41
42 Provides a ``hash_artifacts`` method to generate hashes for passed file
43 paths. The resolver is configurable via its constructor.
44
45 """
46
47 SCHEME = "file"
48
49 def __init__(
50 self,
51 exclude_patterns=None,
52 base_path=None,
53 follow_symlink_dirs=False,
54 normalize_line_endings=False,
55 lstrip_paths=None,
56 ):
57 if exclude_patterns is None:
58 exclude_patterns = []
59
60 if not lstrip_paths:
61 lstrip_paths = []
62
63 if base_path is not None:
64 if not isinstance(base_path, str):
65 raise ValueError("'base_path' must be string")
66
67 for name, val in [
68 ("exclude_patterns", exclude_patterns),
69 ("lstrip_paths", lstrip_paths),
70 ]:
71 if not isinstance(val, list) or not all(
72 isinstance(i, str) for i in val
73 ):
74 raise ValueError(f"'{name}' must be list of strings")
75
76 for _a, _b in combinations(lstrip_paths, 2):
77 if _a.startswith(_b) or _b.startswith(_a):
78 raise PrefixError(
79 f"'{_a}' and '{_b}' triggered a left substring error"
80 )
81
82 # Compile gitignore-style patterns
83 self._exclude_filter = GitIgnoreSpec.from_lines(
84 "gitwildmatch", exclude_patterns
85 )
86 self._base_path = base_path
87 self._follow_symlink_dirs = follow_symlink_dirs
88 self._normalize_line_endings = normalize_line_endings
89 self._lstrip_paths = lstrip_paths
90
91 def _exclude(self, path):
92 """Helper to check, if path matches pre-compiled exclude patterns."""
93 return self._exclude_filter.match_file(path)
94
95 def _hash(self, path):
96 """Helper to generate hash dictionary for path."""
97 digest = digest_filename(
98 path,
99 algorithm=_HASH_ALGORITHM,
100 normalize_line_endings=self._normalize_line_endings,
101 )
102 return {_HASH_ALGORITHM: digest.hexdigest()}
103
104 def _mangle(self, path, existing_paths, scheme_prefix):
105 """Helper for path mangling."""
106
107 # Normalize slashes for cross-platform metadata consistency
108 path = path.replace("\\", "/")
109
110 # Left-strip names using configured path prefixes
111 for lstrip_path in self._lstrip_paths:
112 if path.startswith(lstrip_path):
113 path = path[len(lstrip_path) :]
114 break
115
116 # Fail if left-stripping above results in duplicates
117 if self._lstrip_paths and path in existing_paths:
118 raise PrefixError(
119 "Prefix selection has resulted in non unique dictionary key "
120 f"'{path}'"
121 )
122
123 # Prepend passed scheme prefix
124 path = scheme_prefix + path
125
126 return path
127
128 def _strip_scheme_prefix(self, path):
129 """Helper to strip file resolver scheme prefix from path."""
130
131 prefix = self.SCHEME + ":"
132 if path.startswith(prefix):
133 path = path[len(prefix) :]
134 else:
135 prefix = ""
136
137 return path, prefix
138
139 def hash_artifacts(self, uris):
140 hashes = {}
141
142 if self._base_path:
143 original_cwd = os.getcwd()
144 os.chdir(self._base_path)
145
146 for path in uris:
147 # Remove scheme prefix, but preserver to re-add later (see _mangle)
148 path, prefix = self._strip_scheme_prefix(path)
149
150 # Normalize URI before filtering and returning them
151 # FIXME: Is this expected behavior? Does this make exclude patterns
152 # with slashes platform-dependent? Check how 'gitwildmatch' treats
153 # dots and slashes!
154 path = normpath(path)
155
156 if self._exclude(path):
157 continue
158
159 if not exists(path):
160 logger.info("path: %s does not exist, skipping..", path)
161 continue
162
163 if isfile(path):
164 _name = self._mangle(path, hashes, prefix)
165 _hashes = self._hash(path)
166 hashes[_name] = _hashes
167
168 if isdir(path):
169 for base, dirs, names in os.walk(
170 path, followlinks=self._follow_symlink_dirs
171 ):
172 # Filter directories to avoid unnecessary recursion below
173 # NOTE: Normalize to filter on directory paths without
174 # their dot-slash prefix, if path was dot.
175 dirs[:] = [
176 dirname
177 for dirname in dirs
178 if not self._exclude(normpath(join(base, dirname)))
179 ]
180
181 for filename in names:
182 # NOTE: Normalize to filter on and return file paths
183 # without their dot-slash prefix, if path was dot.
184 filepath = normpath(join(base, filename))
185
186 if self._exclude(filepath):
187 continue
188
189 if not isfile(filepath):
190 logger.info(
191 "File '%s' appears to be a broken symlink. "
192 "Skipping...",
193 filepath,
194 )
195 continue
196
197 _name = self._mangle(filepath, hashes, prefix)
198 _hashes = self._hash(filepath)
199 hashes[_name] = _hashes
200
201 # Change back to original current working dir
202 if self._base_path:
203 os.chdir(original_cwd)
204
205 return hashes
206
207
208 class OSTreeResolver(Resolver):
209 """Resolver for OSTree repositories."""
210
211 SCHEME = "ostree"
212
213 # defining this separately as it should be pinned to OSTree's default
214 # rather than in-toto's
215 _HASH_ALGORITHM = "sha256"
216
217 def __init__(self, base_path=None):
218 self._base_path = base_path
219
220 def _strip_scheme_prefix(self, path):
221 """Helper to strip OSTree resolver scheme prefix from path."""
222
223 return path[len(self.SCHEME + ":") :]
224
225 def _add_scheme_prefix(self, path):
226 """Helper to add scheme back after recording the hash."""
227
228 return f"{self.SCHEME}:{path}"
229
230 def _hash(self, path):
231 """Helper to hash OSTree commits."""
232
233 ref_path = os.path.join("refs", "heads", path)
234
235 with open(ref_path, "r") as ref: # pylint: disable=unspecified-encoding
236 ref_contents = ref.read()
237 ref_contents = ref_contents.strip("\n")
238
239 object_path = os.path.join(
240 "objects", ref_contents[:2], f"{ref_contents[2:]}.commit"
241 )
242
243 digest = digest_filename(object_path, algorithm=self._HASH_ALGORITHM)
244
245 return {self._HASH_ALGORITHM: digest.hexdigest()}
246
247 def hash_artifacts(self, uris):
248 hashes = {}
249
250 if self._base_path:
251 original_cwd = os.getcwd()
252 os.chdir(self._base_path)
253
254 for path in uris:
255 # Remove scheme prefix, but preserver to re-add later
256 path = self._strip_scheme_prefix(path)
257 _hashes = self._hash(path)
258 hashes[self._add_scheme_prefix(path)] = _hashes
259
260 # Change back to original current working dir
261 if self._base_path:
262 os.chdir(original_cwd)
263
264 return hashes