| 1 |
# Copyright New York University and the in-toto contributors |
| 2 |
# SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
""" |
| 5 |
<Program Name> |
| 6 |
common.py |
| 7 |
|
| 8 |
<Author> |
| 9 |
Lukas Puehringer <[email protected]> |
| 10 |
Santiago Torres <[email protected]> |
| 11 |
|
| 12 |
<Started> |
| 13 |
Sep 23, 2016 |
| 14 |
|
| 15 |
<Copyright> |
| 16 |
See LICENSE for licensing information. |
| 17 |
|
| 18 |
<Purpose> |
| 19 |
Provides base classes for various classes in the model. |
| 20 |
|
| 21 |
""" |
| 22 |
|
| 23 |
import inspect |
| 24 |
import json |
| 25 |
|
| 26 |
import attr |
| 27 |
import securesystemslib.formats |
| 28 |
|
| 29 |
|
| 30 |
class ValidationMixin(object): |
| 31 |
"""The validation mixin provides a self-inspecting method, validate, to |
| 32 |
allow in-toto's objects to check that they are proper.""" |
| 33 |
|
| 34 |
def validate(self): |
| 35 |
"""Validates attributes of the instance. |
| 36 |
|
| 37 |
Raises: |
| 38 |
securesystemslib.formats.FormatError: An attribute value is invalid. |
| 39 |
|
| 40 |
""" |
| 41 |
for method in inspect.getmembers(self, predicate=inspect.ismethod): |
| 42 |
if method[0].startswith("_validate_"): |
| 43 |
method[1]() |
| 44 |
|
| 45 |
|
| 46 |
@attr.s(repr=False, init=False) |
| 47 |
class Signable(ValidationMixin): |
| 48 |
"""Objects with base class Signable are to be included in a Metablock class |
| 49 |
to be signed (hence the name). They provide a `signable_bytes` property |
| 50 |
used to create deterministic signatures.""" |
| 51 |
|
| 52 |
def __repr__(self): |
| 53 |
"""Returns an indented JSON string of the metadata object.""" |
| 54 |
return json.dumps( |
| 55 |
attr.asdict(self), indent=1, separators=(",", ": "), sort_keys=True |
| 56 |
) |
| 57 |
|
| 58 |
@property |
| 59 |
def signable_bytes(self): |
| 60 |
"""The UTF-8 encoded canonical JSON byte representation of the dictionary |
| 61 |
representation of the instance.""" |
| 62 |
return securesystemslib.formats.encode_canonical( |
| 63 |
attr.asdict(self) |
| 64 |
).encode("UTF-8") |