コード例 #1
0
 def take_action(self, parsed_args):
     environment = self.app.options.environment
     e = SecretsEnvironment(environment)
     if parsed_args.tmpdir:
         if not e.environment_exists() and not parsed_args.create:
             return (f"[-] environment '{str(e)}' does not exist; "
                     "use '--create' to create it")
         tmpdir = e.get_tmpdir_path(create_path=parsed_args.create)
         self._print(tmpdir, parsed_args.json)
     else:
         base_path = e.get_environment_path()
         subdir = parsed_args.subdir
         full_path = base_path if subdir is None \
             else os.path.join(base_path, *subdir)
         if not os.path.exists(full_path) and parsed_args.create:
             mode = 0o700
             os.makedirs(full_path, mode)
             if self.app_args.verbose_level > 1:
                 self.logger.info("[+] created %s", full_path)
         if parsed_args.exists:
             # Just check existance and return result
             exists = os.path.exists(full_path)
             if self.app_args.verbose_level > 1:
                 status = "exists" if exists else "does not exist"
                 self.logger.info("[+] environment path '%s' %s", full_path,
                                  status)
             return 0 if exists else 1
         else:
             self._print(full_path, parsed_args.json)
コード例 #2
0
class Test_SecretsEnvironment_args(unittest.TestCase):
    def setUp(self):
        self.cwd = os.getcwd()
        self.host = HOST
        self.keys_subdir = KEYS_SUBDIR
        self.envname = TESTENV
        self.basedir = Path(HOME) / (SECRETS_SUBDIR if sys.platform.startswith(
            'win') else '.' + SECRETS_SUBDIR)
        self.secrets_env = None
        with patch.dict('os.environ'):
            for v in ['D2_ENVIRONMENT', 'D2_SECRETS_BASEDIR']:
                try:
                    del os.environ[v]
                except KeyError as e:  # noqa
                    pass
            self.secrets_dir = secrets_dir(env=self.envname,
                                           basedir=self.basedir)
            self.keys_dir = keys_dir(secrets_dir=self.secrets_dir)
            self.keys_with_host_dir = keys_with_host_dir(
                keys_dir=self.keys_dir, host=self.host)
            self.secrets_env = SecretsEnvironment(
                environment=self.envname,
                secrets_basedir=self.basedir,
                create_root=True,
            )

    def tearDown(self):
        pass

    def test_no_D2_ENVIRONMENT(self):
        """Asserting D2_ENVIRONMENT not set in environment"""
        self.assertIsNone(os.environ.get('D2_ENVIRONMENT'))

    def test_environment_path(self):
        self.assertEqual(self.secrets_env.get_environment_path(),
                         self.secrets_dir)

    def test_environment_path_subdir(self):
        self.assertEqual(
            self.secrets_env.get_environment_path(subdir=self.keys_subdir),
            self.keys_dir)

    def test_environment_path_subdir_host(self):
        self.assertEqual(
            self.secrets_env.get_environment_path(subdir=KEYS_SUBDIR,
                                                  host=self.host),
            self.keys_with_host_dir)
コード例 #3
0
 def take_action(self, parsed_args):
     environment = parsed_args.environment
     if environment is None:
         environment = self.app.options.environment
     e = SecretsEnvironment(environment=environment)
     e.requires_environment()
     print_files = bool(parsed_args.no_files is False)
     atree(e.get_environment_path(),
           print_files=print_files,
           outfile=sys.stdout)
コード例 #4
0
class Test_SecretsEnvironment_with_env_vars(unittest.TestCase):
    def setUp(self):
        self.cwd = os.getcwd()
        self.host = HOST
        self.keys_subdir = KEYS_SUBDIR
        self.envname = TESTENV
        self.basedir = Path(HOME) / (SECRETS_SUBDIR if sys.platform.startswith(
            'win') else '.' + SECRETS_SUBDIR)
        self.secrets_env = None
        with patch.dict('os.environ'):
            os.environ['D2_ENVIRONMENT'] = str(self.envname)
            os.environ['D2_SECRETS_BASEDIR'] = str(self.basedir)
            self.secrets_dir = secrets_dir(env=self.envname,
                                           basedir=self.basedir)
            self.keys_dir = keys_dir(secrets_dir=self.secrets_dir)
            self.keys_with_host_dir = keys_with_host_dir(
                keys_dir=self.keys_dir, host=self.host)
            self.secrets_env = SecretsEnvironment(environment=self.envname,
                                                  create_root=True)  # noqa

    def tearDown(self):
        pass

    def test_environment(self):
        self.assertEqual(str(self.secrets_env), self.envname)

    def test_environment_path(self):
        self.assertEqual(self.secrets_env.get_environment_path(),
                         self.secrets_dir)

    def test_environment_path_subdir(self):
        self.assertEqual(
            self.secrets_env.get_environment_path(subdir=KEYS_SUBDIR),
            self.keys_dir)

    def test_environment_path_subdir_host(self):
        self.assertEqual(
            self.secrets_env.get_environment_path(subdir=KEYS_SUBDIR,
                                                  host=HOST),
            self.keys_with_host_dir)
