Metadata

TUF role metadata model.

This module provides container classes for TUF role metadata, including methods to read and write from and to file, perform TUF-compliant metadata updates, and create and verify signatures.

The metadata model supports any custom serialization format, defaulting to JSON as wireline format and Canonical JSON for reproducible signature creation and verification. Custom serializers must implement the abstract serialization interface defined in ‘tuf.api.serialization’, and may use the [to|from]_dict convenience methods available in the class model.

class tuf.api.metadata.BaseFile

Bases: object

A base class of MetaFile and TargetFile.

Encapsulates common static methods for length and hash verification.

class tuf.api.metadata.DelegatedRole(name: str, keyids: List[str], threshold: int, terminating: bool, paths: Optional[List[str]] = None, path_hash_prefixes: Optional[List[str]] = None, unrecognized_fields: Optional[Mapping[str, Any]] = None)

Bases: tuf.api.metadata.Role

A container with information about a delegated role.

A delegation can happen in two ways:

  • paths is set: delegates targets matching any path pattern in paths

  • path_hash_prefixes is set: delegates targets whose target path hash starts with any of the prefixes in path_hash_prefixes

paths and path_hash_prefixes are mutually exclusive: both cannot be set, at least one of them must be set.

name

A string giving the name of the delegated role.

terminating

A boolean indicating whether subsequent delegations should be considered during a target lookup.

paths

An optional list of path pattern strings. See note above.

path_hash_prefixes

An optional list of hash prefixes. See note above.

unrecognized_fields

Dictionary of all unrecognized fields.

classmethod from_dict(role_dict: Dict[str, Any]) tuf.api.metadata.DelegatedRole

Creates DelegatedRole object from its dict representation.

is_delegated_path(target_filepath: str) bool

Determines whether the given ‘target_filepath’ is in one of the paths that DelegatedRole is trusted to provide.

The target_filepath and the DelegatedRole paths are expected to be in their canonical forms, so e.g. “a/b” instead of “a//b” . Only “/” is supported as target path separator. Leading separators are not handled as special cases (see TUF specification on targetpath).

to_dict() Dict[str, Any]

Returns the dict representation of self.

class tuf.api.metadata.Delegations(keys: Dict[str, tuf.api.metadata.Key], roles: List[tuf.api.metadata.DelegatedRole], unrecognized_fields: Optional[Mapping[str, Any]] = None)

Bases: object

A container object storing information about all delegations.

keys

Dictionary of keyids to Keys. Defines the keys used in ‘roles’.

roles

List of DelegatedRoles that define which keys are required to sign the metadata for a specific role. The roles order also defines the order that role delegations are considered in.

unrecognized_fields

Dictionary of all unrecognized fields.

classmethod from_dict(delegations_dict: Dict[str, Any]) tuf.api.metadata.Delegations

Creates Delegations object from its dict representation.

to_dict() Dict[str, Any]

Returns the dict representation of self.

class tuf.api.metadata.Key(keyid: str, keytype: str, scheme: str, keyval: Dict[str, str], unrecognized_fields: Optional[Mapping[str, Any]] = None)

Bases: object

A container class representing the public portion of a Key.

Please note that “Key” instances are not semanticly validated during initialization: this only happens at signature verification time.

keyid

An identifier string that must uniquely identify a key within the metadata it is used in. This implementation does not verify that keyid is the hash of a specific representation of the key.

keytype

A string denoting a public key signature system, such as “rsa”, “ed25519”, “ecdsa” and “ecdsa-sha2-nistp256”.

scheme

A string denoting a corresponding signature scheme. For example: “rsassa-pss-sha256”, “ed25519”, and “ecdsa-sha2-nistp256”.

keyval

A dictionary containing the public portion of the key.

unrecognized_fields

Dictionary of all unrecognized fields.

classmethod from_dict(keyid: str, key_dict: Dict[str, Any]) tuf.api.metadata.Key

Creates Key object from its dict representation.

classmethod from_securesystemslib_key(key_dict: Dict[str, Any]) tuf.api.metadata.Key

Creates a Key object from a securesystemlib key dict representation removing the private key from keyval.

to_dict() Dict[str, Any]

Returns the dictionary representation of self.

to_securesystemslib_key() Dict[str, Any]

Returns a Securesystemslib compatible representation of self.

