How to use the tuf.FormatError 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_ed25519_keys.py View on Github external
# Check for improperly formatted arguments.
    self.assertRaises(tuf.FormatError, ed25519_keys.verify_signature, 123, method,
                                       signature, data)
    
    # Signature method improperly formatted.
    self.assertRaises(tuf.FormatError, ed25519_keys.verify_signature, public, 123,
                                       signature, data)
   
    # Invalid signature method.
    self.assertRaises(tuf.UnknownMethodError, ed25519_keys.verify_signature, public,
                                       'unsupported_method', signature, data)
   
    # Signature not a string.
    self.assertRaises(tuf.FormatError, ed25519_keys.verify_signature, public, method,
                                       123, data)
   
    # Invalid signature length, which must be exactly 64 bytes..
    self.assertRaises(tuf.FormatError, ed25519_keys.verify_signature, public, method,
                                       'bad_signature', data)
    
    # Check for invalid signature and data.
    # Mismatched data.
    self.assertEqual(False, ed25519_keys.verify_signature(public, method,
                                                     signature, '123'))
   
    # Mismatched signature.
    bad_signature = b'a'*64 
    self.assertEqual(False, ed25519_keys.verify_signature(public, method,
                                                     bad_signature, data))
github theupdateframework / tuf / tests / repository_tool.py View on Github external
Updates the Target object's dictionary of delegated targets.
    
    
      The Targets object of 'rolename'.
    """
    
    # Do the arguments 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 any are improperly formatted.
    tuf.formats.ROLENAME_SCHEMA.check_match(rolename)
  
    if not isinstance(targets_object, Targets):
      raise tuf.FormatError(repr(targets_object) + ' is not a Targets object.')
   

    if rolename in self._delegated_roles:
      raise tuf.RoleAlreadyExistsError(repr(rolename) + ' already exists.')
    
    else:
      self._delegated_roles[rolename] = targets_object
github theupdateframework / tuf / tests / unit / deprecated / test_signercli.py View on Github external
#  Build config file.
    config_filepath = signerlib.build_config_file(config_dir, 365,
                                                  self.top_level_role_info)

    #  Create role's metadata.
    signable_meta = signerlib.generate_root_metadata(config_filepath, 8)


    # TESTS
    #  Test: normal case.
    signercli._sign_and_write_metadata(signable_meta, keyids, filename)

    #  Verify that the root meta file was created.
    self.assertTrue(os.path.exists(filename))

    Errors = (tuf.Error, tuf.FormatError)

    #  Test: invalid metadata.
    self.assertRaises(Errors, signercli._sign_and_write_metadata,
                      self.random_string(), keyids, filename)

    #  Test: invalid keyids
    invalid_keyids = self.random_string()
    self.assertRaises(Errors, signercli._sign_and_write_metadata,
                      signable_meta, invalid_keyids, filename)

    #  Test: invalid filename
    self.assertRaises(Errors, signercli._sign_and_write_metadata,
                      signable_meta, invalid_keyids, True)
github theupdateframework / tuf / tests / test_roledb.py View on Github external
def test_add_role(self):
    # Test conditions where the arguments are valid.
    self.assertEqual(0, len(tuf.roledb._roledb_dict)) 
    rolename = 'targets'
    roleinfo = {'keyids': ['123'], 'threshold': 1}
    rolename2 = 'targets/role1'
    self.assertEqual(None, tuf.roledb.add_role(rolename, roleinfo))
    self.assertEqual(1, len(tuf.roledb._roledb_dict))
    tuf.roledb.clear_roledb()
    self.assertEqual(None, tuf.roledb.add_role(rolename, roleinfo, True))
    self.assertEqual(1, len(tuf.roledb._roledb_dict))

    # Test conditions where the arguments are improperly formatted.
    self.assertRaises(tuf.FormatError, tuf.roledb.add_role, None, roleinfo) 
    self.assertRaises(tuf.FormatError, tuf.roledb.add_role, 123, roleinfo) 
    self.assertRaises(tuf.FormatError, tuf.roledb.add_role, [''], roleinfo) 
    self.assertRaises(tuf.FormatError, tuf.roledb.add_role, rolename, None) 
    self.assertRaises(tuf.FormatError, tuf.roledb.add_role, rolename, 123)
    self.assertRaises(tuf.FormatError, tuf.roledb.add_role, rolename, [''])
    self.assertRaises(tuf.FormatError, tuf.roledb.add_role,
                      rolename, roleinfo, 123)
    self.assertRaises(tuf.FormatError, tuf.roledb.add_role, rolename,
                      roleinfo, None)

    # Test condition where the role already exists in the role database.
    self.assertRaises(tuf.RoleAlreadyExistsError, tuf.roledb.add_role,
                      rolename, roleinfo)

    # Test condition where the parent role does not exist.
    tuf.roledb.clear_roledb()
github uptane / uptane / uptane_tuf_client.py View on Github external
def update_client():
  """Perform a simple update cycle on the current client."""
  global updater

  # TODO: Make sure this doesn't hide exceptions - or, if it does, be OK with
  # that.
  #tuf.log.remove_console_handler()

  # Does the tuf server url we're about to use have the correct format?
  try:
    tuf.formats.URL_SCHEMA.check_match(uptane_tuf_server.url)
  except tuf.FormatError as e:
    message = 'The repository mirror supplied is invalid.' 
    raise tuf.RepositoryError(message)

  # Set the repository mirrors.  This dictionary is needed by the Updater
  # class of updater.py.
  repository_mirrors = {'mirror': {'url_prefix': uptane_tuf_server.url,
      'metadata_path': 'metadata',
      'targets_path': '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)

  # Refresh top-level metadata.
  updater.refresh()
github theupdateframework / tuf / tuf / schema.py View on Github external
pattern:  The pattern to match, or None if re_object is provided.
      modifiers:  Flags to use when compiling the pattern.
      re_object:  A compiled regular expression object.
      re_name: Identifier for the regular expression object.
    """

    if not isinstance(pattern, six.string_types):
      if pattern is not None:
        raise tuf.FormatError(repr(pattern) + ' is not a string.')
        
    if re_object is None:
      if pattern is None:
        error = 'Cannot compare against an unset regular expression'
        raise tuf.FormatError(error)
      if not pattern.endswith('$'):
        pattern += '$'
      re_object = re.compile(pattern, modifiers)
    self._re_object = re_object
        
    if re_name is None:
      if pattern is not None:
        re_name = 'pattern /' + pattern + '/'
      else:
        re_name = 'pattern'
    self._re_name = re_name
