5050import logging
5151import os
5252import tempfile
53- from securesystemslib .hash import digest
53+ import securesystemslib .hash as sslib_hash
5454from securesystemslib .keys import generate_ed25519_key
5555from securesystemslib .signer import SSlibSigner
5656from typing import Dict , Iterator , List , Optional , Tuple
5757from urllib import parse
5858
5959from tuf .api .serialization .json import JSONSerializer
60- from tuf .exceptions import FetcherHTTPError , RepositoryError
60+ from tuf .exceptions import FetcherHTTPError
6161from tuf .api .metadata import (
6262 Key ,
6363 Metadata ,
@@ -100,6 +100,9 @@ def __init__(self):
100100 # target downloads are served from this dict
101101 self .target_files : Dict [str , RepositoryTarget ] = {}
102102
103+ # Whether to compute hashes and legth for meta in snapshot/timestamp
104+ self .compute_metafile_hashes_length = False
105+
103106 self .dump_dir = None
104107 self .dump_version = 0
105108
@@ -121,7 +124,8 @@ def snapshot(self) -> Snapshot:
121124 def targets (self ) -> Targets :
122125 return self .md_targets .signed
123126
124- def delegates (self ) -> Iterator [Tuple [str , Targets ]]:
127+ def all_targets (self ) -> Iterator [Tuple [str , Targets ]]:
128+ yield "targets" , self .md_targets .signed
125129 for role , md in self .md_delegates .items ():
126130 yield role , md .signed
127131
@@ -243,16 +247,34 @@ def _fetch_metadata(self, role: str, version: Optional[int] = None) -> bytes:
243247 )
244248 return md .to_bytes (JSONSerializer ())
245249
250+ def _compute_hashes_and_length (
251+ self , role : str
252+ ) -> Tuple [Dict [str , str ], int ]:
253+ data = self ._fetch_metadata (role )
254+ digest_object = sslib_hash .digest (sslib_hash .DEFAULT_HASH_ALGORITHM )
255+ digest_object .update (data )
256+ hashes = {sslib_hash .DEFAULT_HASH_ALGORITHM : digest_object .hexdigest ()}
257+ return hashes , len (data )
258+
246259 def update_timestamp (self ):
247260 self .timestamp .snapshot_meta .version = self .snapshot .version
248261
262+ if self .compute_metafile_hashes_length :
263+ hashes , length = self ._compute_hashes_and_length ("snapshot" )
264+ self .timestamp .snapshot_meta .hashes = hashes
265+ self .timestamp .snapshot_meta .length = length
266+
249267 self .timestamp .version += 1
250268
251269 def update_snapshot (self ):
252- self .snapshot .meta ["targets.json" ].version = self .targets .version
253- for role , delegate in self .delegates ():
270+ for role , delegate in self .all_targets ():
254271 self .snapshot .meta [f"{ role } .json" ].version = delegate .version
255272
273+ if self .compute_metafile_hashes_length :
274+ hashes , length = self ._compute_hashes_and_length (role )
275+ self .snapshot .meta [f"{ role } .json" ].hashes = hashes
276+ self .snapshot .meta [f"{ role } .json" ].length = length
277+
256278 self .snapshot .version += 1
257279 self .update_timestamp ()
258280
0 commit comments