verify_signature(metadata: tuf.api.metadata.Metadata, signed_serializer: Optional[tuf.api.serialization.SignedSerializer] = None) None

Verifies that the ‘metadata.signatures’ contains a signature made with this key, correctly signing ‘metadata.signed’.

Parameters
  • metadata – Metadata to verify

  • signed_serializer – Optional; SignedSerializer to serialize ‘metadata.signed’ with. Default is CanonicalJSONSerializer.

Raises

UnsignedMetadataError – The signature could not be verified for a variety of possible reasons: see error message.

class tuf.api.metadata.MetaFile(version: int, length: Optional[int] = None, hashes: Optional[Dict[str, str]] = None, unrecognized_fields: Optional[Mapping[str, Any]] = None)

Bases: tuf.api.metadata.BaseFile

A container with information about a particular metadata file.

version

An integer indicating the version of the metadata file.

length

An optional integer indicating the length of the metadata file.

hashes

An optional dictionary of hash algorithm names to hash values.

unrecognized_fields

Dictionary of all unrecognized fields.

classmethod from_dict(meta_dict: Dict[str, Any]) tuf.api.metadata.MetaFile

Creates MetaFile object from its dict representation.

to_dict() Dict[str, Any]

Returns the dictionary representation of self.

verify_length_and_hashes(data: Union[bytes, IO[bytes]]) None

Verifies that the length and hashes of “data” match expected values.

Parameters

data – File object or its content in bytes.

Raises

LengthOrHashMismatchError – Calculated length or hashes do not match expected values or hash algorithm is not supported.

class tuf.api.metadata.Metadata(signed: tuf.api.metadata.T, signatures: OrderedDict[str, Signature])

Bases: Generic[tuf.api.metadata.T]

A container for signed TUF metadata.

Provides methods to convert to and from dictionary, read and write to and from file and to create and verify metadata signatures.

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:

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 “[Root]” is not validated at runtime (as pure annotations are not available then).

signed

A subclass of Signed, which has the actual metadata payload, i.e. one of Targets, Snapshot, Timestamp or Root.

signatures

An ordered dictionary of keyids to Signature objects, each signing the canonical serialized representation of ‘signed’.

classmethod from_bytes(data: bytes, deserializer: Optional[tuf.api.serialization.MetadataDeserializer] = None) tuf.api.metadata.Metadata[tuf.api.metadata.T]

Loads TUF metadata from raw data.

Parameters
  • data – metadata content as bytes.

  • deserializer – Optional; A MetadataDeserializer instance that implements deserialization. Default is JSONDeserializer.

Raises

tuf.api.serialization.DeserializationError – The file cannot be deserialized.

Returns

A TUF Metadata object.

classmethod from_dict(metadata: Dict[str, Any]) tuf.api.metadata.Metadata[tuf.api.metadata.T]

Creates Metadata object from its dict representation.

Parameters

metadata – TUF metadata in dict representation.

Raises
  • KeyError – The metadata dict format is invalid.

  • ValueError – The metadata has an unrecognized signed._type field.

Side Effect:

Destroys the metadata dict passed by reference.

Returns

A TUF Metadata object.

classmethod from_file(filename: str, deserializer: Optional[tuf.api.serialization.MetadataDeserializer] = None, storage_backend: Optional[securesystemslib.storage.StorageBackendInterface] = None) tuf.api.metadata.Metadata[tuf.api.metadata.T]

Loads TUF metadata from file storage.

Parameters
  • filename – The path to read the file from.

  • deserializer – A MetadataDeserializer subclass instance that implements the desired wireline format deserialization. Per default a JSONDeserializer is used.

  • storage_backend – An object that implements securesystemslib.storage.StorageBackendInterface. Per default a (local) FilesystemBackend is used.

Raises
  • securesystemslib.exceptions.StorageError – The file cannot be read.

  • tuf.api.serialization.DeserializationError – The file cannot be deserialized.

Returns

A TUF Metadata object.

sign(signer: securesystemslib.signer.Signer, append: bool = False, signed_serializer: Optional[tuf.api.serialization.SignedSerializer] = None) securesystemslib.signer.Signature

Creates signature over ‘signed’ and assigns it to ‘signatures’.

Parameters
  • signer – A securesystemslib.signer.Signer implementation.

  • append – A boolean indicating if the signature should be appended to the list of signatures or replace any existing signatures. The default behavior is to replace signatures.

  • signed_serializer – A SignedSerializer that implements the desired serialization format. Default is CanonicalJSONSerializer.