github theupdateframework / tuf / tuf / keys.py View on Github external
if not private_pem:  
      raise tuf.FormatError('Required PEM header ' + repr(pem_header) + '\n not'
        ' found in PEM string: ' + repr(pem))
    
    else:
      raise tuf.FormatError('Required PEM header ' + repr(pem_header) + '\n not'
        ' found in private PEM string.')
  
  try:
    # Search for 'pem_footer' after the PEM header.
    footer_start = pem.index(pem_footer, header_start + len(pem_header))
  
  except ValueError:
    # Be careful not to print private key material in exception message.
    if not private_pem:  
      raise tuf.FormatError('Required PEM footer ' + repr(pem_footer) + '\n not'
        ' found in PEM string ' + repr(pem))

    else:
      raise tuf.FormatError('Required PEM footer ' + repr(pem_footer) + '\n not'
        ' found in private PEM string.')
  
  # Extract only the public portion of 'pem'.  Leading or trailing whitespace
  # is excluded.
  pem = pem[header_start:footer_start + len(pem_footer)]

  return pem
github theupdateframework / tuf / quickstart.py View on Github external
tuf.RepositoryError, if there was an error building the repository.

  
    The repository files created are written to disk to the current
    working directory.

  
    None.

  """

  # 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
github theupdateframework / tuf / tuf / keys.py View on Github external
else:
    pem_header = '-----BEGIN PUBLIC KEY-----'
    pem_footer = '-----END PUBLIC KEY-----'
  
  header_start = 0
  footer_start = 0

  # Raise error message if the expected header or footer is not found in 'pem'.
  try:
    header_start = pem.index(pem_header)
  
  except ValueError:
    # Be careful not to print private key material in exception message. 
    if not private_pem:  
      raise tuf.FormatError('Required PEM header ' + repr(pem_header) + '\n not'
        ' found in PEM string: ' + repr(pem))
    
    else:
      raise tuf.FormatError('Required PEM header ' + repr(pem_header) + '\n not'
        ' found in private PEM string.')
  
  try:
    # Search for 'pem_footer' after the PEM header.
    footer_start = pem.index(pem_footer, header_start + len(pem_header))
  
  except ValueError:
    # Be careful not to print private key material in exception message.
    if not private_pem:  
      raise tuf.FormatError('Required PEM footer ' + repr(pem_footer) + '\n not'
        ' found in PEM string ' + repr(pem))
github theupdateframework / tuf / tuf / repo / signercli.py View on Github external
Prompt the user for the expiration date of the metadata file.
    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