How to use the tuf.util.load_json_file function in tuf

To help you get started, we’ve selected a few tuf examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github theupdateframework / tuf / tests / test_updater.py View on Github external
self.assertFalse('timestamp' in self.repository_updater.metadata)
    
    logger.info('\nroleinfo: ' + repr(tuf.roledb.get_rolenames(self.repository_name)))
    self.repository_updater._update_metadata('timestamp',
                                             DEFAULT_TIMESTAMP_FILELENGTH)
    self.assertTrue('timestamp' in self.repository_updater.metadata['current'])
    os.path.exists(timestamp_filepath)
  
    # Verify 'targets.json' is properly installed.
    self.assertFalse('targets' in self.repository_updater.metadata['current'])
    self.repository_updater._update_metadata('targets',
                                DEFAULT_TARGETS_FILELENGTH,
                                targets_versioninfo['version'])
    self.assertTrue('targets' in self.repository_updater.metadata['current'])
   
    targets_signable = tuf.util.load_json_file(targets_filepath)
    loaded_targets_version = targets_signable['signed']['version']
    self.assertEqual(targets_versioninfo['version'], loaded_targets_version)
    
    # Remove the 'targets.json' metadata so that the compressed version may be
    # tested next.
    del self.repository_updater.metadata['current']['targets']
    os.remove(targets_filepath)

    # Verify 'targets.json.gz' is properly intalled.  Note: The uncompressed
    # version is installed if the compressed one is downloaded.
    self.assertFalse('targets' in self.repository_updater.metadata['current'])
    self.repository_updater._update_metadata('targets',
                                             DEFAULT_TARGETS_FILELENGTH,
                                             targets_versioninfo['version'],                                          
                                             'gzip')
    self.assertTrue('targets' in self.repository_updater.metadata['current'])
github theupdateframework / tuf / tests / test_util.py View on Github external
def  test_B6_load_json_file(self):
    data = ['a', {'b': ['c', None, 30.3, 29]}]
    filepath = self.make_temp_file()
    fileobj = open(filepath, 'wt')
    tuf.util.json.dump(data, fileobj)
    fileobj.close()
    self.assertEqual(data, tuf.util.load_json_file(filepath))

    # Test a gzipped file.
    compressed_filepath = self._compress_existing_file(filepath)
    self.assertEqual(data, tuf.util.load_json_file(compressed_filepath))

    # Improperly formatted arguments.
    for bogus_arg in [1, [b'a'], {'a':b'b'}]:
      self.assertRaises(tuf.FormatError, tuf.util.load_json_file, bogus_arg)

    # Non-existent path. 
    self.assertRaises(IOError, tuf.util.load_json_file, 'non-existent.json')

    # Invalid JSON content.
    with open(filepath, 'a') as filepath:
      filepath.write('junk data')
    self.assertRaises(tuf.Error, tuf.util.load_json_file, filepath)
github theupdateframework / tuf / tuf / libtuf.py View on Github external
if os.path.exists(root_filename+'.gz'):
      roleinfo['compressions'].append('gz')
    
    _check_if_partial_loaded('root', signable, roleinfo)
    tuf.roledb.update_roleinfo('root', roleinfo)
  
  else:
    message = 'Cannot load the required root file: '+repr(root_filename)
    raise tuf.RepositoryError(message)
  
  repository = Repository(repository_directory, metadata_directory,
                          targets_directory)
   
  # TARGETS.txt
  if os.path.exists(targets_filename):
    signable = tuf.util.load_json_file(targets_filename)
    tuf.formats.check_signable_object_format(signable)
    targets_metadata = signable['signed']

    for signature in signable['signatures']:
      repository.targets.add_signature(signature)
   
    # Update 'targets.txt' in 'tuf.roledb.py' 
    roleinfo = tuf.roledb.get_roleinfo('targets')
    roleinfo['paths'] = targets_metadata['targets'].keys()
    roleinfo['version'] = targets_metadata['version']
    roleinfo['expires'] = targets_metadata['expires']
    roleinfo['delegations'] = targets_metadata['delegations']
    if os.path.exists(targets_filename+'.gz'):
      roleinfo['compressions'].append('gz')
    
    _check_if_partial_loaded('targets', signable, roleinfo)
