How to use the tuf.RepositoryError 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 / go-tuf / client / python_interop / testdata / python-tuf-v0.9.9 / client.py View on Github external
tuf.RepositoryError, if 'repository_mirror' is improperly formatted.

  
    Connects to a repository mirror and updates the metadata files and
    any target files.  Obsolete targets are also removed locally.

  
    None.
  """

  # Does 'repository_mirror' have the correct format?
  try:
    tuf.formats.URL_SCHEMA.check_match(repository_mirror)
  except tuf.FormatError as e:
    message = 'The repository mirror supplied is invalid.' 
    raise tuf.RepositoryError(message)
  
  # Set the local repository directory containing all of the metadata files.
  tuf.conf.repository_directory = '.'

  # Set the repository mirrors.  This dictionary is needed by the Updater
  # class of updater.py.
  repository_mirrors = {'mirror': {'url_prefix': repository_mirror,
                                  'metadata_path': 'repository',
                                  'targets_path': 'repository/targets',
                                  'confined_target_dirs': ['']}}

  # Create the repository object using the repository name 'repository'
  # and the repository mirrors defined above.
  updater = tuf.client.updater.Updater('repository', repository_mirrors)

  # The local destination directory to save the target files.
github theupdateframework / tuf / tests / test_updater.py View on Github external
# Test: Invalid arguments.
    # Invalid 'updater_name' argument.  String expected. 
    self.assertRaises(tuf.FormatError, updater.Updater, 8,
                      self.repository_mirrors)
   
    # Invalid 'repository_mirrors' argument.  'tuf.formats.MIRRORDICT_SCHEMA'
    # expected.
    self.assertRaises(tuf.FormatError, updater.Updater, updater.Updater, 8)


    # 'tuf.client.updater.py' requires that the client's repository directory
    # be configured in 'tuf.conf.py'.
    tuf.conf.repository_directory = None
    self.assertRaises(tuf.RepositoryError, updater.Updater, 'test_repository',
                      self.repository_mirrors)
    # Restore 'tuf.conf.repository_directory' to the original client directory.
    tuf.conf.repository_directory = self.client_directory
    

    # Test: empty client repository (i.e., no metadata directory).
    metadata_backup = self.client_metadata + '.backup'
    shutil.move(self.client_metadata, metadata_backup)
    self.assertRaises(tuf.RepositoryError, updater.Updater, 'test_repository',
                      self.repository_mirrors)
    # Restore the client's metadata directory.
    shutil.move(metadata_backup, self.client_metadata)


    # Test: repository with only a '{repository_directory}/metadata' directory.
    # (i.e., missing the required 'current' and 'previous' sub-directories). 
github theupdateframework / tuf / tests / test_util.py View on Github external
# Test improperly formatted arguments.
    self.assertRaises(tuf.FormatError, tuf.util.find_delegated_role, 8, role_list)
    self.assertRaises(tuf.FormatError, tuf.util.find_delegated_role, 8, 'targets/tuf')

    # Test duplicate roles.
    role_list.append(role_list[1])
    self.assertRaises(tuf.RepositoryError, tuf.util.find_delegated_role, role_list,
                      'targets/tuf')

    # Test missing 'name' attribute (optional, but required by 
    # 'find_delegated_role()').
    # Delete the duplicate role, and the remaining role's 'name' attribute. 
    del role_list[2]
    del role_list[0]['name']
    self.assertRaises(tuf.RepositoryError, tuf.util.find_delegated_role, role_list,
                      'targets/warehouse')
github theupdateframework / tuf / quickstart.py View on Github external
# Do the arguments have the correct format?
  # Raise 'tuf.RepositoryError' if there is a mismatch.
  try:
    tuf.formats.PATH_SCHEMA.check_match(project_directory)
  except tuf.FormatError, e:
    message = str(e)
    raise tuf.RepositoryError(message)
  
  # Verify the 'project_directory' argument.
  project_directory = os.path.abspath(project_directory)
  try:
    tuf.repo.signerlib.check_directory(project_directory)
  except (tuf.FormatError, tuf.Error), e:
    message = str(e)
    raise tuf.RepositoryError(message)
  
  # Handle the expiration time.  The expiration date determines when
  # the top-level roles expire.
  prompt_message = \
    '\nWhen would you like your certificates to expire? (mm/dd/yyyy): '
  timeout = None
  for attempt in range(MAX_INPUT_ATTEMPTS):
    # Get the difference between the user's entered expiration date and today's
    # date.  Convert and store the difference to total days till expiration.
    try:
      input_date = _prompt(prompt_message)
      expiration_date = datetime.datetime.strptime(input_date, '%m/%d/%Y')
      time_difference = expiration_date - datetime.datetime.now()
      timeout = time_difference.days
      if timeout < 1:
        raise ValueError
github theupdateframework / tuf / tuf / repo / signerlib.py View on Github external
"""

  # Check argument types.
  tuf.formats.ROLELIST_SCHEMA.check_match(roles)
  tuf.formats.ROLENAME_SCHEMA.check_match(delegated_role)

  # The index of a role, if any, with the same name.
  role_index = None

  for index in xrange(len(roles)):
    role = roles[index]
    name = role.get('name')
    # This role has no name.
    if name is None:
      no_name_message = 'Role with no name!'
      raise tuf.RepositoryError(no_name_message)
    # Does this role have the same name?
    else:
      # This role has the same name, and...
      if name == delegated_role:
        # ...it is the only known role with the same name.
        if role_index is None:
          role_index = index
        # ...there are at least two roles with the same name!
        else:
          duplicate_role_message = 'Duplicate role ('+str(delegated_role)+')!'
          raise tuf.RepositoryError(duplicate_role_message)
      # This role has a different name.
      else:
        continue

  return role_index
