2021-03-04 15:25:36 +00:00
|
|
|
# Copyright New York University and the TUF contributors
|
|
|
|
|
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
|
|
|
|
2022-12-18 12:28:47 +00:00
|
|
|
"""The low-level Metadata API.
|
|
|
|
|
|
2021-09-23 12:25:47 +00:00
|
|
|
The low-level Metadata API in ``tuf.api.metadata`` module contains:
|
2021-08-23 12:21:36 +00:00
|
|
|
|
|
|
|
|
* Safe de/serialization of metadata to and from files.
|
|
|
|
|
* Access to and modification of signed metadata content.
|
|
|
|
|
* Signing metadata and verifying signatures.
|
|
|
|
|
|
2021-09-23 12:25:47 +00:00
|
|
|
Metadata API implements functionality at the metadata file level, it does
|
|
|
|
|
not provide TUF repository or client functionality on its own (but can be used
|
|
|
|
|
to implement them).
|
2021-08-23 12:21:36 +00:00
|
|
|
|
2021-09-23 12:25:47 +00:00
|
|
|
The API design is based on the file format defined in the `TUF specification
|
|
|
|
|
<https://theupdateframework.github.io/specification/latest/>`_ and the object
|
|
|
|
|
attributes generally follow the JSON format used in the specification.
|
2021-03-05 11:29:57 +00:00
|
|
|
|
2021-09-23 12:25:47 +00:00
|
|
|
The above principle means that a ``Metadata`` object represents a single
|
|
|
|
|
metadata file, and has a ``signed`` attribute that is an instance of one of the
|
2024-03-07 08:05:36 +00:00
|
|
|
four top level signed classes (``Root``, ``Timestamp``, ``Snapshot`` and
|
|
|
|
|
``Targets``). To make Python type annotations useful ``Metadata`` can be
|
|
|
|
|
type constrained: e.g. the signed attribute of ``Metadata[Root]``
|
2024-02-20 05:34:47 +00:00
|
|
|
is known to be ``Root``.
|
Add simple TUF role metadata model (WIP)
Add metadata module with container classes for TUF role metadata, including
methods to read/serialize/write from and to JSON, perform TUF-compliant
metadata updates, and create and verify signatures.
The 'Metadata' class provides a container for inner TUF metadata objects (Root,
Timestamp, Snapshot, Targets) (i.e. OOP composition)
The 'Signed' class provides a base class to aggregate common attributes (i.e.
version, expires, spec_version) of the inner metadata classes. (i.e. OOP
inheritance). The name of the class also aligns with the 'signed' field of
the outer metadata container.
Based on prior observations in TUF's sister project in-toto, this architecture
seems to well represent the metadata model as it is defined in the
specification (see in-toto/in-toto#98 and in-toto/in-toto#142 for related
discussions).
This commits also adds tests.
**TODO: See doc header TODO list**
**Additional design considerations**
(also in regards to prior sketches of this module)
- Aims at simplicity, brevity and recognizability of the wireline metadata
format.
- All attributes that correspond to fields in TUF JSON metadata are public.
There doesn't seem to be a good reason to protect them with leading
underscores and use setters/getters instead, it just adds more code, and
impedes recognizability of the wireline metadata format.
- Although, it might be convenient to have short-cuts on the Metadata class
that point to methods and attributes that are common to all subclasses of
the contained Signed class (e.g. Metadata.version instead of
Metadata.signed.version, etc.), this also conflicts with goal of
recognizability of the wireline metadata. Thus we won't add such short-cuts
for now. See:
https://github.com/theupdateframework/tuf/pull/1060#discussion_r452906629
- Signing keys and a 'consistent_snapshot' boolean are not on the targets
metadata class. They are a better fit for management code. See:
https://github.com/theupdateframework/tuf/pull/1060#issuecomment-660056376,
and #660.
- Does not use sslib schema checks (see TODO notes about validation in
doc header)
- Does not use existing tuf utils, such as make_metadata_fileinfo,
build_dict_conforming_to_schema, if it is easy and more explicit to
just re-implement the desired behavior on the metadata classes.
- All datetime's are treated as UTC. Since timezone info is not captured in
the wireline metadata format it should not be captured in the internal
representation either.
- Does not use 3rd-party dateutil package, in order to minimize dependency
footprint, which is especially important for update clients which often have
to vendor their dependencies.
However, compatibility between the more advanced dateutil.relativedelta (e.g
handles leap years automatically) and timedelta is tested.
- Uses PEP8 indentation (4 space) and Google-style doc string instead of
sslab-style. See
https://github.com/secure-systems-lab/code-style-guidelines/issues/20
- Does not support Python =< 3.5
Co-authored-by: Trishank Karthik Kuppusamy <trishank.kuppusamy@datadoghq.com>
Co-authored-by: Joshua Lock <jlock@vmware.com>
Co-authored-by: Teodora Sechkova <tsechkova@vmware.com>
Signed-off-by: Lukas Puehringer <lukas.puehringer@nyu.edu>
2020-08-18 09:15:49 +00:00
|
|
|
|
2021-09-23 12:25:47 +00:00
|
|
|
Currently Metadata API supports JSON as the file format.
|
2022-01-13 16:51:37 +00:00
|
|
|
|
|
|
|
|
A basic example of repository implementation using the Metadata is available in
|
2024-05-21 11:37:39 +00:00
|
|
|
`examples/repository <https://github.com/theupdateframework/python-tuf/tree/develop/examples/repository>`_.
|
Add simple TUF role metadata model (WIP)
Add metadata module with container classes for TUF role metadata, including
methods to read/serialize/write from and to JSON, perform TUF-compliant
metadata updates, and create and verify signatures.
The 'Metadata' class provides a container for inner TUF metadata objects (Root,
Timestamp, Snapshot, Targets) (i.e. OOP composition)
The 'Signed' class provides a base class to aggregate common attributes (i.e.
version, expires, spec_version) of the inner metadata classes. (i.e. OOP
inheritance). The name of the class also aligns with the 'signed' field of
the outer metadata container.
Based on prior observations in TUF's sister project in-toto, this architecture
seems to well represent the metadata model as it is defined in the
specification (see in-toto/in-toto#98 and in-toto/in-toto#142 for related
discussions).
This commits also adds tests.
**TODO: See doc header TODO list**
**Additional design considerations**
(also in regards to prior sketches of this module)
- Aims at simplicity, brevity and recognizability of the wireline metadata
format.
- All attributes that correspond to fields in TUF JSON metadata are public.
There doesn't seem to be a good reason to protect them with leading
underscores and use setters/getters instead, it just adds more code, and
impedes recognizability of the wireline metadata format.
- Although, it might be convenient to have short-cuts on the Metadata class
that point to methods and attributes that are common to all subclasses of
the contained Signed class (e.g. Metadata.version instead of
Metadata.signed.version, etc.), this also conflicts with goal of
recognizability of the wireline metadata. Thus we won't add such short-cuts
for now. See:
https://github.com/theupdateframework/tuf/pull/1060#discussion_r452906629
- Signing keys and a 'consistent_snapshot' boolean are not on the targets
metadata class. They are a better fit for management code. See:
https://github.com/theupdateframework/tuf/pull/1060#issuecomment-660056376,
and #660.
- Does not use sslib schema checks (see TODO notes about validation in
doc header)
- Does not use existing tuf utils, such as make_metadata_fileinfo,
build_dict_conforming_to_schema, if it is easy and more explicit to
just re-implement the desired behavior on the metadata classes.
- All datetime's are treated as UTC. Since timezone info is not captured in
the wireline metadata format it should not be captured in the internal
representation either.
- Does not use 3rd-party dateutil package, in order to minimize dependency
footprint, which is especially important for update clients which often have
to vendor their dependencies.
However, compatibility between the more advanced dateutil.relativedelta (e.g
handles leap years automatically) and timedelta is tested.
- Uses PEP8 indentation (4 space) and Google-style doc string instead of
sslab-style. See
https://github.com/secure-systems-lab/code-style-guidelines/issues/20
- Does not support Python =< 3.5
Co-authored-by: Trishank Karthik Kuppusamy <trishank.kuppusamy@datadoghq.com>
Co-authored-by: Joshua Lock <jlock@vmware.com>
Co-authored-by: Teodora Sechkova <tsechkova@vmware.com>
Signed-off-by: Lukas Puehringer <lukas.puehringer@nyu.edu>
2020-08-18 09:15:49 +00:00
|
|
|
"""
|
2024-03-07 08:05:36 +00:00
|
|
|
|
2024-11-29 10:29:32 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
2021-06-22 07:10:17 +00:00
|
|
|
import logging
|
2021-03-11 17:00:19 +00:00
|
|
|
import tempfile
|
2024-11-29 10:29:32 +00:00
|
|
|
from typing import TYPE_CHECKING, Any, Generic, cast
|
Add simple TUF role metadata model (WIP)
Add metadata module with container classes for TUF role metadata, including
methods to read/serialize/write from and to JSON, perform TUF-compliant
metadata updates, and create and verify signatures.
The 'Metadata' class provides a container for inner TUF metadata objects (Root,
Timestamp, Snapshot, Targets) (i.e. OOP composition)
The 'Signed' class provides a base class to aggregate common attributes (i.e.
version, expires, spec_version) of the inner metadata classes. (i.e. OOP
inheritance). The name of the class also aligns with the 'signed' field of
the outer metadata container.
Based on prior observations in TUF's sister project in-toto, this architecture
seems to well represent the metadata model as it is defined in the
specification (see in-toto/in-toto#98 and in-toto/in-toto#142 for related
discussions).
This commits also adds tests.
**TODO: See doc header TODO list**
**Additional design considerations**
(also in regards to prior sketches of this module)
- Aims at simplicity, brevity and recognizability of the wireline metadata
format.
- All attributes that correspond to fields in TUF JSON metadata are public.
There doesn't seem to be a good reason to protect them with leading
underscores and use setters/getters instead, it just adds more code, and
impedes recognizability of the wireline metadata format.
- Although, it might be convenient to have short-cuts on the Metadata class
that point to methods and attributes that are common to all subclasses of
the contained Signed class (e.g. Metadata.version instead of
Metadata.signed.version, etc.), this also conflicts with goal of
recognizability of the wireline metadata. Thus we won't add such short-cuts
for now. See:
https://github.com/theupdateframework/tuf/pull/1060#discussion_r452906629
- Signing keys and a 'consistent_snapshot' boolean are not on the targets
metadata class. They are a better fit for management code. See:
https://github.com/theupdateframework/tuf/pull/1060#issuecomment-660056376,
and #660.
- Does not use sslib schema checks (see TODO notes about validation in
doc header)
- Does not use existing tuf utils, such as make_metadata_fileinfo,
build_dict_conforming_to_schema, if it is easy and more explicit to
just re-implement the desired behavior on the metadata classes.
- All datetime's are treated as UTC. Since timezone info is not captured in
the wireline metadata format it should not be captured in the internal
representation either.
- Does not use 3rd-party dateutil package, in order to minimize dependency
footprint, which is especially important for update clients which often have
to vendor their dependencies.
However, compatibility between the more advanced dateutil.relativedelta (e.g
handles leap years automatically) and timedelta is tested.
- Uses PEP8 indentation (4 space) and Google-style doc string instead of
sslab-style. See
https://github.com/secure-systems-lab/code-style-guidelines/issues/20
- Does not support Python =< 3.5
Co-authored-by: Trishank Karthik Kuppusamy <trishank.kuppusamy@datadoghq.com>
Co-authored-by: Joshua Lock <jlock@vmware.com>
Co-authored-by: Teodora Sechkova <tsechkova@vmware.com>
Signed-off-by: Lukas Puehringer <lukas.puehringer@nyu.edu>
2020-08-18 09:15:49 +00:00
|
|
|
|
2023-08-02 12:52:18 +00:00
|
|
|
from securesystemslib.signer import Signature, Signer
|
2021-03-11 17:00:19 +00:00
|
|
|
from securesystemslib.storage import FilesystemBackend, StorageBackendInterface
|
2021-03-04 09:51:45 +00:00
|
|
|
|
2023-08-02 12:52:18 +00:00
|
|
|
# Expose payload classes via ``tuf.api.metadata`` to maintain the API,
|
|
|
|
|
# even if they are unused in the local scope.
|
|
|
|
|
from tuf.api._payload import ( # noqa: F401
|
|
|
|
|
_ROOT,
|
|
|
|
|
_SNAPSHOT,
|
|
|
|
|
_TARGETS,
|
|
|
|
|
_TIMESTAMP,
|
|
|
|
|
SPECIFICATION_VERSION,
|
|
|
|
|
TOP_LEVEL_ROLE_NAMES,
|
|
|
|
|
BaseFile,
|
|
|
|
|
DelegatedRole,
|
|
|
|
|
Delegations,
|
|
|
|
|
Key,
|
2024-02-22 12:45:21 +00:00
|
|
|
LengthOrHashMismatchError,
|
2023-08-02 12:52:18 +00:00
|
|
|
MetaFile,
|
|
|
|
|
Role,
|
|
|
|
|
Root,
|
|
|
|
|
RootVerificationResult,
|
|
|
|
|
Signed,
|
|
|
|
|
Snapshot,
|
|
|
|
|
SuccinctRoles,
|
|
|
|
|
T,
|
|
|
|
|
TargetFile,
|
|
|
|
|
Targets,
|
|
|
|
|
Timestamp,
|
|
|
|
|
VerificationResult,
|
|
|
|
|
)
|
|
|
|
|
from tuf.api.exceptions import UnsignedMetadataError
|
2024-11-29 10:29:32 +00:00
|
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
|
from tuf.api.serialization import (
|
|
|
|
|
MetadataDeserializer,
|
|
|
|
|
MetadataSerializer,
|
|
|
|
|
SignedSerializer,
|
|
|
|
|
)
|
Add simple TUF role metadata model (WIP)
Add metadata module with container classes for TUF role metadata, including
methods to read/serialize/write from and to JSON, perform TUF-compliant
metadata updates, and create and verify signatures.
The 'Metadata' class provides a container for inner TUF metadata objects (Root,
Timestamp, Snapshot, Targets) (i.e. OOP composition)
The 'Signed' class provides a base class to aggregate common attributes (i.e.
version, expires, spec_version) of the inner metadata classes. (i.e. OOP
inheritance). The name of the class also aligns with the 'signed' field of
the outer metadata container.
Based on prior observations in TUF's sister project in-toto, this architecture
seems to well represent the metadata model as it is defined in the
specification (see in-toto/in-toto#98 and in-toto/in-toto#142 for related
discussions).
This commits also adds tests.
**TODO: See doc header TODO list**
**Additional design considerations**
(also in regards to prior sketches of this module)
- Aims at simplicity, brevity and recognizability of the wireline metadata
format.
- All attributes that correspond to fields in TUF JSON metadata are public.
There doesn't seem to be a good reason to protect them with leading
underscores and use setters/getters instead, it just adds more code, and
impedes recognizability of the wireline metadata format.
- Although, it might be convenient to have short-cuts on the Metadata class
that point to methods and attributes that are common to all subclasses of
the contained Signed class (e.g. Metadata.version instead of
Metadata.signed.version, etc.), this also conflicts with goal of
recognizability of the wireline metadata. Thus we won't add such short-cuts
for now. See:
https://github.com/theupdateframework/tuf/pull/1060#discussion_r452906629
- Signing keys and a 'consistent_snapshot' boolean are not on the targets
metadata class. They are a better fit for management code. See:
https://github.com/theupdateframework/tuf/pull/1060#issuecomment-660056376,
and #660.
- Does not use sslib schema checks (see TODO notes about validation in
doc header)
- Does not use existing tuf utils, such as make_metadata_fileinfo,
build_dict_conforming_to_schema, if it is easy and more explicit to
just re-implement the desired behavior on the metadata classes.
- All datetime's are treated as UTC. Since timezone info is not captured in
the wireline metadata format it should not be captured in the internal
representation either.
- Does not use 3rd-party dateutil package, in order to minimize dependency
footprint, which is especially important for update clients which often have
to vendor their dependencies.
However, compatibility between the more advanced dateutil.relativedelta (e.g
handles leap years automatically) and timedelta is tested.
- Uses PEP8 indentation (4 space) and Google-style doc string instead of
sslab-style. See
https://github.com/secure-systems-lab/code-style-guidelines/issues/20
- Does not support Python =< 3.5
Co-authored-by: Trishank Karthik Kuppusamy <trishank.kuppusamy@datadoghq.com>
Co-authored-by: Joshua Lock <jlock@vmware.com>
Co-authored-by: Teodora Sechkova <tsechkova@vmware.com>
Signed-off-by: Lukas Puehringer <lukas.puehringer@nyu.edu>
2020-08-18 09:15:49 +00:00
|
|
|
|
2021-06-22 07:10:17 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2021-06-15 09:55:39 +00:00
|
|
|
|
|
|
|
|
class Metadata(Generic[T]):
|
2020-08-20 10:19:55 +00:00
|
|
|
"""A container for signed TUF metadata.
|
|
|
|
|
|
2021-03-05 11:29:57 +00:00
|
|
|
Provides methods to convert to and from dictionary, read and write to and
|
|
|
|
|
from file and to create and verify metadata signatures.
|
2020-08-20 10:19:55 +00:00
|
|
|
|
2022-02-02 12:19:46 +00:00
|
|
|
``Metadata[T]`` is a generic container type where T can be any one type of
|
|
|
|
|
[``Root``, ``Timestamp``, ``Snapshot``, ``Targets``]. The purpose of this
|
|
|
|
|
is to allow static type checking of the signed attribute in code using
|
|
|
|
|
Metadata::
|
2021-06-15 09:55:39 +00:00
|
|
|
|
|
|
|
|
root_md = Metadata[Root].from_file("root.json")
|
|
|
|
|
# root_md type is now Metadata[Root]. This means signed and its
|
|
|
|
|
# attributes like consistent_snapshot are now statically typed and the
|
|
|
|
|
# types can be verified by static type checkers and shown by IDEs
|
|
|
|
|
print(root_md.signed.consistent_snapshot)
|
|
|
|
|
|
|
|
|
|
Using a type constraint is not required but not doing so means T is not a
|
|
|
|
|
specific type so static typing cannot happen. Note that the type constraint
|
2024-02-20 05:34:47 +00:00
|
|
|
``[Root]`` is not validated at runtime (as pure annotations are not
|
|
|
|
|
available then).
|
2021-06-15 09:55:39 +00:00
|
|
|
|
2022-03-24 14:00:15 +00:00
|
|
|
New Metadata instances can be created from scratch with::
|
|
|
|
|
|
2024-02-26 20:27:38 +00:00
|
|
|
one_day = datetime.now(timezone.utc) + timedelta(days=1)
|
2022-03-24 14:00:15 +00:00
|
|
|
timestamp = Metadata(Timestamp(expires=one_day))
|
|
|
|
|
|
|
|
|
|
Apart from ``expires`` all of the arguments to the inner constructors have
|
|
|
|
|
reasonable default values for new metadata.
|
|
|
|
|
|
2021-09-17 16:02:43 +00:00
|
|
|
*All parameters named below are not just constructor arguments but also
|
|
|
|
|
instance attributes.*
|
|
|
|
|
|
|
|
|
|
Args:
|
2022-02-02 16:09:10 +00:00
|
|
|
signed: Actual metadata payload, i.e. one of ``Targets``,
|
2022-02-02 12:19:46 +00:00
|
|
|
``Snapshot``, ``Timestamp`` or ``Root``.
|
2022-02-02 16:09:10 +00:00
|
|
|
signatures: Ordered dictionary of keyids to ``Signature`` objects, each
|
2022-02-02 12:19:46 +00:00
|
|
|
signing the canonical serialized representation of ``signed``.
|
2022-03-24 14:00:15 +00:00
|
|
|
Default is an empty dictionary.
|
2022-02-13 17:31:17 +00:00
|
|
|
unrecognized_fields: Dictionary of all attributes that are not managed
|
|
|
|
|
by TUF Metadata API. These fields are NOT signed and it's preferable
|
|
|
|
|
if unrecognized fields are added to the Signed derivative classes.
|
2020-08-20 10:19:55 +00:00
|
|
|
"""
|
2021-03-11 17:00:19 +00:00
|
|
|
|
2022-02-13 17:31:17 +00:00
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
signed: T,
|
2024-11-29 10:29:32 +00:00
|
|
|
signatures: dict[str, Signature] | None = None,
|
|
|
|
|
unrecognized_fields: dict[str, Any] | None = None,
|
2022-02-13 17:31:17 +00:00
|
|
|
):
|
2021-06-15 09:55:39 +00:00
|
|
|
self.signed: T = signed
|
2022-03-24 13:38:53 +00:00
|
|
|
self.signatures = signatures if signatures is not None else {}
|
2022-04-21 08:23:17 +00:00
|
|
|
if unrecognized_fields is None:
|
|
|
|
|
unrecognized_fields = {}
|
|
|
|
|
|
|
|
|
|
self.unrecognized_fields = unrecognized_fields
|
Add simple TUF role metadata model (WIP)
Add metadata module with container classes for TUF role metadata, including
methods to read/serialize/write from and to JSON, perform TUF-compliant
metadata updates, and create and verify signatures.
The 'Metadata' class provides a container for inner TUF metadata objects (Root,
Timestamp, Snapshot, Targets) (i.e. OOP composition)
The 'Signed' class provides a base class to aggregate common attributes (i.e.
version, expires, spec_version) of the inner metadata classes. (i.e. OOP
inheritance). The name of the class also aligns with the 'signed' field of
the outer metadata container.
Based on prior observations in TUF's sister project in-toto, this architecture
seems to well represent the metadata model as it is defined in the
specification (see in-toto/in-toto#98 and in-toto/in-toto#142 for related
discussions).
This commits also adds tests.
**TODO: See doc header TODO list**
**Additional design considerations**
(also in regards to prior sketches of this module)
- Aims at simplicity, brevity and recognizability of the wireline metadata
format.
- All attributes that correspond to fields in TUF JSON metadata are public.
There doesn't seem to be a good reason to protect them with leading
underscores and use setters/getters instead, it just adds more code, and
impedes recognizability of the wireline metadata format.
- Although, it might be convenient to have short-cuts on the Metadata class
that point to methods and attributes that are common to all subclasses of
the contained Signed class (e.g. Metadata.version instead of
Metadata.signed.version, etc.), this also conflicts with goal of
recognizability of the wireline metadata. Thus we won't add such short-cuts
for now. See:
https://github.com/theupdateframework/tuf/pull/1060#discussion_r452906629
- Signing keys and a 'consistent_snapshot' boolean are not on the targets
metadata class. They are a better fit for management code. See:
https://github.com/theupdateframework/tuf/pull/1060#issuecomment-660056376,
and #660.
- Does not use sslib schema checks (see TODO notes about validation in
doc header)
- Does not use existing tuf utils, such as make_metadata_fileinfo,
build_dict_conforming_to_schema, if it is easy and more explicit to
just re-implement the desired behavior on the metadata classes.
- All datetime's are treated as UTC. Since timezone info is not captured in
the wireline metadata format it should not be captured in the internal
representation either.
- Does not use 3rd-party dateutil package, in order to minimize dependency
footprint, which is especially important for update clients which often have
to vendor their dependencies.
However, compatibility between the more advanced dateutil.relativedelta (e.g
handles leap years automatically) and timedelta is tested.
- Uses PEP8 indentation (4 space) and Google-style doc string instead of
sslab-style. See
https://github.com/secure-systems-lab/code-style-guidelines/issues/20
- Does not support Python =< 3.5
Co-authored-by: Trishank Karthik Kuppusamy <trishank.kuppusamy@datadoghq.com>
Co-authored-by: Joshua Lock <jlock@vmware.com>
Co-authored-by: Teodora Sechkova <tsechkova@vmware.com>
Signed-off-by: Lukas Puehringer <lukas.puehringer@nyu.edu>
2020-08-18 09:15:49 +00:00
|
|
|
|
2024-04-03 11:28:38 +00:00
|
|
|
def __eq__(self, other: object) -> bool:
|
2021-12-21 14:19:08 +00:00
|
|
|
if not isinstance(other, Metadata):
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
self.signatures == other.signatures
|
Take order into account for certain cases
After we have dropped OrderedDict in https://github.com/theupdateframework/python-tuf/pull/1783/commits/e3b267e2e0799673ac99ccfccd3631628013201c
we are relying on python3.7+ default behavior to preserve the insertion
order, but there is one caveat.
When comparing dictionaries the order is still irrelevant compared to
OrderedDict. For example:
>>> OrderedDict([(1,1), (2,2)]) == OrderedDict([(2,2), (1,1)])
False
>>> dict([(1,1), (2,2)]) == dict([(2,2), (1,1)])
True
There are two special attributes, defined in the specification, where
the order makes a difference when comparing two objects:
- Metadata.signatures
- Targets.delegations.roles.
We want to make sure that the order in those two cases makes a
difference when comparing two objects and that's why those changes
are required inside two __eq__ implementations.
Signed-off-by: Martin Vrachev <mvrachev@vmware.com>
2022-02-04 17:49:44 +00:00
|
|
|
# Order of the signatures matters (see issue #1788).
|
|
|
|
|
and list(self.signatures.items()) == list(other.signatures.items())
|
2021-12-21 14:19:08 +00:00
|
|
|
and self.signed == other.signed
|
|
|
|
|
and self.unrecognized_fields == other.unrecognized_fields
|
|
|
|
|
)
|
|
|
|
|
|
2025-06-24 07:56:32 +00:00
|
|
|
def __hash__(self) -> int:
|
|
|
|
|
return hash((self.signatures, self.signed, self.unrecognized_fields))
|
|
|
|
|
|
2023-08-01 12:29:17 +00:00
|
|
|
@property
|
|
|
|
|
def signed_bytes(self) -> bytes:
|
|
|
|
|
"""Default canonical json byte representation of ``self.signed``."""
|
|
|
|
|
|
|
|
|
|
# Use local scope import to avoid circular import errors
|
2025-06-24 07:56:32 +00:00
|
|
|
from tuf.api.serialization.json import CanonicalJSONSerializer # noqa: I001, PLC0415
|
2023-08-01 12:29:17 +00:00
|
|
|
|
|
|
|
|
return CanonicalJSONSerializer().serialize(self.signed)
|
|
|
|
|
|
2021-03-04 11:46:16 +00:00
|
|
|
@classmethod
|
2024-11-29 10:29:32 +00:00
|
|
|
def from_dict(cls, metadata: dict[str, Any]) -> Metadata[T]:
|
2022-12-18 11:55:37 +00:00
|
|
|
"""Create ``Metadata`` object from its json/dict representation.
|
2021-03-04 11:46:16 +00:00
|
|
|
|
2022-02-02 12:38:36 +00:00
|
|
|
Args:
|
2021-03-05 11:29:57 +00:00
|
|
|
metadata: TUF metadata in dict representation.
|
2021-03-04 11:46:16 +00:00
|
|
|
|
|
|
|
|
Raises:
|
2022-02-03 15:14:29 +00:00
|
|
|
ValueError, KeyError, TypeError: Invalid arguments.
|
2021-03-04 11:46:16 +00:00
|
|
|
|
2021-03-05 11:29:57 +00:00
|
|
|
Side Effect:
|
2021-05-07 14:08:51 +00:00
|
|
|
Destroys the metadata dict passed by reference.
|
2021-03-05 11:29:57 +00:00
|
|
|
|
2021-03-04 11:46:16 +00:00
|
|
|
Returns:
|
2022-02-02 16:09:10 +00:00
|
|
|
TUF ``Metadata`` object.
|
2021-03-04 11:46:16 +00:00
|
|
|
"""
|
2021-06-19 09:47:34 +00:00
|
|
|
|
2021-03-04 11:46:16 +00:00
|
|
|
# Dispatch to contained metadata class on metadata _type field.
|
2021-03-11 17:00:19 +00:00
|
|
|
_type = metadata["signed"]["_type"]
|
2021-03-04 11:46:16 +00:00
|
|
|
|
2021-11-17 12:23:03 +00:00
|
|
|
if _type == _TARGETS:
|
2024-11-04 04:21:23 +00:00
|
|
|
inner_cls: type[Signed] = Targets
|
2021-11-17 12:23:03 +00:00
|
|
|
elif _type == _SNAPSHOT:
|
2021-03-04 11:46:16 +00:00
|
|
|
inner_cls = Snapshot
|
2021-11-17 12:23:03 +00:00
|
|
|
elif _type == _TIMESTAMP:
|
2021-03-04 11:46:16 +00:00
|
|
|
inner_cls = Timestamp
|
2021-11-17 12:23:03 +00:00
|
|
|
elif _type == _ROOT:
|
2021-03-04 11:46:16 +00:00
|
|
|
inner_cls = Root
|
|
|
|
|
else:
|
|
|
|
|
raise ValueError(f'unrecognized metadata type "{_type}"')
|
|
|
|
|
|
2021-05-28 18:06:45 +00:00
|
|
|
# Make sure signatures are unique
|
2024-11-04 04:21:23 +00:00
|
|
|
signatures: dict[str, Signature] = {}
|
2021-05-28 18:06:45 +00:00
|
|
|
for sig_dict in metadata.pop("signatures"):
|
|
|
|
|
sig = Signature.from_dict(sig_dict)
|
|
|
|
|
if sig.keyid in signatures:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
f"Multiple signatures found for keyid {sig.keyid}"
|
|
|
|
|
)
|
|
|
|
|
signatures[sig.keyid] = sig
|
2021-02-03 16:46:02 +00:00
|
|
|
|
2021-03-04 11:46:16 +00:00
|
|
|
return cls(
|
2021-06-15 09:55:39 +00:00
|
|
|
# Specific type T is not known at static type check time: use cast
|
2025-03-18 16:20:11 +00:00
|
|
|
signed=cast("T", inner_cls.from_dict(metadata.pop("signed"))),
|
2021-03-11 17:00:19 +00:00
|
|
|
signatures=signatures,
|
2022-02-13 17:31:17 +00:00
|
|
|
# All fields left in the metadata dict are unrecognized.
|
|
|
|
|
unrecognized_fields=metadata,
|
2021-03-11 17:00:19 +00:00
|
|
|
)
|
2021-03-04 11:46:16 +00:00
|
|
|
|
2020-09-03 13:35:05 +00:00
|
|
|
@classmethod
|
2021-03-04 09:51:45 +00:00
|
|
|
def from_file(
|
2021-03-11 17:00:19 +00:00
|
|
|
cls,
|
|
|
|
|
filename: str,
|
2024-11-29 10:29:32 +00:00
|
|
|
deserializer: MetadataDeserializer | None = None,
|
|
|
|
|
storage_backend: StorageBackendInterface | None = None,
|
|
|
|
|
) -> Metadata[T]:
|
2022-12-18 11:55:37 +00:00
|
|
|
"""Load TUF metadata from file storage.
|
2020-09-03 14:10:19 +00:00
|
|
|
|
2022-02-02 12:38:36 +00:00
|
|
|
Args:
|
2022-02-02 16:09:10 +00:00
|
|
|
filename: Path to read the file from.
|
|
|
|
|
deserializer: ``MetadataDeserializer`` subclass instance that
|
2021-03-04 09:51:45 +00:00
|
|
|
implements the desired wireline format deserialization. Per
|
2022-02-02 12:19:46 +00:00
|
|
|
default a ``JSONDeserializer`` is used.
|
2022-02-02 16:09:10 +00:00
|
|
|
storage_backend: Object that implements
|
2022-02-02 12:19:46 +00:00
|
|
|
``securesystemslib.storage.StorageBackendInterface``.
|
2022-02-02 12:38:36 +00:00
|
|
|
Default is ``FilesystemBackend`` (i.e. a local file).
|
2024-02-20 05:34:47 +00:00
|
|
|
|
2020-09-03 14:10:19 +00:00
|
|
|
Raises:
|
2022-12-01 08:46:42 +00:00
|
|
|
StorageError: The file cannot be read.
|
2021-02-09 14:36:49 +00:00
|
|
|
tuf.api.serialization.DeserializationError:
|
|
|
|
|
The file cannot be deserialized.
|
2020-09-03 14:10:19 +00:00
|
|
|
|
|
|
|
|
Returns:
|
2022-02-02 16:09:10 +00:00
|
|
|
TUF ``Metadata`` object.
|
2020-09-03 14:10:19 +00:00
|
|
|
"""
|
2021-06-19 09:47:34 +00:00
|
|
|
|
2021-04-16 13:12:15 +00:00
|
|
|
if storage_backend is None:
|
|
|
|
|
storage_backend = FilesystemBackend()
|
|
|
|
|
|
|
|
|
|
with storage_backend.get(filename) as file_obj:
|
|
|
|
|
return cls.from_bytes(file_obj.read(), deserializer)
|
|
|
|
|
|
2021-06-15 09:55:39 +00:00
|
|
|
@classmethod
|
2021-04-16 13:12:15 +00:00
|
|
|
def from_bytes(
|
2021-06-15 09:55:39 +00:00
|
|
|
cls,
|
2021-04-16 13:12:15 +00:00
|
|
|
data: bytes,
|
2024-11-29 10:29:32 +00:00
|
|
|
deserializer: MetadataDeserializer | None = None,
|
|
|
|
|
) -> Metadata[T]:
|
2022-12-18 11:55:37 +00:00
|
|
|
"""Load TUF metadata from raw data.
|
2021-04-16 13:12:15 +00:00
|
|
|
|
2022-02-02 12:38:36 +00:00
|
|
|
Args:
|
2022-02-02 16:09:10 +00:00
|
|
|
data: Metadata content.
|
2022-02-02 12:19:46 +00:00
|
|
|
deserializer: ``MetadataDeserializer`` implementation to use.
|
|
|
|
|
Default is ``JSONDeserializer``.
|
2021-04-16 13:12:15 +00:00
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
|
tuf.api.serialization.DeserializationError:
|
|
|
|
|
The file cannot be deserialized.
|
|
|
|
|
|
|
|
|
|
Returns:
|
2022-02-02 16:09:10 +00:00
|
|
|
TUF ``Metadata`` object.
|
2021-04-16 13:12:15 +00:00
|
|
|
"""
|
|
|
|
|
|
2021-03-04 09:51:45 +00:00
|
|
|
if deserializer is None:
|
2021-03-04 15:31:36 +00:00
|
|
|
# Use local scope import to avoid circular import errors
|
2025-06-24 07:56:32 +00:00
|
|
|
from tuf.api.serialization.json import JSONDeserializer # noqa: I001, PLC0415
|
2021-03-11 17:00:19 +00:00
|
|
|
|
2021-03-04 09:51:45 +00:00
|
|
|
deserializer = JSONDeserializer()
|
|
|
|
|
|
2021-04-16 13:12:15 +00:00
|
|
|
return deserializer.deserialize(data)
|
2020-09-03 14:10:19 +00:00
|
|
|
|
2024-11-29 10:29:32 +00:00
|
|
|
def to_bytes(self, serializer: MetadataSerializer | None = None) -> bytes:
|
2021-07-09 12:53:48 +00:00
|
|
|
"""Return the serialized TUF file format as bytes.
|
|
|
|
|
|
2022-01-26 14:07:04 +00:00
|
|
|
Note that if bytes are first deserialized into ``Metadata`` and then
|
|
|
|
|
serialized with ``to_bytes()``, the two are not required to be
|
|
|
|
|
identical even though the signatures are guaranteed to stay valid. If
|
|
|
|
|
byte-for-byte equivalence is required (which is the case when content
|
|
|
|
|
hashes are used in other metadata), the original content should be used
|
|
|
|
|
instead of re-serializing.
|
|
|
|
|
|
2022-02-02 12:38:36 +00:00
|
|
|
Args:
|
2022-02-02 16:09:10 +00:00
|
|
|
serializer: ``MetadataSerializer`` instance that implements the
|
2022-02-02 12:19:46 +00:00
|
|
|
desired serialization format. Default is ``JSONSerializer``.
|
2021-07-09 12:53:48 +00:00
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
|
tuf.api.serialization.SerializationError:
|
|
|
|
|
The metadata object cannot be serialized.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
if serializer is None:
|
|
|
|
|
# Use local scope import to avoid circular import errors
|
2025-06-24 07:56:32 +00:00
|
|
|
from tuf.api.serialization.json import JSONSerializer # noqa: I001, PLC0415
|
2021-07-09 12:53:48 +00:00
|
|
|
|
|
|
|
|
serializer = JSONSerializer(compact=True)
|
|
|
|
|
|
|
|
|
|
return serializer.serialize(self)
|
|
|
|
|
|
2024-11-04 04:21:23 +00:00
|
|
|
def to_dict(self) -> dict[str, Any]:
|
2022-12-18 11:55:37 +00:00
|
|
|
"""Return the dict representation of self."""
|
2021-02-03 16:46:02 +00:00
|
|
|
|
2021-05-28 18:06:45 +00:00
|
|
|
signatures = [sig.to_dict() for sig in self.signatures.values()]
|
2021-02-03 16:46:02 +00:00
|
|
|
|
2022-02-13 17:31:17 +00:00
|
|
|
return {
|
|
|
|
|
"signatures": signatures,
|
|
|
|
|
"signed": self.signed.to_dict(),
|
|
|
|
|
**self.unrecognized_fields,
|
|
|
|
|
}
|
2021-03-04 11:46:16 +00:00
|
|
|
|
2021-03-05 10:27:33 +00:00
|
|
|
def to_file(
|
2021-03-11 17:00:19 +00:00
|
|
|
self,
|
|
|
|
|
filename: str,
|
2024-11-29 10:29:32 +00:00
|
|
|
serializer: MetadataSerializer | None = None,
|
|
|
|
|
storage_backend: StorageBackendInterface | None = None,
|
2021-03-05 10:27:33 +00:00
|
|
|
) -> None:
|
2022-12-18 11:55:37 +00:00
|
|
|
"""Write TUF metadata to file storage.
|
2020-09-03 14:10:19 +00:00
|
|
|
|
2022-01-26 14:07:04 +00:00
|
|
|
Note that if a file is first deserialized into ``Metadata`` and then
|
|
|
|
|
serialized with ``to_file()``, the two files are not required to be
|
|
|
|
|
identical even though the signatures are guaranteed to stay valid. If
|
|
|
|
|
byte-for-byte equivalence is required (which is the case when file
|
|
|
|
|
hashes are used in other metadata), the original file should be used
|
|
|
|
|
instead of re-serializing.
|
|
|
|
|
|
2022-02-02 12:38:36 +00:00
|
|
|
Args:
|
2022-02-02 16:09:10 +00:00
|
|
|
filename: Path to write the file to.
|
|
|
|
|
serializer: ``MetadataSerializer`` instance that implements the
|
2022-02-02 12:19:46 +00:00
|
|
|
desired serialization format. Default is ``JSONSerializer``.
|
2022-02-02 16:09:10 +00:00
|
|
|
storage_backend: ``StorageBackendInterface`` implementation. Default
|
2022-02-02 12:19:46 +00:00
|
|
|
is ``FilesystemBackend`` (i.e. a local file).
|
2021-03-04 09:51:45 +00:00
|
|
|
|
2020-09-03 14:10:19 +00:00
|
|
|
Raises:
|
2021-02-09 14:36:49 +00:00
|
|
|
tuf.api.serialization.SerializationError:
|
|
|
|
|
The metadata object cannot be serialized.
|
2022-12-01 08:46:42 +00:00
|
|
|
StorageError: The file cannot be written.
|
2020-09-03 14:10:19 +00:00
|
|
|
"""
|
2021-06-19 09:47:34 +00:00
|
|
|
|
2024-04-12 19:41:12 +00:00
|
|
|
if storage_backend is None:
|
|
|
|
|
storage_backend = FilesystemBackend()
|
|
|
|
|
|
2021-07-09 12:53:48 +00:00
|
|
|
bytes_data = self.to_bytes(serializer)
|
2021-03-04 09:51:45 +00:00
|
|
|
|
2020-10-15 10:23:59 +00:00
|
|
|
with tempfile.TemporaryFile() as temp_file:
|
2021-07-09 12:53:48 +00:00
|
|
|
temp_file.write(bytes_data)
|
2024-04-12 19:41:12 +00:00
|
|
|
storage_backend.put(temp_file, filename)
|
2020-09-03 14:10:19 +00:00
|
|
|
|
|
|
|
|
# Signatures.
|
2021-03-05 11:29:57 +00:00
|
|
|
def sign(
|
2021-03-11 17:00:19 +00:00
|
|
|
self,
|
|
|
|
|
signer: Signer,
|
|
|
|
|
append: bool = False,
|
2024-11-29 10:29:32 +00:00
|
|
|
signed_serializer: SignedSerializer | None = None,
|
2021-06-11 06:57:08 +00:00
|
|
|
) -> Signature:
|
2022-12-18 11:55:37 +00:00
|
|
|
"""Create signature over ``signed`` and assigns it to ``signatures``.
|
2020-08-31 14:10:19 +00:00
|
|
|
|
2022-02-02 12:38:36 +00:00
|
|
|
Args:
|
2024-02-20 05:34:47 +00:00
|
|
|
signer: A ``securesystemslib.signer.Signer`` object that provides a
|
2024-05-03 09:18:27 +00:00
|
|
|
signing implementation to generate the signature.
|
2022-02-02 12:38:36 +00:00
|
|
|
append: ``True`` if the signature should be appended to
|
2020-08-31 14:10:19 +00:00
|
|
|
the list of signatures or replace any existing signatures. The
|
|
|
|
|
default behavior is to replace signatures.
|
2022-02-02 16:09:10 +00:00
|
|
|
signed_serializer: ``SignedSerializer`` that implements the desired
|
2022-02-02 12:19:46 +00:00
|
|
|
serialization format. Default is ``CanonicalJSONSerializer``.
|
2020-08-31 14:10:19 +00:00
|
|
|
|
|
|
|
|
Raises:
|
2021-02-09 14:36:49 +00:00
|
|
|
tuf.api.serialization.SerializationError:
|
2022-02-02 12:19:46 +00:00
|
|
|
``signed`` cannot be serialized.
|
2022-12-01 08:46:42 +00:00
|
|
|
UnsignedMetadataError: Signing errors.
|
2020-08-31 14:10:19 +00:00
|
|
|
|
|
|
|
|
Returns:
|
2022-02-02 16:09:10 +00:00
|
|
|
``securesystemslib.signer.Signature`` object that was added into
|
|
|
|
|
signatures.
|
2020-08-31 14:10:19 +00:00
|
|
|
"""
|
2021-06-19 09:47:34 +00:00
|
|
|
|
2021-03-05 10:46:00 +00:00
|
|
|
if signed_serializer is None:
|
2023-08-01 12:29:17 +00:00
|
|
|
bytes_data = self.signed_bytes
|
|
|
|
|
else:
|
|
|
|
|
bytes_data = signed_serializer.serialize(self.signed)
|
2022-01-26 18:09:40 +00:00
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
signature = signer.sign(bytes_data)
|
2024-04-30 07:32:37 +00:00
|
|
|
except Exception as e:
|
2024-02-20 12:39:50 +00:00
|
|
|
raise UnsignedMetadataError(f"Failed to sign: {e}") from e
|
2020-08-31 14:10:19 +00:00
|
|
|
|
2021-06-11 07:45:04 +00:00
|
|
|
if not append:
|
|
|
|
|
self.signatures.clear()
|
|
|
|
|
|
|
|
|
|
self.signatures[signature.keyid] = signature
|
2020-08-31 14:10:19 +00:00
|
|
|
|
|
|
|
|
return signature
|
|
|
|
|
|
2021-04-22 16:37:38 +00:00
|
|
|
def verify_delegate(
|
|
|
|
|
self,
|
2021-07-05 12:01:31 +00:00
|
|
|
delegated_role: str,
|
2024-11-29 10:29:32 +00:00
|
|
|
delegated_metadata: Metadata,
|
|
|
|
|
signed_serializer: SignedSerializer | None = None,
|
2021-07-05 12:01:31 +00:00
|
|
|
) -> None:
|
2022-12-18 11:55:37 +00:00
|
|
|
"""Verify that ``delegated_metadata`` is signed with the required
|
2023-05-15 07:49:40 +00:00
|
|
|
threshold of keys for ``delegated_role``.
|
2021-04-22 16:37:38 +00:00
|
|
|
|
2023-05-15 08:07:47 +00:00
|
|
|
.. deprecated:: 3.1.0
|
2024-02-20 05:34:47 +00:00
|
|
|
Please use ``Root.verify_delegate()`` or
|
|
|
|
|
``Targets.verify_delegate()``.
|
2021-04-22 16:37:38 +00:00
|
|
|
"""
|
|
|
|
|
|
2023-01-17 13:03:16 +00:00
|
|
|
if self.signed.type not in ["root", "targets"]:
|
2021-06-16 11:54:17 +00:00
|
|
|
raise TypeError("Call is valid only on delegator metadata")
|
2021-04-22 16:37:38 +00:00
|
|
|
|
2022-12-01 09:38:19 +00:00
|
|
|
if signed_serializer is None:
|
2023-08-01 13:21:07 +00:00
|
|
|
payload = delegated_metadata.signed_bytes
|
2023-01-17 13:03:16 +00:00
|
|
|
|
2023-08-01 13:21:07 +00:00
|
|
|
else:
|
|
|
|
|
payload = signed_serializer.serialize(delegated_metadata.signed)
|
2021-04-22 16:37:38 +00:00
|
|
|
|
2023-05-05 06:58:41 +00:00
|
|
|
self.signed.verify_delegate(
|
2023-08-01 13:21:07 +00:00
|
|
|
delegated_role, payload, delegated_metadata.signatures
|
2023-05-05 06:58:41 +00:00
|
|
|
)
|