Skip to content

Commit

Permalink
Use MetaFile.verify_length_and_hashes in ngclient
Browse files Browse the repository at this point in the history
Use MetaFile.verify_length_and_hashes during snapshot
and targets verification in TrustedMetadataSet.

Remove pylint: disable=too-many-branches.

Signed-off-by: Teodora Sechkova <tsechkova@vmware.com>
  • Loading branch information
sechkova committed Jun 25, 2021
1 parent 3398bf3 commit 39ebe92
Showing 1 changed file with 13 additions and 19 deletions.
32 changes: 13 additions & 19 deletions tuf/ngclient/_internal/trusted_metadata_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,6 @@
from datetime import datetime
from typing import Dict, Iterator, Optional

from securesystemslib import hash as sslib_hash

from tuf import exceptions
from tuf.api.metadata import Metadata, Root, Targets
from tuf.api.serialization import DeserializationError
Expand Down Expand Up @@ -305,8 +303,7 @@ def update_timestamp(self, data: bytes):
self._trusted_set["timestamp"] = new_timestamp
logger.debug("Updated timestamp")

# TODO: remove pylint disable once the hash verification is in metadata.py
def update_snapshot(self, data: bytes): # pylint: disable=too-many-branches
def update_snapshot(self, data: bytes):
"""Verifies and loads 'data' as new snapshot metadata.
Args:
Expand All @@ -326,13 +323,12 @@ def update_snapshot(self, data: bytes): # pylint: disable=too-many-branches
meta = self.timestamp.signed.meta["snapshot.json"]

# Verify against the hashes in timestamp, if any
hashes = meta.hashes or {}
for algo, stored_hash in hashes.items():
digest_object = sslib_hash.digest(algo)
digest_object.update(data)
observed_hash = digest_object.hexdigest()
if observed_hash != stored_hash:
raise exceptions.BadHashError(stored_hash, observed_hash)
try:
meta.verify_length_and_hashes(data)
except exceptions.LengthOrHashMismatchError as e:
raise exceptions.RepositoryError(
"Snapshot length or hashes do not match"
) from e

try:
new_snapshot = Metadata.from_bytes(data)
Expand Down Expand Up @@ -426,14 +422,12 @@ def update_delegated_targets(
f"Snapshot does not contain information for '{role_name}'"
)

hashes = meta.hashes or {}
for algo, stored_hash in hashes.items():
digest_object = sslib_hash.digest(algo)
digest_object.update(data)
observed_hash = digest_object.hexdigest()
if observed_hash != stored_hash:
# TODO: Error should derive from RepositoryError
raise exceptions.BadHashError(stored_hash, observed_hash)
try:
meta.verify_length_and_hashes(data)
except exceptions.LengthOrHashMismatchError as e:
raise exceptions.RepositoryError(
f"{role_name} length or hashes do not match"
) from e

try:
new_delegate = Metadata.from_bytes(data)
Expand Down

0 comments on commit 39ebe92

Please sign in to comment.