def test_provide_user(request, salt_factories, configure_kwargs):
    master_config = salt_factories.configure_master(request, "master-1", **configure_kwargs)
    if not configure_kwargs:
        # salt-factories injects the current username
        assert master_config["user"] is not None
        assert master_config["user"] == running_username()
    else:
        # salt-factories does not override the passed user value
        assert master_config["user"] != running_username()
        assert master_config["user"] == "blah"
def test_provide_user(salt_factories, configure_kwargs):
    minion_config = salt_factories.get_salt_minion_daemon(
        random_string("minion-"), **configure_kwargs).config
    if not configure_kwargs:
        # salt-factories injects the current username
        assert minion_config["user"] is not None
        assert minion_config["user"] == running_username()
    else:
        # salt-factories does not override the passed user value
        assert minion_config["user"] != running_username()
        assert minion_config["user"] == "blah"
Ejemplo n.º 3
0
    def final_common_config_tweaks(self, config, role):
        config.setdefault("engines", [])
        if "pytest" not in config["engines"]:
            config["engines"].append("pytest")

        if "engines_dirs" not in config:
            config["engines_dirs"] = []
        config["engines_dirs"].insert(
            0, str(FactoriesManager.get_salt_engines_path()))
        config.setdefault("user", running_username())
        if not config["user"]:
            # If this value is empty, None, False, just remove it
            config.pop("user")
        if "log_forwarding_consumer" not in config:
            # Still using old logging, let's add our custom log handler
            if "log_handlers_dirs" not in config:
                config["log_handlers_dirs"] = []
            config["log_handlers_dirs"].insert(
                0, str(FactoriesManager.get_salt_log_handlers_path()))

        pytest_key = "pytest-{}".format(role)
        if pytest_key not in config:
            config[pytest_key] = {}

        pytest_config = config[pytest_key]
        if "log" not in pytest_config:
            pytest_config["log"] = {}

        log_config = pytest_config["log"]
        log_config.setdefault("host", self.log_server_host)
        log_config.setdefault("port", self.log_server_port)
        log_config.setdefault("level", self.log_server_level)
Ejemplo n.º 4
0
 def verify_config(cls, config):
     salt.utils.verify.verify_env(
         [str(pathlib.Path(config["log_file"]).parent)],
         running_username(),
         pki_dir=config.get("pki_dir") or "",
         root_dir=config["root_dir"],
     )
Ejemplo n.º 5
0
    def final_common_config_tweaks(self, config, role):
        """
        Final common tweaks to the configuration.
        """
        config.setdefault("engines", [])
        if "pytest" not in config["engines"]:
            config["engines"].append("pytest")

        config.setdefault("user", running_username())
        if not config["user"]:  # pragma: no cover
            # If this value is empty, None, False, just remove it
            config.pop("user")

        pytest_key = "pytest-{}".format(role)
        if pytest_key not in config:
            config[pytest_key] = {}

        pytest_config = config[pytest_key]
        if "log" not in pytest_config:  # pragma: no cover
            pytest_config["log"] = {}

        log_config = pytest_config["log"]
        log_config.setdefault("host", self.log_server_host)
        log_config.setdefault("port", self.log_server_port)
        log_config.setdefault("level", "debug")
Ejemplo n.º 6
0
 def verify_config(cls, config):
     salt.utils.verify.verify_env(
         cls._get_verify_config_entries(config),
         running_username(),
         pki_dir=config.get("pki_dir") or "",
         root_dir=config["root_dir"],
     )
Ejemplo n.º 7
0
    def get_salt_ssh_cli(self,
                         factory_class=cli.ssh.SaltSshCliFactory,
                         roster_file=None,
                         target_host=None,
                         client_key=None,
                         ssh_user=None,
                         **factory_class_kwargs):
        """
        Return a `salt-ssh` CLI process for this master instance

        Args:
            roster_file(str):
                The roster file to use
            target_host(str):
                The target host address to connect to
            client_key(str):
                The path to the private ssh key to use to connect
            ssh_user(str):
                The remote username to connect as
        """
        script_path = cli_scripts.generate_script(
            self.factories_manager.scripts_dir,
            "salt-ssh",
            code_dir=self.factories_manager.code_dir,
            inject_coverage=self.factories_manager.inject_coverage,
            inject_sitecustomize=self.factories_manager.inject_sitecustomize,
        )
        return factory_class(cli_script_name=script_path,
                             config=self.config.copy(),
                             roster_file=roster_file,
                             target_host=target_host,
                             client_key=client_key,
                             ssh_user=ssh_user or running_username(),
                             **factory_class_kwargs)
Ejemplo n.º 8
0
 def verify_config(cls, config):
     """
     Verify the configuration dictionary.
     """
     salt.utils.verify.verify_env(
         cls._get_verify_config_entries(config),
         running_username(),
         pki_dir=config.get("pki_dir") or "",
         root_dir=config["root_dir"],
     )
