Skip to content

Commit b422afe

Browse files
author
Lukas Puehringer
committed
Envelope API: add dsse equivalent for Metadata API
Add Envelope class with basic de/serialization methods, currently hardcoded to JSON. Signed-off-by: Lukas Puehringer <lukas.puehringer@nyu.edu>
1 parent cb9aa4a commit b422afe

1 file changed

Lines changed: 96 additions & 0 deletions

File tree

tuf/api/dsse.py

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
"""Low-level TUF Envelope API.
2+
3+
"""
4+
import json
5+
from typing import Generic, Type, cast
6+
7+
from securesystemslib.dsse import Envelope as BaseEnvelope
8+
9+
from tuf.api._payload import ( # noqa: F401
10+
_ROOT,
11+
_SNAPSHOT,
12+
_TARGETS,
13+
_TIMESTAMP,
14+
SPECIFICATION_VERSION,
15+
TOP_LEVEL_ROLE_NAMES,
16+
BaseFile,
17+
DelegatedRole,
18+
Delegations,
19+
MetaFile,
20+
Role,
21+
Root,
22+
RootVerificationResult,
23+
Signed,
24+
Snapshot,
25+
SuccinctRoles,
26+
T,
27+
TargetFile,
28+
Targets,
29+
Timestamp,
30+
VerificationResult,
31+
)
32+
from tuf.api.serialization import DeserializationError, SerializationError
33+
34+
35+
class Envelope(Generic[T], BaseEnvelope):
36+
"""TODO: doc"""
37+
38+
_DEFAULT_PAYLOAD_TYPE = "application/vnd.tuf+json"
39+
40+
@classmethod
41+
def from_bytes(cls, data: bytes) -> "Envelope[T]":
42+
"""TODO: doc"""
43+
try:
44+
envelope_dict = json.loads(data.decode())
45+
envelope = Envelope.from_dict(envelope_dict)
46+
47+
except Exception as e:
48+
raise SerializationError from e
49+
50+
return envelope
51+
52+
def to_bytes(self) -> bytes:
53+
"""TODO: doc"""
54+
try:
55+
envelope_dict = self.to_dict()
56+
json_bytes = json.dumps(envelope_dict).encode()
57+
58+
except Exception as e:
59+
raise SerializationError from e
60+
61+
return json_bytes
62+
63+
@classmethod
64+
def from_signed(cls, signed: T) -> "Envelope[T]":
65+
"""TODO: doc"""
66+
try:
67+
signed_dict = signed.to_dict()
68+
json_bytes = json.dumps(signed_dict).encode()
69+
70+
except Exception as e:
71+
raise SerializationError from e
72+
73+
return cls(json_bytes, cls._DEFAULT_PAYLOAD_TYPE, [])
74+
75+
def get_signed(self) -> T:
76+
"""TODO: doc"""
77+
try:
78+
payload_dict = json.loads(self.payload.decode())
79+
80+
# TODO: can we move this to tuf.api._payload?
81+
_type = payload_dict["_type"]
82+
if _type == _TARGETS:
83+
inner_cls: Type[Signed] = Targets
84+
elif _type == _SNAPSHOT:
85+
inner_cls = Snapshot
86+
elif _type == _TIMESTAMP:
87+
inner_cls = Timestamp
88+
elif _type == _ROOT:
89+
inner_cls = Root
90+
else:
91+
raise ValueError(f'unrecognized metadata type "{_type}"')
92+
93+
except Exception as e:
94+
raise DeserializationError from e
95+
96+
return cast(T, inner_cls.from_dict(payload_dict))

0 commit comments

Comments
 (0)