github theupdateframework / tuf / tuf / repo / signerlib.py View on Github external
# the targets.  This information is stored in the 'meta' field of
  # the snapshot metadata object.  The keyids for the optional
  # delegated roles will now be extracted.
  targets_metadata = os.path.join(metadata_directory, 'targets')
  if os.path.exists(targets_metadata) and os.path.isdir(targets_metadata):
    for directory_path, junk, files in os.walk(targets_metadata):
      for basename in files:
        # Store the metadata's file path and the role's full name (without
        # the '.txt').   The target role is identified by its full name.
        # The metadata's file path is needed so it can be loaded.
        metadata_path = os.path.join(directory_path, basename)
        metadata_name = metadata_path[len(metadata_directory):].lstrip(os.path.sep)
        metadata_name = metadata_name[:-len('.txt')]

        # Read the contents of 'metadata_path' and save the signable.
        targets_signable = tuf.util.load_json_file(metadata_path)

        # Ensure the signable is properly formatted.
        try:
          tuf.formats.check_signable_object_format(targets_signable)
        except tuf.FormatError, e:
          continue

        # Store the signature keyids of the 'metadata_name' role.
        role_keyids[metadata_name] = []
        for signature in targets_signable['signatures']:
          role_keyids[metadata_name].append(signature['keyid'])

  return role_keyids
github theupdateframework / tuf / tuf / pushtools / receivetools / receive.py View on Github external
None.

  """
    
  # Create the backup destination directories.  The old target files
  # and target metadata are backed up to these directories.
  backup_destdirectory = os.path.join(backup_directory, pushname)
  os.mkdir(backup_destdirectory)
  targets_basename = os.path.basename(targets_directory)
  backup_targetsdirectory = os.path.join(backup_destdirectory, targets_basename)
  os.mkdir(backup_targetsdirectory)

  # Load the old 'targets.txt' file and determine all the targets to be replaced.
  # Need to ensure we only remove target files specified by 'targets.txt'.
  targets_signable = tuf.util.load_json_file(targets_metadatapath)
  for target_relativepath in targets_signable['signed']['targets'].keys():
    targetpath = os.path.join(targets_directory, target_relativepath)
    backup_targetpath = os.path.join(backup_targetsdirectory, target_relativepath)
    message = 'Backing up target '+repr(targetpath)+' to '+repr(backup_targetpath)
    logger.info(message)
   
    # Move the old target file to the backup directory.  Create any
    # directories along the way.
    if os.path.exists(targetpath):
      try:
        os.makedirs(os.path.dirname(backup_targetpath))
      except OSError, e:
        if e.errno == errno.EEXIST:
          pass
        else:
          raise tuf.Error(str(e))
github theupdateframework / tuf / tuf / repo / signerlib.py View on Github external
filename:
      The filename of the file containing the metadata object.

  
    tuf.FormatError, if 'filename' is improperly formatted.

    tuf.Error, if 'filename' cannot be opened.

  
    The contents of 'filename' are extracted.

  
   The metadata object.
  """

  return tuf.util.load_json_file(filename)
