| 1 |
# Wrapper class for in-toto attestation SCAI predicate protos. |
| 2 |
|
| 3 |
import in_toto_attestation.predicates.scai.v0.scai_pb2 as scaipb |
| 4 |
from in_toto_attestation.v1.resource_descriptor import ResourceDescriptor |
| 5 |
|
| 6 |
SCAI_PREDICATE_TYPE = "https://in-toto.io/attestation/scai/" |
| 7 |
SCAI_PREDICATE_VERSION = "v0.3" |
| 8 |
|
| 9 |
|
| 10 |
class AttributeAssertion: |
| 11 |
def __init__(self, attribute, target=None, conditions=None, evidence=None) -> None: |
| 12 |
self.pb = scaipb.AttributeAssertion() # type: ignore[attr-defined] |
| 13 |
self.pb.attribute = attribute |
| 14 |
if target: |
| 15 |
self.pb.target.CopyFrom(target) |
| 16 |
if conditions: |
| 17 |
self.pb.conditions.update(conditions) |
| 18 |
if evidence: |
| 19 |
self.pb.evidence.CopyFrom(evidence) |
| 20 |
|
| 21 |
@staticmethod |
| 22 |
def copy_from_pb(proto: type[scaipb.AttributeAssertion]) -> "AttributeAssertion": # type: ignore[name-defined] |
| 23 |
assertion = AttributeAssertion("tmp-attr") |
| 24 |
assertion.pb.CopyFrom(proto) |
| 25 |
return assertion |
| 26 |
|
| 27 |
def validate(self) -> None: |
| 28 |
if len(self.pb.attribute) == 0: |
| 29 |
raise ValueError("The attribute field is required") |
| 30 |
|
| 31 |
# check any resource descriptors are valid |
| 32 |
if self.pb.target.ByteSize() > 0: |
| 33 |
rd = ResourceDescriptor.copy_from_pb(self.pb.target) |
| 34 |
rd.validate() |
| 35 |
|
| 36 |
if self.pb.evidence.ByteSize() > 0: |
| 37 |
rd = ResourceDescriptor.copy_from_pb(self.pb.evidence) |
| 38 |
rd.validate() |
| 39 |
|
| 40 |
|
| 41 |
class AttributeReport: |
| 42 |
def __init__(self, attributes: list, producer=None) -> None: |
| 43 |
self.pb = scaipb.AttributeReport() # type: ignore[attr-defined] |
| 44 |
self.pb.attributes.extend(attributes) |
| 45 |
if producer: |
| 46 |
self.pb.producer.CopyFrom(producer) |
| 47 |
|
| 48 |
@staticmethod |
| 49 |
def copy_from_pb(proto: type[scaipb.AttributeReport]) -> "AttributeReport": # type: ignore[name-defined] |
| 50 |
report = AttributeReport([None]) |
| 51 |
report.pb.CopyFrom(proto) |
| 52 |
return report |
| 53 |
|
| 54 |
def validate(self) -> None: |
| 55 |
if len(self.pb.attributes) == 0: |
| 56 |
raise ValueError("The attributes field is required") |
| 57 |
|
| 58 |
# check any attribute assertions are valid |
| 59 |
attributes = self.pb.attributes |
| 60 |
for i, attrpb in enumerate(attributes): |
| 61 |
assertion = AttributeAssertion.copy_from_pb(attrpb) |
| 62 |
|
| 63 |
try: |
| 64 |
assertion.validate() |
| 65 |
except ValueError as e: |
| 66 |
# return index in the attributes list in case of failure: |
| 67 |
# can't assume any other fields in attribute assertion are set |
| 68 |
raise ValueError(f"Invalid attributes field (index: {i})") from e |
| 69 |
|
| 70 |
if self.pb.producer.ByteSize() > 0: |
| 71 |
rd = ResourceDescriptor.copy_from_pb(self.pb.producer) |
| 72 |
rd.validate() |