github theupdateframework / tuf / tuf / repo / signercli.py View on Github external
If the entered date is valid, it is returned unmodified.

    
      tuf.RepositoryError, if the entered expiration date is invalid.
  
  """

  message = '\nCurrent time: '+tuf.formats.format_time(time.time())+'.\n'+\
    'Enter the expiration date, in UTC, of the metadata file (yyyy-mm-dd HH:MM:SS): '
    
  try:
    input_date = _prompt(message, str)
    input_date = input_date+' UTC'
    expiration_date = tuf.formats.parse_time(input_date)
  except (tuf.FormatError, ValueError), e:
    raise tuf.RepositoryError('Invalid date entered.')
  
  if expiration_date < time.time():
    message = 'The expiration date must occur after the current date.'
    raise tuf.RepositoryError(message)
  
  return input_date
github theupdateframework / tuf / tuf / repo / signercli.py View on Github external
# Retrieve the parent role from the user.
  for attempt in range(MAX_INPUT_ATTEMPTS):
    prompt = '\nChoose and enter the parent role\'s full name: '
    parent_role = _prompt(prompt, str)
    if parent_role not in targets_roles:
      message = 'Invalid role name entered'
      logger.info(message)
      parent_role = None
      continue
    else:
      break

  # Ensure we loaded a valid parent role.
  if parent_role is None:
    message = 'Could not get a valid parent role.\n'
    raise tuf.RepositoryError(message)

  # Load the parent's key(s).  The key needs to be loaded because
  # its metadata file will be modified.
  parent_keyids = []
  for keyid in targets_roles[parent_role]:
    for attempt in range(MAX_INPUT_ATTEMPTS):
      prompt = '\nEnter the password for '+parent_role+' ('+keyid+'): '
      password = _get_password(prompt)
      loaded_keyid = load_key(keystore_directory, [keyid], [password])
      if keyid not in loaded_keyid:
        message = 'The keyid could not be loaded.'
        logger.info(message)
        continue
      parent_keyids.append(loaded_keyid[0])
      break
    if keyid not in parent_keyids:
github theupdateframework / tuf / tuf / repo / signercli.py View on Github external
"""

  message = '\nCurrent time: '+tuf.formats.format_time(time.time())+'.\n'+\
    'Enter the expiration date, in UTC, of the metadata file (yyyy-mm-dd HH:MM:SS): '
    
  try:
    input_date = _prompt(message, str)
    input_date = input_date+' UTC'
    expiration_date = tuf.formats.parse_time(input_date)
  except (tuf.FormatError, ValueError), e:
    raise tuf.RepositoryError('Invalid date entered.')
  
  if expiration_date < time.time():
    message = 'The expiration date must occur after the current date.'
    raise tuf.RepositoryError(message)
  
  return input_date
github theupdateframework / tuf / tuf / repo / signercli.py View on Github external
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']

  # Determine the keyids associated with all the targets roles.
  try: 
    targets_keyids = tuf.repo.signerlib.get_target_keyids(metadata_directory)
  except tuf.FormatError, e:
    raise tuf.RepositoryError('Format error: '+str(e))

  # Extract the key files ending in a '.key' extension.
  key_paths = []
  for filename in os.listdir(keystore_directory):
    full_path = os.path.join(keystore_directory, filename)
    if filename.endswith('.key') and not os.path.isdir(full_path):
      key_paths.append(filename)

  # For each keyid listed in the keystore, search 'top_level_keyids'
  # and 'targets_keyids' for a possible entry.  'keyids_dict' stores
  # the associated roles for each keyid.
  keyids_dict = {}
  for keyid in key_paths:
    # Strip the '.key' extension.  These raw keyids are needed to search
    # for the roles attached to them in the metadata files.
    keyid = keyid[0:keyid.rfind('.key')]
github theupdateframework / tuf / tuf / repo / signercli.py View on Github external
# 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']

  # Determine the keyids associated with all the targets roles.
  try: 
    targets_keyids = tuf.repo.signerlib.get_target_keyids(metadata_directory)
  except tuf.FormatError, e:
    raise tuf.RepositoryError('Format error: '+str(e))

  # Extract the key files ending in a '.key' extension.