github theupdateframework / tuf / tuf / libtuf.py View on Github external
The contents of 'filepath' is read and saved.

  
    An ED25519 key object conformant to 'tuf.formats.ED25519KEY_SCHEMA'.
  """

  # Does 'filepath' have the correct format?
  # Ensure the arguments have the appropriate number of objects and object
  # types, and that all dict keys are properly named.
  # Raise 'tuf.FormatError' if there is a mismatch.
  tuf.formats.PATH_SCHEMA.check_match(filepath)

  # ED25519 key objects are saved in json and metadata format.  Return the
  # loaded key object in tuf.formats.ED25519KEY_SCHEMA' format that also
  # includes the keyid.
  ed25519_key_metadata = tuf.util.load_json_file(filepath)
  ed25519_key = tuf.keys.format_metadata_to_key(ed25519_key_metadata)
  
  # Raise an exception if an unexpected key type is imported. 
  if ed25519_key['keytype'] != 'ed25519':
    message = 'Invalid key type loaded: '+repr(ed25519_key['keytype'])
    raise tuf.FormatError(message)

  return ed25519_key
github theupdateframework / tuf / tuf / pushtools / receivetools / receive.py View on Github external
"""
  
  # The push's timestamp directory name (e.g., '1348449811.39')
  pushname = os.path.basename(pushpath)

  # Copy the contents of pushpath to a temp directory. We don't want the
  # user modifying the files we work with.  The temp directory is only
  # accessible by the calling process.
  temporary_directory = tempfile.mkdtemp()
  push_temporary_directory = os.path.join(temporary_directory, 'push')
  shutil.copytree(pushpath, push_temporary_directory)
  
  # Read the 'root' metadata of the current repository.  'root.txt'
  # is needed to authorize the 'targets' metadata file.
  root_metadatapath = os.path.join(metadata_directory, 'root.txt')
  root_signable = tuf.util.load_json_file(root_metadatapath)
  
  # Ensure 'root_signable' is properly formatted.
  try:
    tuf.formats.check_signable_object_format(root_signable)
  except tuf.FormatError, e:
    raise tuf.Error('The repository contains an invalid "root.txt".')
 
  # Extract the metadata object and load the key and role databases.
  # The keys and roles are needed to verify the signatures of the
  # metadata files.
  root_metadata = root_signable['signed']
  tuf.keydb.create_keydb_from_root_metadata(root_metadata)
  tuf.roledb.create_roledb_from_root_metadata(root_metadata)

  # Determine the name of the targets metadata file that was pushed.
  # The required 'info' file should list the metadata file that was
github theupdateframework / tuf / tuf / repo / signercli.py View on Github external
"""
    List the key files found in 'keystore_directory'.
    It is assumed the directory arguments exist and have been validated by
    the caller.  The keyids are listed without the '.key' extension,
    along with their associated roles.

  """

  # Determine the 'root.txt' filename.  This metadata file is needed
  # to extract the keyids belonging to the top-level roles.
  filenames = tuf.repo.signerlib.get_metadata_filenames(metadata_directory)
  root_filename = filenames['root']
 
  # Load the root metadata file.  The loaded object should conform to
  # 'tuf.formats.SIGNABLE_SCHEMA'.
  metadata_signable = tuf.util.load_json_file(root_filename)

  # Ensure the loaded json object is properly formatted.
  try: 
    tuf.formats.check_signable_object_format(metadata_signable)
  except tuf.FormatError, e:
    message = 'Invalid metadata format: '+repr(root_filename)+'.'
    raise tuf.RepositoryError(message)

  # Extract the 'signed' role object from 'metadata_signable'.
  root_metadata = metadata_signable['signed']
 
  # Extract the 'roles' dict, where the dict keys are top-level roles and dict
  # values a dictionary containing a list of corresponding keyids and a 
  # threshold.
  top_level_keyids = root_metadata['roles']
github theupdateframework / tuf / tuf / repo / signercli.py View on Github external
"""
    List the key files found in 'keystore_directory'.
    It is assumed the directory arguments exist and have been validated by
    the caller.  The keyids are listed without the '.key' extension,
    along with their associated roles.

  """

  # Determine the 'root.txt' filename.  This metadata file is needed
  # to extract the keyids belonging to the top-level roles.
  filenames = tuf.repo.signerlib.get_metadata_filenames(metadata_directory)
  root_filename = filenames['root']
 
  # Load the root metadata file.  The loaded object should conform to
  # 'tuf.formats.SIGNABLE_SCHEMA'.
  metadata_signable = tuf.util.load_json_file(root_filename)

  # Ensure the loaded json object is properly formatted.
  try: 
    tuf.formats.check_signable_object_format(metadata_signable)
  except tuf.FormatError, e:
    message = 'Invalid metadata format: '+repr(root_filename)+'.'
    raise tuf.RepositoryError(message)

  # Extract the 'signed' role object from 'metadata_signable'.
  root_metadata = metadata_signable['signed']
 
  # Extract the 'roles' dict, where the dict keys are top-level roles and dict
  # values a dictionary containing a list of corresponding keyids and a 
  # threshold.
  top_level_keyids = root_metadata['roles']