Debian Codegraph @

in_toto/models/layout.py

raw
1 #!/usr/bin/env python
2
3 # Copyright New York University and the in-toto contributors
4 # SPDX-License-Identifier: Apache-2.0
5
6 """
7 <Program Name>
8 layout.py
9
10 <Author>
11 Lukas Puehringer <[email protected]>
12 Santiago Torres <[email protected]>
13
14 <Started>
15 Sep 23, 2016
16
17 <Copyright>
18 See LICENSE for licensing information.
19
20 <Purpose>
21 Provides classes related to the definition of a software supply chain.
22
23 <Classes>
24 Layout:
25 represents the metadata file that defines a software supply chain through
26 steps and inspections
27
28 Step:
29 represents one step of the software supply chain, performed by one or
30 many functionaries, who are identified by a key also stored to the layout
31
32 Inspection:
33 represents a hook that is run at verification
34 """
35 import json
36 import shlex
37 from datetime import datetime
38
39 import attr
40 import securesystemslib.exceptions
41 import securesystemslib.formats
42 import securesystemslib.gpg.functions
43 import securesystemslib.interface
44 import securesystemslib.schema
45 from dateutil.parser import parse
46 from dateutil.relativedelta import relativedelta
47
48 import in_toto.exceptions
49 import in_toto.rulelib
50 from in_toto.models.common import Signable, ValidationMixin
51
52 # Link metadata for sublayouts are expected to be found in a subdirectory
53 # with the following name, relative to the verification directory
54 SUBLAYOUT_LINK_DIR_FORMAT = "{name}.{keyid:.8}"
55
56
57 @attr.s(repr=False, init=False)
58 class Layout(Signable):
59 """A definition for a software supply chain.
60
61 A layout lists the sequence of steps of the software supply chain in the
62 order they are expected to be performed, the functionaries authorized and
63 required to perform them, and inspections to be performed by the client upon
64 final product verification.
65
66 A Layout object is usually contained in a generic Metablock object for
67 signing, serialization and I/O capabilities.
68
69 Attributes:
70 steps: A list of Step objects.
71
72 inspect: A list of Inspection objects.
73
74 keys: A dictionary of functionary public keys, with keyids as dict keys and
75 keys as values.
76
77 expires: The layout expiration.
78
79 readme: A human readable description of the software supply chain.
80
81 """
82
83 _type = attr.ib()
84 steps = attr.ib()
85 inspect = attr.ib()
86 keys = attr.ib()
87 expires = attr.ib()
88 readme = attr.ib()
89
90 def __init__(self, **kwargs):
91 super(Layout, self).__init__()
92 self._type = "layout"
93 self.steps = kwargs.get("steps", [])
94 self.inspect = kwargs.get("inspect", [])
95 self.keys = kwargs.get("keys", {})
96 self.readme = kwargs.get("readme", "")
97
98 # Assign a default expiration (one month) if not expiration date is passed
99 # TODO: Is one month a sensible default? In any case, we need a valid
100 # expiration date in order for the layout object to validate.
101 # (see self._validate_expires)
102 self.expires = kwargs.get("expires")
103 if not self.expires:
104 self.set_relative_expiration(months=1)
105
106 # TODO: Should we validate in the constructor or allow the user to create
107 # an invalid layout and call validate explicitly?
108 self.validate()
109
110 @property
111 def type_(self):
112 """The string "layout" to indentify the in-toto metadata type."""
113 # NOTE: We expose the type_ property in the API documentation instead of
114 # _type to protect it against modification.
115 # NOTE: Trailing underscore is used by convention (pep8) to avoid conflict
116 # with Python's type keyword.
117 return self._type
118
119 @staticmethod
120 def read(data):
121 """Creates a Layout object from its dictionary representation.
122
123 Arguments:
124 data: A dictionary with layout metadata fields.
125
126 Raises:
127 securesystemslib.exceptions.FormatError: Passed data is invalid.
128
129 Returns:
130 The created Layout object.
131
132 """
133 steps = []
134
135 for step_data in data.get("steps"):
136 steps.append(Step.read(step_data))
137 data["steps"] = steps
138
139 inspections = []
140 for inspect_data in data.get("inspect"):
141 inspections.append(Inspection.read(inspect_data))
142 data["inspect"] = inspections
143
144 return Layout(**data)
145
146 def set_relative_expiration(self, days=0, months=0, years=0):
147 """Sets layout expiration relative to today.
148
149 If not argument is passed the set exipration date is now.
150
151 Arguments:
152 days (optional): Days from today.
153 months (optional): Months from today.
154 years (optional): Years from today.
155
156 Raises:
157 securesystemslib.exceptions.FormatError: Arguments are not ints.
158
159 """
160 securesystemslib.schema.Integer().check_match(days)
161 securesystemslib.schema.Integer().check_match(months)
162 securesystemslib.schema.Integer().check_match(years)
163
164 self.expires = (
165 datetime.today()
166 + relativedelta(days=days, months=months, years=years)
167 ).strftime("%Y-%m-%dT%H:%M:%SZ")
168
169 def get_step_name_list(self):
170 """Returns ordered list of step names as they appear in the layout.
171
172 Returns:
173 A list of step names.
174
175 """
176 step_names = []
177 for step in self.steps:
178 step_names.append(step.name)
179
180 return step_names
181
182 def get_step_by_name(self, step_name):
183 """Returns step identified by step_name from the layout.
184
185 NOTE: Returns the first step identified only, which should be the only step
186 for a given name of a valid layout.
187
188 Arguments:
189 step_name: A step name.
190
191 Raises:
192 securesystemslib.exceptions.FormatError: Argument is not a string.
193
194 Returns:
195 A Step object.
196
197 """
198 securesystemslib.schema.AnyString().check_match(step_name)
199
200 for step in self.steps: # pragma: no branch
201 if step.name == step_name:
202 return step
203
204 def remove_step_by_name(self, step_name):
205 """Removes steps identified by step_name from the layout.
206
207 NOTE: Removes all steps identified, which should be only one step for a
208 given name of a valid layout.
209
210 Arguments:
211 step_name: A step name.
212
213 Raises:
214 securesystemslib.exceptions.FormatError: Argument is not a string.
215
216 """
217 securesystemslib.schema.AnyString().check_match(step_name)
218
219 for step in self.steps:
220 if step.name == step_name:
221 self.steps.remove(step)
222
223 def get_inspection_name_list(self):
224 """Returns ordered list of inspection names as they appear in the layout.
225
226 Returns:
227 A list of inspection names.
228
229 """
230 inspection_names = []
231 for inspection in self.inspect:
232 inspection_names.append(inspection.name)
233
234 return inspection_names
235
236 def get_inspection_by_name(self, inspection_name):
237 """Returns inspection identified by inspection_names from the layout.
238
239 NOTE: Returns the first inspection identified only, which should be the
240 only inspection for a given name of a valid layout.
241
242 Arguments:
243 inspection_name: An inspection name.
244
245 Raises:
246 securesystemslib.exceptions.FormatError: Argument is not a string.
247
248 Returns:
249 An Inspection object.
250
251 """
252 securesystemslib.schema.AnyString().check_match(inspection_name)
253
254 for inspection in self.inspect: # pragma: no branch
255 if inspection.name == inspection_name:
256 return inspection
257
258 def remove_inspection_by_name(self, inspection_name):
259 """Removes inspections identified by inspection_name from the layout.
260
261 NOTE: Removes all inspections identified, which should be only one
262 inspection for a given name of a valid layout.
263
264 Arguments:
265 inspection_name: An inspection name.
266
267 Raises:
268 securesystemslib.exceptions.FormatError: Argument is not a string.
269
270 """
271 securesystemslib.schema.AnyString().check_match(inspection_name)
272
273 for inspection in self.inspect:
274 if inspection.name == inspection_name:
275 self.inspect.remove(inspection)
276
277 def get_functionary_key_id_list(self):
278 """Returns list of functionary keyids from the layout.
279
280 Returns:
281 A list of keyids.
282
283 """
284 return list(self.keys.keys())
285
286 def add_functionary_key(self, key):
287 """Adds key as functionary key to layout.
288
289 Arguments:
290 key: A public key. Format is securesystemslib.formats.ANY_PUBKEY_SCHEMA.
291
292 Raises:
293 securesystemslib.exceptions.FormatError: Argument is malformed.
294
295 Returns:
296 The added key.
297
298 """
299 securesystemslib.formats.ANY_PUBKEY_SCHEMA.check_match(key)
300 keyid = key["keyid"]
301 self.keys[keyid] = key
302 return key
303
304 def add_functionary_key_from_path(self, key_path):
305 """Loads key from disk and adds as functionary key to layout.
306
307 Arguments:
308 key_path: A path to a PEM-formatted RSA public key. Format is
309 securesystemslib.formats.PATH_SCHEMA.
310
311 Raises:
312 securesystemslib.exceptions.FormatError: Argument is malformed.
313 securesystemslib.exceptions.Error: Key cannot be imported.
314
315 Returns:
316 The added functionary public key.
317
318 """
319 securesystemslib.formats.PATH_SCHEMA.check_match(key_path)
320 key = securesystemslib.interface.import_rsa_publickey_from_file(
321 key_path
322 )
323
324 return self.add_functionary_key(key)
325
326 def add_functionary_key_from_gpg_keyid(self, gpg_keyid, gpg_home=None):
327 """Loads key from gpg keychain and adds as functionary key to layout.
328
329 Arguments:
330 gpg_keyid: A keyid used to identify a local gpg public key.
331 gpg_home (optional): A path to the gpg home directory. If not set the
332 default gpg home directory is used.
333
334 Raises:
335 securesystemslib.exceptions.FormatError: Arguments are malformed.
336 securesystemslib.gpg.execeptions.KeyNotFoundError: Key cannot be found.
337
338 Side Effects:
339 Calls system gpg command in a subprocess.
340
341 Returns:
342 The added key.
343
344 """
345 securesystemslib.formats.KEYID_SCHEMA.check_match(gpg_keyid)
346 if gpg_home: # pragma: no branch
347 securesystemslib.formats.PATH_SCHEMA.check_match(gpg_home)
348
349 key = securesystemslib.gpg.functions.export_pubkey(
350 gpg_keyid, homedir=gpg_home
351 )
352 return self.add_functionary_key(key)
353
354 def add_functionary_keys_from_paths(self, key_path_list):
355 """Loads keys from disk and adds as functionary keys to layout.
356
357 Arguments:
358 key_path_list: A list of paths to PEM-formatted RSA public keys. Format
359 of each path is securesystemslib.formats.PATH_SCHEMA.
360
361 Raises:
362 securesystemslib.exceptions.FormatError: Argument is malformed.
363 securesystemslib.exceptions.Error: A key cannot be imported.
364
365 Returns:
366 A dictionary of the added functionary keys, with keyids as dictionary
367 keys and keys as values.
368
369 """
370 securesystemslib.formats.PATHS_SCHEMA.check_match(key_path_list)
371 key_dict = {}
372 for key_path in key_path_list:
373 key = self.add_functionary_key_from_path(key_path)
374 key_dict[key["keyid"]] = key
375
376 return key_dict
377
378 def add_functionary_keys_from_gpg_keyids(
379 self, gpg_keyid_list, gpg_home=None
380 ):
381 """Loads keys from gpg keychain and adds as functionary keys to layout.
382
383 Arguments:
384 gpg_keyid_list: A list of keyids used to identify local gpg public keys.
385 gpg_home (optional): A path to the gpg home directory. If not set the
386 default gpg home directory is used.
387
388 Raises:
389 securesystemslib.exceptions.FormatError: Arguments are malformed.
390 securesystemslib.gpg.execeptions.KeyNotFoundError: A key cannot be found.
391
392 Side Effects:
393 Calls system gpg command in a subprocess.
394
395 Returns:
396 A dictionary of the added functionary keys, with keyids as dictionary
397 keys and keys as values.
398
399 """
400 securesystemslib.formats.KEYIDS_SCHEMA.check_match(gpg_keyid_list)
401 key_dict = {}
402 for gpg_keyid in gpg_keyid_list:
403 key = self.add_functionary_key_from_gpg_keyid(gpg_keyid, gpg_home)
404 key_dict[key["keyid"]] = key
405
406 return key_dict
407
408 def _validate_type(self):
409 """Private method to check that the type string is set to layout."""
410 if self._type != "layout":
411 raise securesystemslib.exceptions.FormatError(
412 "Invalid _type value for layout (Should be 'layout')"
413 )
414
415 def _validate_expires(self):
416 """Private method to verify if the expiration field has the right format
417 and can be parsed."""
418 try:
419 # We do both 'parse' and 'check_match' because the format check does not
420 # detect bogus dates (e.g. Jan 35th) and parse can do more formats.
421 parse(self.expires)
422 securesystemslib.formats.ISO8601_DATETIME_SCHEMA.check_match(
423 self.expires
424 )
425 except Exception as e:
426 raise securesystemslib.exceptions.FormatError(
427 "Malformed date string in layout. Exception: {}".format(e)
428 )
429
430 def _validate_readme(self):
431 """Private method to check that the readme field is a string."""
432 if not isinstance(self.readme, str):
433 raise securesystemslib.exceptions.FormatError(
434 "Invalid readme '{}', value must be a string.".format(
435 self.readme
436 )
437 )
438
439 def _validate_keys(self):
440 """Private method to ensure that the keys contained are right."""
441 securesystemslib.formats.ANY_PUBKEY_DICT_SCHEMA.check_match(self.keys)
442
443 def _validate_steps_and_inspections(self):
444 """Private method to verify that the list of steps and inspections are
445 correctly formed."""
446 names_seen = set()
447 if not isinstance(self.steps, list):
448 raise securesystemslib.exceptions.FormatError(
449 "The steps field should be a list!"
450 )
451
452 for step in self.steps:
453 if not isinstance(step, Step):
454 raise securesystemslib.exceptions.FormatError(
455 "The steps list should only contain steps!"
456 )
457
458 step.validate()
459
460 if step.name in names_seen:
461 raise securesystemslib.exceptions.FormatError(
462 "There is already a step with name '{}'. Step names must be"
463 " unique within a layout.".format(step.name)
464 )
465 names_seen.add(step.name)
466
467 if not isinstance(self.inspect, list):
468 raise securesystemslib.exceptions.FormatError(
469 "The inspect field should a be a list!"
470 )
471
472 for inspection in self.inspect:
473 if not isinstance(inspection, Inspection):
474 raise securesystemslib.exceptions.FormatError(
475 "The inspect list should only contain inspections!"
476 )
477
478 inspection.validate()
479
480 if inspection.name in names_seen:
481 raise securesystemslib.exceptions.FormatError(
482 "There is already an inspection with name '{}'. Inspection names"
483 " must be unique within a layout.".format(inspection.name)
484 )
485 names_seen.add(inspection.name)
486
487
488 @attr.s(repr=False, init=False)
489 class SupplyChainItem(ValidationMixin):
490 """Common attributes and methods for supply chain steps and inspections.
491
492 Attributes:
493 name: A unique named used to associate related link metadata.
494
495 expected_materials: A list of rules to encode expectations about used
496 artifacts (see ``rulelib`` for formats).
497
498 expected_products: A list of rules to encode expectations about produced
499 artifacts (see ``rulelib`` for formats).
500
501 """
502
503 name = attr.ib()
504 expected_materials = attr.ib()
505 expected_products = attr.ib()
506
507 def __init__(self, **kwargs):
508 super(SupplyChainItem, self).__init__()
509 self.name = kwargs.get("name")
510 self.expected_materials = kwargs.get("expected_materials", [])
511 self.expected_products = kwargs.get("expected_products", [])
512
513 def __repr__(self):
514 """Returns an indented JSON string of the metadata object."""
515 return json.dumps(
516 attr.asdict(self), indent=1, separators=(",", ": "), sort_keys=True
517 )
518
519 def add_material_rule_from_string(self, rule_string):
520 """Parse artifact rule string as list and add to expected_materials.
521
522 Arguments:
523 rule_string: An artifact rule string (see ``rulelib`` for formats).
524
525 Raises:
526 securesystemslib.exceptions.FormatError: Argument is malformed.
527
528 """
529 securesystemslib.schema.AnyString().check_match(rule_string)
530 rule_list = shlex.split(rule_string)
531
532 # Raises format error if the parsed rule_string is not a valid rule
533 in_toto.rulelib.unpack_rule(rule_list)
534
535 self.expected_materials.append(rule_list)
536
537 def add_product_rule_from_string(self, rule_string):
538 """Parse artifact rule string as list and add to expected_products.
539
540 Arguments:
541 rule_string: An artifact rule string (see ``rulelib`` for formats).
542
543 Raises:
544 securesystemslib.exceptions.FormatError: Argument is malformed.
545
546 """
547 securesystemslib.schema.AnyString().check_match(rule_string)
548 rule_list = shlex.split(rule_string)
549
550 # Raises format error if the parsed rule_string is not a valid rule
551 in_toto.rulelib.unpack_rule(rule_list)
552
553 self.expected_products.append(rule_list)
554
555 def _validate_expected_materials(self):
556 """Private method to check that material rules are correctly formed."""
557 if not isinstance(self.expected_materials, list):
558 raise securesystemslib.exceptions.FormatError(
559 "Material rules should be a list!"
560 )
561
562 for rule in self.expected_materials:
563 in_toto.rulelib.unpack_rule(rule)
564
565 def _validate_expected_products(self):
566 """Private method to check that product rules are correctly formed."""
567 if not isinstance(self.expected_products, list):
568 raise securesystemslib.exceptions.FormatError(
569 "Product rules should be a list!"
570 )
571
572 for rule in self.expected_products:
573 in_toto.rulelib.unpack_rule(rule)
574
575
576 @attr.s(repr=False, init=False)
577 class Step(SupplyChainItem):
578 """A step of a software supply chain.
579
580 A Step object is usually contained in a Layout object and encodes the
581 expectations for a step of the software supply chain such as, who is
582 authorized to perform the step, what command is executed, and which artifacts
583 are used and produced. Evidence about a performed step is provided by link
584 metadata.
585
586 Attributes:
587 pubkeys: A list of functionary keyids authorized to perform the step.
588
589 threshold: A minimum number of distinct functionaries required to provide
590 evidence for a step.
591
592 expected_command: A list of command and command arguments, expected to
593 perform the step.
594
595 """
596
597 _type = attr.ib()
598 pubkeys = attr.ib()
599 expected_command = attr.ib()
600 threshold = attr.ib()
601
602 def __init__(self, **kwargs):
603 super(Step, self).__init__(**kwargs)
604 self._type = "step"
605 self.pubkeys = kwargs.get("pubkeys", [])
606 self.expected_command = kwargs.get("expected_command", [])
607 self.threshold = kwargs.get("threshold", 1)
608
609 self.validate()
610
611 @staticmethod
612 def read(data):
613 """Creates a Step object from its dictionary representation.
614
615 Arguments:
616 data: A dictionary with step metadata fields.
617
618 Raises:
619 securesystemslib.exceptions.FormatError: Passed data is invalid.
620
621 Returns:
622 The created Step object.
623
624 """
625 return Step(**data)
626
627 def set_expected_command_from_string(self, command_string):
628 """Parse command string as list and assign to expected_command.
629
630 Arguments:
631 command_string: A command and command arguments string.
632
633 Raises:
634 securesystemslib.exceptions.FormatError: Argument is malformed.
635
636 """
637 securesystemslib.schema.AnyString().check_match(command_string)
638 self.expected_command = shlex.split(command_string)
639
640 def _validate_type(self):
641 """Private method to ensure that the type field is set to step."""
642 if self._type != "step":
643 raise securesystemslib.exceptions.FormatError(
644 "Invalid _type value for step (Should be 'step')"
645 )
646
647 def _validate_threshold(self):
648 """Private method to check that the threshold field is set to an int."""
649 if not isinstance(self.threshold, int):
650 raise securesystemslib.exceptions.FormatError(
651 "Invalid threshold '{}', value must be an int.".format(
652 self.threshold
653 )
654 )
655
656 def _validate_pubkeys(self):
657 """Private method to check that the pubkeys is a list of keyids."""
658 if not isinstance(self.pubkeys, list):
659 raise securesystemslib.exceptions.FormatError(
660 "The pubkeys field should be a list!"
661 )
662
663 for keyid in self.pubkeys:
664 securesystemslib.formats.KEYID_SCHEMA.check_match(keyid)
665
666 def _validate_expected_command(self):
667 """Private method to check that the expected_command is proper."""
668 if not isinstance(self.expected_command, list):
669 raise securesystemslib.exceptions.FormatError(
670 "The expected command field is malformed!"
671 )
672
673
674 @attr.s(repr=False, init=False)
675 class Inspection(SupplyChainItem):
676 """An inspection for a software supply chain.
677
678 An Inspection object is usually contained in a Layout object and encodes a
679 command to be executed by an in-toto client during final product
680 verification. Akin to steps, inspections can define artifact rules.
681
682 Attributes:
683 run: A list of command and command arguments to be executed upon final
684 product verification.
685
686 """
687
688 _type = attr.ib()
689 run = attr.ib()
690
691 def __init__(self, **kwargs):
692 super(Inspection, self).__init__(**kwargs)
693 self._type = "inspection"
694 self.run = kwargs.get("run", [])
695
696 self.validate()
697
698 @staticmethod
699 def read(data):
700 """Creates an Inspection object from its dictionary representation.
701
702 Arguments:
703 data: A dictionary with inspection metadata fields.
704
705 Raises:
706 securesystemslib.exceptions.FormatError: Passed data is invalid.
707
708 Returns:
709 The created Inspection object.
710
711 """
712 return Inspection(**data)
713
714 def set_run_from_string(self, command_string):
715 """Parse command string as list and assign to run attribute.
716
717 Arguments:
718 command_string: A command and command arguments string.
719
720 Raises:
721 securesystemslib.exceptions.FormatError: Argument is malformed.
722
723 """
724 securesystemslib.schema.AnyString().check_match(command_string)
725 self.run = shlex.split(command_string)
726
727 def _validate_type(self):
728 """Private method to ensure that the type field is set to inspection."""
729 if self._type != "inspection":
730 raise securesystemslib.exceptions.FormatError(
731 "The _type field must be set to 'inspection'!"
732 )
733
734 def _validate_run(self):
735 """Private method to check that the expected command is correct."""
736 if not isinstance(self.run, list):
737 raise securesystemslib.exceptions.FormatError(
738 "The run field is malformed!"
739 )