コード例 #5
0
ファイル: delete.py プロジェクト: davedittrich/python_secrets
 def take_action(self, parsed_args):
     se = self.app.secrets
     choice = None
     if parsed_args.environment is not None:
         choice = parsed_args.environment
     elif stdin.isatty() and 'Bullet' in globals():
         # Give user a chance to choose.
         environments = os.listdir(se.get_secrets_basedir())
         choices = ['<CANCEL>'] + sorted(environments)
         cli = Bullet(prompt="\nSelect environment to delete:",
                      choices=choices,
                      indent=0,
                      align=2,
                      margin=1,
                      shift=0,
                      bullet="→",
                      pad_right=5)
         choice = cli.launch()
         if choice == "<CANCEL>":
             self.logger.info('[-] cancelled deleting environment')
             return
     else:
         # Can't involve user in getting a choice.
         sys.exit('[-] no environment specified to delete')
     # Environment chosen. Now do we need to confirm?
     e = SecretsEnvironment(choice)
     env_path = e.get_environment_path()
     if not parsed_args.force:
         if not stdin.isatty():
             output = atree(env_path, outfile=None, print_files=True)
             raise RuntimeError(
                 "[-] must use '--force' flag to delete an environment.\n"
                 "[-] the following will be deleted: \n"
                 f"{''.join([line for line in output])}")
         else:
             prompt = f"Type the name '{choice}' to confirm: "
             cli = Input(prompt,
                         default="",
                         word_color=colors.foreground["yellow"])
             confirm = cli.launch()
             if confirm != choice:
                 self.logger.info('[-] cancelled deleting environment')
                 return
     # We have confirmation or --force. Now safe to delete.
     # TODO(dittrich): Use safe_delete_file over file list
     if env_path.is_symlink():
         env_path.unlink()
         self.logger.info("[+] deleted alias '%s'", env_path)
     else:
         shutil.rmtree(env_path)
         self.logger.info("[+] deleted directory path '%s'", env_path)
コード例 #6
0
class Test_SecretsEnvironment_no_env_vars(unittest.TestCase):
    def setUp(self):
        self.cwd = os.getcwd()
        self.host = HOST
        self.keys_subdir = KEYS_SUBDIR
        self.secrets_env = None
        with patch.dict('os.environ'):
            for v in ['D2_ENVIRONMENT', 'D2_SECRETS_BASEDIR']:
                try:
                    del os.environ[v]
                except KeyError as e:  # noqa
                    pass
            self.secrets_env = SecretsEnvironment(create_root=True)

    def tearDown(self):
        pass

    def test_no_D2_ENVIRONMENT(self):
        """Asserting D2_ENVIRONMENT not set in environment"""
        self.assertIsNone(os.environ.get('D2_ENVIRONMENT'))

    def test_environment_path(self):
        assert type(self.secrets_env) is not type(str)
        env_path = self.secrets_env.get_environment_path()
        self.assertEqual(env_path, secrets_dir())

    def test_environment_path_subdir(self):
        self.assertEqual(
            self.secrets_env.get_environment_path(subdir=self.keys_subdir),
            keys_dir())

    def test_environment_path_subdir_host(self):
        self.assertEqual(
            self.secrets_env.get_environment_path(subdir=KEYS_SUBDIR,
                                                  host=self.host),
            keys_with_host_dir(host=self.host))
コード例 #7
0
ファイル: create.py プロジェクト: davedittrich/python_secrets
 def take_action(self, parsed_args):
     secrets_basedir = self.app.secrets_basedir
     if parsed_args.alias is not None:
         if len(parsed_args.env) != 1:
             raise RuntimeError(
                 '[-] --alias requires one source environment')
         se = SecretsEnvironment(
             environment=parsed_args.alias,
             secrets_basedir=secrets_basedir,
             create_root=parsed_args.force,
         )
         se.environment_create(
             source=parsed_args.env[0],
             alias=True
         )
         if se.environment_exists():
             self.logger.info(
                 "[+] environment '%s' aliased to '%s'",
                 parsed_args.alias,
                 parsed_args.env[0]
             )
         else:
             raise RuntimeError('[-] creating environment failed')
     else:
         # Default to app environment identifier
         if len(parsed_args.env) == 0:
             parsed_args.env = list(self.app.environment)
         for environment in parsed_args.env:
             se = SecretsEnvironment(
                 environment=environment,
                 secrets_basedir=secrets_basedir,
                 create_root=True,
             )
             se.environment_create(source=parsed_args.clone_from)
             self.logger.info(
                 "[+] environment '%s' (%s) created",
                 environment,
                 se.get_environment_path()
             )
             if parsed_args.clone_from:
                 se.read_secrets(from_descriptions=True)
                 se.write_secrets()