Raises
  • tuf.api.serialization.SerializationError – ‘signed’ cannot be serialized.

  • securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError – Signing errors.

Returns

Securesystemslib Signature object that was added into signatures.

to_bytes(serializer: Optional[tuf.api.serialization.MetadataSerializer] = None) bytes

Return the serialized TUF file format as bytes.

Parameters

serializer – A MetadataSerializer instance that implements the desired serialization format. Default is JSONSerializer.

Raises

tuf.api.serialization.SerializationError – The metadata object cannot be serialized.

to_dict() Dict[str, Any]

Returns the dict representation of self.

to_file(filename: str, serializer: Optional[tuf.api.serialization.MetadataSerializer] = None, storage_backend: Optional[securesystemslib.storage.StorageBackendInterface] = None) None

Writes TUF metadata to file storage.

Parameters
  • filename – The path to write the file to.

  • serializer – A MetadataSerializer instance that implements the desired serialization format. Default is JSONSerializer.

  • storage_backend – A StorageBackendInterface implementation. Default is FilesystemBackend (i.e. a local file).

Raises
  • tuf.api.serialization.SerializationError – The metadata object cannot be serialized.

  • securesystemslib.exceptions.StorageError – The file cannot be written.

verify_delegate(delegated_role: str, delegated_metadata: tuf.api.metadata.Metadata, signed_serializer: Optional[tuf.api.serialization.SignedSerializer] = None) None

Verifies that ‘delegated_metadata’ is signed with the required threshold of keys for the delegated role ‘delegated_role’.

Parameters
  • delegated_role – Name of the delegated role to verify

  • delegated_metadata – The Metadata object for the delegated role

  • signed_serializer – Optional; serializer used for delegate serialization. Default is CanonicalJSONSerializer.

Raises

UnsignedMetadataError – ‘delegate’ was not signed with required threshold of keys for ‘role_name’

class tuf.api.metadata.Role(keyids: List[str], threshold: int, unrecognized_fields: Optional[Mapping[str, Any]] = None)

Bases: object

Container that defines which keys are required to sign roles metadata.

Role defines how many keys are required to successfully sign the roles metadata, and which keys are accepted.

keyids

A set of strings representing signing keys for this role.

threshold

Number of keys required to sign this role’s metadata.

unrecognized_fields

Dictionary of all unrecognized fields.

classmethod from_dict(role_dict: Dict[str, Any]) tuf.api.metadata.Role

Creates Role object from its dict representation.

to_dict() Dict[str, Any]

Returns the dictionary representation of self.

class tuf.api.metadata.Root(version: int, spec_version: str, expires: datetime.datetime, keys: Dict[str, tuf.api.metadata.Key], roles: Dict[str, tuf.api.metadata.Role], consistent_snapshot: Optional[bool] = None, unrecognized_fields: Optional[Mapping[str, Any]] = None)

Bases: tuf.api.metadata.Signed

A container for the signed part of root metadata.

consistent_snapshot

An optional boolean indicating whether the repository supports consistent snapshots.

keys

Dictionary of keyids to Keys. Defines the keys used in ‘roles’.

roles

Dictionary of role names to Roles. Defines which keys are required to sign the metadata for a specific role.

add_key(role: str, key: tuf.api.metadata.Key) None

Adds new signing key for delegated role ‘role’.

classmethod from_dict(signed_dict: Dict[str, Any]) tuf.api.metadata.Root

Creates Root object from its dict representation.

remove_key(role: str, keyid: str) None

Removes key from ‘role’ and updates the key store.

Raises

KeyError – If ‘role’ does not include the key

to_dict() Dict[str, Any]

Returns the dict representation of self.

class tuf.api.metadata.Signed(version: int, spec_version: str, expires: datetime.datetime, unrecognized_fields: Optional[Mapping[str, Any]] = None)

Bases: object

A base class for the signed part of TUF metadata.

Objects with base class Signed are usually included in a Metadata object on the signed attribute. This class provides attributes and methods that are common for all TUF metadata types (roles).

_type

The metadata type string. Also available without underscore.

version

The metadata version number.

spec_version

The TUF specification version number (semver) the metadata format adheres to.

expires

The metadata expiration datetime object.