Ejemplo n.º 9
0
    def __attrs_post_init__(self):
        """
        Post attrs initialization routines.
        """
        if self.authorized_keys is None:
            self.authorized_keys = []
        if self.sshd_config_dict is None:
            self.sshd_config_dict = {}
        if self.listen_address is None:
            self.listen_address = "127.0.0.1"
        if self.listen_port is None:
            self.listen_port = ports.get_unused_localhost_port()
        self.check_ports = [self.listen_port]
        if isinstance(self.config_dir, str):
            self.config_dir = pathlib.Path(self.config_dir)
        elif not isinstance(self.config_dir, pathlib.Path):
            # A py local path?
            self.config_dir = pathlib.Path(self.config_dir.strpath)
        self.config_dir.chmod(0o0700)
        authorized_keys_file = self.config_dir / "authorized_keys"

        # Let's generate the client key
        self.client_key = self._generate_client_ecdsa_key()
        with open("{}.pub".format(self.client_key)) as rfh:
            pubkey = rfh.read().strip()
            log.debug("SSH client pub key: %r", pubkey)
            self.authorized_keys.append(pubkey)

        # Write the authorized pub keys to file
        with open(str(authorized_keys_file), "w") as wfh:
            wfh.write("\n".join(self.authorized_keys))

        authorized_keys_file.chmod(0o0600)

        with open(str(authorized_keys_file)) as rfh:
            log.debug("AuthorizedKeysFile contents:\n%s", rfh.read())

        _default_config = {
            "ListenAddress": self.listen_address,
            "PermitRootLogin": "******" if running_username() == "root" else "no",
            "ChallengeResponseAuthentication": "no",
            "PasswordAuthentication": "no",
            "PubkeyAuthentication": "yes",
            "PrintMotd": "no",
            "PidFile": self.config_dir / "sshd.pid",
            "AuthorizedKeysFile": authorized_keys_file,
        }
        if self.sshd_config_dict:
            _default_config.update(self.sshd_config_dict)
        self.sshd_config = _default_config
        self._write_config()
        super().__attrs_post_init__()
Ejemplo n.º 10
0
 def verify_config(cls, config):
     prepend_root_dirs = []
     for config_key in ("log_file", ):
         if urllib.parse.urlparse(config.get(config_key, "")).scheme == "":
             prepend_root_dirs.append(config_key)
     if prepend_root_dirs:
         salt.config.prepend_root_dir(config, prepend_root_dirs)
     salt.utils.verify.verify_env(
         [str(pathlib.Path(config["log_file"]).parent)],
         running_username(),
         pki_dir=config.get("pki_dir") or "",
         root_dir=config["root_dir"],
     )
Ejemplo n.º 11
0
    def _ssh_keygen(self, key_filename, key_type, bits, comment=None):
        try:
            ssh_keygen = self._ssh_keygen_path
        except AttributeError:
            ssh_keygen = self._ssh_keygen_path = shutil.which("ssh-keygen")

        if comment is None:
            comment = "{user}@{host}-{date}".format(
                user=running_username(),
                host=socket.gethostname(),
                date=datetime.utcnow().strftime("%Y-%m-%d"),
            )

        cmdline = [
            ssh_keygen,
            "-t",
            key_type,
            "-b",
            bits,
            "-C",
            comment,
            "-f",
            key_filename,
            "-P",
            "",
        ]
        try:
            subprocess.run(
                cmdline,
                cwd=str(self.config_dir),
                check=True,
                universal_newlines=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
        except subprocess.CalledProcessError as exc:
            raise FactoryFailure(
                "Failed to generate ssh key.",
                cmdline=exc.args,
                stdout=exc.stdout,
                stderr=exc.stderr,
                exitcode=exc.returncode,
            )
Ejemplo n.º 12
0
def test_provide_user(salt_factories, mom, configure_kwargs):
    syndic_id = random_string("syndic-")
    syndic = mom.get_salt_syndic_daemon(syndic_id, **configure_kwargs)

    if not configure_kwargs:
        # salt-factories injects the current username
        assert syndic.master.config["user"] is not None
        assert syndic.master.config["user"] == running_username()
        assert syndic.minion.config["user"] is not None
        assert syndic.minion.config["user"] == running_username()
        assert syndic.config["user"] is not None
        assert syndic.config["user"] == running_username()
    else:
        assert syndic.master.config["user"] != running_username()
        assert syndic.master.config["user"] == "blah"
        assert syndic.minion.config["user"] != running_username()
        assert syndic.minion.config["user"] == "blah"
        # salt-factories does not override the passed user value
        assert syndic.config["user"] != running_username()
        assert syndic.config["user"] == "blah"