unrecognized_fields

Dictionary of all unrecognized fields.

bump_expiration(delta: datetime.timedelta = datetime.timedelta(days=1)) None

Increments the expires attribute by the passed timedelta.

bump_version() None

Increments the metadata version number by 1.

abstract classmethod from_dict(signed_dict: Dict[str, Any]) tuf.api.metadata.Signed

Deserialization helper, creates object from dict representation

is_expired(reference_time: Optional[datetime.datetime] = None) bool

Checks metadata expiration against a reference time.

Parameters

reference_time – Optional; The time to check expiration date against. A naive datetime in UTC expected. If not provided, checks against the current UTC date and time.

Returns

True if expiration time is less than the reference time.

abstract to_dict() Dict[str, Any]

Serialization helper that returns dict representation of self

property type: str
class tuf.api.metadata.Snapshot(version: int, spec_version: str, expires: datetime.datetime, meta: Dict[str, tuf.api.metadata.MetaFile], unrecognized_fields: Optional[Mapping[str, Any]] = None)

Bases: tuf.api.metadata.Signed

A container for the signed part of snapshot metadata.

Snapshot contains information about all target Metadata files.

meta

A dictionary of target metadata filenames to MetaFile objects.

classmethod from_dict(signed_dict: Dict[str, Any]) tuf.api.metadata.Snapshot

Creates Snapshot object from its dict representation.

to_dict() Dict[str, Any]

Returns the dict representation of self.

update(rolename: str, role_info: tuf.api.metadata.MetaFile) None

Assigns passed (delegated) targets role info to meta dict.

class tuf.api.metadata.TargetFile(length: int, hashes: Dict[str, str], path: str, unrecognized_fields: Optional[Mapping[str, Any]] = None)

Bases: tuf.api.metadata.BaseFile

A container with information about a particular target file.

length

An integer indicating the length of the target file.

hashes

A dictionary of hash algorithm names to hash values.

path

A string denoting the path to a target file relative to a base URL of targets.

unrecognized_fields

Dictionary of all unrecognized fields.

property custom: Any
classmethod from_dict(target_dict: Dict[str, Any], path: str) tuf.api.metadata.TargetFile

Creates TargetFile object from its dict representation.

to_dict() Dict[str, Any]

Returns the JSON-serializable dictionary representation of self.

verify_length_and_hashes(data: Union[bytes, IO[bytes]]) None

Verifies that length and hashes of “data” match expected values.

Parameters

data – File object or its content in bytes.

Raises

LengthOrHashMismatchError – Calculated length or hashes do not match expected values or hash algorithm is not supported.

class tuf.api.metadata.Targets(version: int, spec_version: str, expires: datetime.datetime, targets: Dict[str, tuf.api.metadata.TargetFile], delegations: Optional[tuf.api.metadata.Delegations] = None, unrecognized_fields: Optional[Mapping[str, Any]] = None)

Bases: tuf.api.metadata.Signed

A container for the signed part of targets metadata.

Targets contains verifying information about target files and also delegates responsibility to other Targets roles.

targets

A dictionary of target filenames to TargetFiles

delegations

An optional Delegations that defines how this Targets further delegates responsibility to other Targets Metadata files.

classmethod from_dict(signed_dict: Dict[str, Any]) tuf.api.metadata.Targets

Creates Targets object from its dict representation.

to_dict() Dict[str, Any]

Returns the dict representation of self.

update(fileinfo: tuf.api.metadata.TargetFile) None

Assigns passed target file info to meta dict.

class tuf.api.metadata.Timestamp(version: int, spec_version: str, expires: datetime.datetime, meta: Dict[str, tuf.api.metadata.MetaFile], unrecognized_fields: Optional[Mapping[str, Any]] = None)

Bases: tuf.api.metadata.Signed

A container for the signed part of timestamp metadata.

Timestamp contains information about the snapshot Metadata file.

meta

A dictionary of filenames to MetaFiles. The only valid key value is the snapshot filename, as defined by the specification.

classmethod from_dict(signed_dict: Dict[str, Any]) tuf.api.metadata.Timestamp

Creates Timestamp object from its dict representation.

to_dict() Dict[str, Any]

Returns the dict representation of self.

update(snapshot_meta: tuf.api.metadata.MetaFile) None

Assigns passed info about snapshot metadata to meta dict.