diff --git a/src/azure-cli/azure/cli/command_modules/mysql/_util.py b/src/azure-cli/azure/cli/command_modules/mysql/_util.py index 7e20ebf304b..2f2e97496df 100644 --- a/src/azure-cli/azure/cli/command_modules/mysql/_util.py +++ b/src/azure-cli/azure/cli/command_modules/mysql/_util.py @@ -28,7 +28,7 @@ from azure.core.paging import ItemPaged from azure.core.rest import HttpRequest from azure.cli.core.commands import LongRunningOperation, AzArgumentContext, _is_poller -from azure.cli.core.azclierror import RequiredArgumentMissingError, InvalidArgumentValueError, AuthenticationError +from azure.cli.core.azclierror import RequiredArgumentMissingError, InvalidArgumentValueError, AuthenticationError, ClientRequestError from azure.cli.command_modules.role.custom import create_service_principal_for_rbac from azure.mgmt.mysqlflexibleservers import models from azure.mgmt.resource.resources.models import ResourceGroup @@ -433,9 +433,15 @@ def run_cmd(args, **kwargs): return core_run_cmd(args, **kwargs) -def run_subprocess(command, stdout_show=None): +def run_subprocess(command, stdout_show=None, input_data=None): commands = list(command) commands[0] = resolve_executable(commands[0]) + if input_data is not None: + # Keep caller-provided input out of subprocess diagnostics. + process = subprocess.run(commands, input=input_data, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + if process.returncode: + raise ClientRequestError("Command '{}' failed with exit code {}.".format(commands[0], process.returncode)) + return if stdout_show: process = subprocess.Popen(commands) else: @@ -460,25 +466,17 @@ def register_credential_secrets(cmd, database_engine, server, repository): app.pop('displayName') app.pop('name') - app_key_val = [] - for key, val in app.items(): - app_key_val.append('"{}": "{}"'.format(key, val)) - - app_json = ',\n '.join(app_key_val) - app_json = '{\n ' + app_json + '\n}' - credential_file = "./temp_app_credential.txt" - with open(credential_file, "w") as f: - f.write(app_json) - run_subprocess(["gh", "secret", "set", AZURE_CREDENTIALS, "--repo", repository, "<", credential_file]) - os.remove(credential_file) + run_subprocess(['gh', 'secret', 'set', AZURE_CREDENTIALS, '--repo', repository], + input_data=json.dumps(app).encode('utf-8')) def register_connection_secrets(server, database_name, administrator_login, administrator_login_password, repository, connection_string_name): - logger.warning("Added secret %s to github repository", connection_string_name) connection_string = "Server={}; Port=3306; Database={}; Uid={}; Pwd={}; SslMode=Preferred;".format( server.fully_qualified_domain_name, database_name, administrator_login, administrator_login_password) - run_subprocess(['gh', 'secret', 'set', connection_string_name, '--repo', repository, '-b', connection_string]) + run_subprocess(['gh', 'secret', 'set', connection_string_name, '--repo', repository], + input_data=connection_string.encode('utf-8')) + logger.warning("Added secret %s to github repository", connection_string_name) def fill_action_template(cmd, database_engine, server, database_name, administrator_login, diff --git a/src/azure-cli/azure/cli/command_modules/postgresql/tests/latest/test_deploy_commands.py b/src/azure-cli/azure/cli/command_modules/postgresql/tests/latest/test_deploy_commands.py index 59d57c393c9..274c33e6d44 100644 --- a/src/azure-cli/azure/cli/command_modules/postgresql/tests/latest/test_deploy_commands.py +++ b/src/azure-cli/azure/cli/command_modules/postgresql/tests/latest/test_deploy_commands.py @@ -132,7 +132,7 @@ def test_setup_uploads_missing_credentials_through_stdin(self): self.upload.assert_called_once_with( [self.executable, 'secret', 'set', util.AZURE_CREDENTIALS, '--repo', 'owner/repository'], - input=mock.ANY, capture_output=True, check=False) + input=mock.ANY, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) self.assertEqual(json.loads(self.upload.call_args.kwargs['input']), self.credentials) self.files.assert_any_call(self.workflow, 'w', encoding='utf8') self.assertEqual(self.git.call_args_list, [ @@ -143,7 +143,9 @@ def test_setup_uploads_missing_credentials_through_stdin(self): def test_setup_stops_after_credential_upload_failure(self): self.upload.return_value.returncode = 1 - self.upload.return_value.stderr = self.credentials['clientSecret'].encode('UTF-8') + self.upload.return_value.stdout = b'unexpected upload stdout' + self.upload.return_value.stderr = ( + self.credentials['clientSecret'].encode('UTF-8') + b' unexpected upload stderr') with self.assertLogs(util.logger.name, level='WARNING') as logs: with self.assertRaisesRegex(ClientRequestError, 'Failed to set the AZURE_CREDENTIALS secret') as error: deploy.github_actions_setup( @@ -151,11 +153,19 @@ def test_setup_stops_after_credential_upload_failure(self): 'schema file.sql', 'owner/repository', action_name='deploy database', branch='feature/database', allow_push=True) - self.upload.assert_called_once() + self.upload.assert_called_once_with( + [self.executable, 'secret', 'set', util.AZURE_CREDENTIALS, '--repo', 'owner/repository'], + input=mock.ANY, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) self.git.assert_not_called() self.files.assert_not_called() - self.assertNotIn(self.credentials['clientSecret'], str(error.exception)) - self.assertNotIn(self.credentials['clientSecret'], '\n'.join(logs.output)) + self.assertEqual( + str(error.exception), + 'Failed to set the AZURE_CREDENTIALS secret in the GitHub repository (exit code 1).') + self.assertEqual(error.exception.recommendations, [ + 'Check your GitHub CLI authentication and repository permissions, then retry.']) + diagnostics = '\n'.join([str(error.exception), *error.exception.recommendations, *logs.output]) + for value in (self.credentials['clientSecret'], 'unexpected upload stdout', 'unexpected upload stderr'): + self.assertNotIn(value, diagnostics) @unittest.skipUnless(sys.platform == 'win32', 'Windows executable search semantics') diff --git a/src/azure-cli/azure/cli/command_modules/postgresql/tests/unit/test_deploy_commands.py b/src/azure-cli/azure/cli/command_modules/postgresql/tests/unit/test_deploy_commands.py index 6d3ec32accd..eb368f263e5 100644 --- a/src/azure-cli/azure/cli/command_modules/postgresql/tests/unit/test_deploy_commands.py +++ b/src/azure-cli/azure/cli/command_modules/postgresql/tests/unit/test_deploy_commands.py @@ -76,16 +76,15 @@ def test_setup_pins_all_probe_login_secret_and_git_launches(self): [self.git, 'rev-parse', '--show-toplevel'], [self.gh, 'secret', 'list', '--repo', 'owner/repo'], [self.gh, 'secret', 'set', 'AZURE_CREDENTIALS', '--repo', 'owner/repo'], + [self.gh, 'secret', 'set', 'SERVER_DATABASE_POSTGRESQL_CONNECTION_STRING', '--repo', 'owner/repo'], [self.git, 'rev-parse', '--show-toplevel']]) - credentials = self.run.call_args_list[-2].kwargs + credentials = self.run.call_args_list[-3].kwargs self.assertEqual(json.loads(credentials['input']), { 'clientId': 'app', 'clientSecret': 'unused', 'tenantId': 'tenant', 'subscriptionId': 'sub'}) + self.assertIn(b'host=server.example', self.run.call_args_list[-2].kwargs['input']) launches = [c.args[0] for c in self.popen.call_args_list] self.assertEqual(launches[0], [self.gh, 'auth', 'login']) - self.assertEqual(launches[1][:7], [ - self.gh, 'secret', 'set', 'SERVER_DATABASE_POSTGRESQL_CONNECTION_STRING', '--repo', 'owner/repo', '-b']) - self.assertEqual(len(launches[1]), 8) - self.assertEqual(launches[2:], [ + self.assertEqual(launches[1:], [ [self.git, 'add', 'C:/work with spaces/.github/workflows/deploy action.yml'], [self.git, 'commit', '-m', 'Add github action file'], [self.git, 'push', 'origin', 'topic branch']]) diff --git a/src/azure-cli/azure/cli/command_modules/postgresql/utils/_flexible_server_util.py b/src/azure-cli/azure/cli/command_modules/postgresql/utils/_flexible_server_util.py index 84699a9fa2d..c88a7a32f52 100644 --- a/src/azure-cli/azure/cli/command_modules/postgresql/utils/_flexible_server_util.py +++ b/src/azure-cli/azure/cli/command_modules/postgresql/utils/_flexible_server_util.py @@ -284,12 +284,19 @@ def run_cmd(args, **kwargs): return core_run_cmd(args, **kwargs) -def run_subprocess(command, stdout_show=None): - command = [resolve_executable(command[0])] + command[1:] +def run_subprocess(command, stdout_show=None, input_data=None): + commands = list(command) + commands[0] = resolve_executable(commands[0]) + if input_data is not None: + # Keep caller-provided input out of subprocess diagnostics. + process = subprocess.run(commands, input=input_data, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + if process.returncode: + raise ClientRequestError("Command '{}' failed with exit code {}.".format(commands[0], process.returncode)) + return if stdout_show: - process = subprocess.Popen(command, shell=False) + process = subprocess.Popen(commands, shell=False) else: - process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) + process = subprocess.Popen(commands, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) process.wait() if process.returncode: logger.warning(process.stderr.read().strip().decode('UTF-8')) @@ -310,7 +317,7 @@ def register_credential_secrets(cmd, database_engine, server, repository, gh_pat process = subprocess.run( [gh_path, 'secret', 'set', AZURE_CREDENTIALS, '--repo', repository], - input=json.dumps(app).encode('UTF-8'), capture_output=True, check=False) + input=json.dumps(app).encode('utf-8'), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) if process.returncode: raise ClientRequestError( 'Failed to set the AZURE_CREDENTIALS secret in the GitHub repository (exit code {}).'.format( @@ -320,9 +327,10 @@ def register_credential_secrets(cmd, database_engine, server, repository, gh_pat def register_connection_secrets(cmd, database_engine, server, database_name, administrator_login, administrator_login_password, repository, connection_string_name, gh_path=None): gh_path = resolve_executable(gh_path or "gh") - logger.warning("Added secret %s to github repository", connection_string_name) connection_string = "host={} port=5432 dbname={} user={} password={} sslmode=require".format(server.fully_qualified_domain_name, database_name, administrator_login, administrator_login_password) - run_subprocess([gh_path, 'secret', 'set', connection_string_name, '--repo', repository, '-b', connection_string]) + run_subprocess([gh_path, 'secret', 'set', connection_string_name, '--repo', repository], + input_data=connection_string.encode('utf-8')) + logger.warning("Added secret %s to github repository", connection_string_name) def fill_action_template(cmd, database_engine, server, database_name, administrator_login, administrator_login_password, file_name, action_name, repository, gh_path=None, git_path=None): diff --git a/src/azure-cli/azure/cli/command_modules/rdbms/_flexible_server_util.py b/src/azure-cli/azure/cli/command_modules/rdbms/_flexible_server_util.py index c870582db9c..9b8800e5d21 100644 --- a/src/azure-cli/azure/cli/command_modules/rdbms/_flexible_server_util.py +++ b/src/azure-cli/azure/cli/command_modules/rdbms/_flexible_server_util.py @@ -6,18 +6,20 @@ # pylint: disable=unused-argument, line-too-long, import-outside-toplevel, raise-missing-from import datetime as dt from datetime import datetime +import errno +import json import os import random import subprocess import secrets -import shlex import string +import sys import yaml from knack.log import get_logger from knack.prompting import prompt_y_n, NoTTYException from azure.mgmt.core.tools import parse_resource_id -from azure.cli.core.util import CLIError, run_cmd -from azure.cli.core.azclierror import AuthenticationError +from azure.cli.core.util import CLIError, get_safe_executable_path, run_cmd as core_run_cmd +from azure.cli.core.azclierror import AuthenticationError, ClientRequestError from azure.core.exceptions import HttpResponseError from azure.core.paging import ItemPaged from azure.cli.core.commands.client_factory import get_subscription_id @@ -298,8 +300,32 @@ def _resolve_api_version(client, provider_namespace, resource_type, parent_path) .format(resource_type)) -def run_subprocess(command, stdout_show=None): - commands = shlex.split(command) +def resolve_executable(executable): + """Bind Windows tool launches to installed executables without changing Unix lookup.""" + if sys.platform != 'win32' or os.path.dirname(executable): + return executable + name = executable if os.path.splitext(executable)[1] else executable + '.exe' + resolved = get_safe_executable_path(name) + if resolved is None: + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), executable) + return resolved + + +def run_cmd(args, **kwargs): + if isinstance(args, list) and args: + args = [resolve_executable(args[0]), *args[1:]] + return core_run_cmd(args, **kwargs) + + +def run_subprocess(command, stdout_show=None, input_data=None): + commands = list(command) + commands[0] = resolve_executable(commands[0]) + if input_data is not None: + # Keep caller-provided input out of subprocess diagnostics. + process = subprocess.run(commands, input=input_data, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + if process.returncode: + raise ClientRequestError("Command '{}' failed with exit code {}.".format(commands[0], process.returncode)) + return if stdout_show: process = subprocess.Popen(commands) else: @@ -321,23 +347,15 @@ def register_credential_secrets(cmd, database_engine, server, repository): app.pop('displayName') app.pop('name') - app_key_val = [] - for key, val in app.items(): - app_key_val.append('"{}": "{}"'.format(key, val)) - - app_json = ',\n '.join(app_key_val) - app_json = '{\n ' + app_json + '\n}' - credential_file = "./temp_app_credential.txt" - with open(credential_file, "w") as f: - f.write(app_json) - run_subprocess('gh secret set {} --repo {} < {}'.format(AZURE_CREDENTIALS, repository, credential_file)) - os.remove(credential_file) + run_subprocess(['gh', 'secret', 'set', AZURE_CREDENTIALS, '--repo', repository], + input_data=json.dumps(app).encode('utf-8')) def register_connection_secrets(cmd, database_engine, server, database_name, administrator_login, administrator_login_password, repository, connection_string_name): - logger.warning("Added secret %s to github repository", connection_string_name) connection_string = "Server={}; Port=3306; Database={}; Uid={}; Pwd={}; SslMode=Preferred;".format(server.fully_qualified_domain_name, database_name, administrator_login, administrator_login_password) - run_subprocess('gh secret set {} --repo {} -b"{}"'.format(connection_string_name, repository, connection_string)) + run_subprocess(['gh', 'secret', 'set', connection_string_name, '--repo', repository], + input_data=connection_string.encode('utf-8')) + logger.warning("Added secret %s to github repository", connection_string_name) def fill_action_template(cmd, database_engine, server, database_name, administrator_login, administrator_login_password, file_name, action_name, repository): diff --git a/src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_common.py b/src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_common.py index 6974f6951ba..617af621a6f 100644 --- a/src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_common.py +++ b/src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_common.py @@ -11,9 +11,9 @@ from knack.log import get_logger from knack.util import CLIError from urllib.request import urlretrieve -from azure.cli.core.util import sdk_no_wait, user_confirmation, run_cmd +from azure.cli.core.util import sdk_no_wait, user_confirmation from azure.cli.core.azclierror import ClientRequestError -from ._flexible_server_util import run_subprocess +from ._flexible_server_util import run_cmd, run_subprocess from .validators import validate_public_access_server, validate_resource_group, check_resource_group logger = get_logger(__name__) @@ -195,17 +195,20 @@ def github_actions_run(action_name, branch): gitcli_check_and_login() logger.warning("Created an event for %s.yml in branch %s", action_name, branch) - run_subprocess("gh workflow run {}.yml --ref {}".format(action_name, branch)) + run_subprocess(["gh", "workflow", "run", action_name + ".yml", "--ref", branch]) def gitcli_check_and_login(): - output = run_cmd(["gh"], capture_output=True) + try: + output = run_cmd(["gh"], capture_output=True) + except FileNotFoundError as ex: + raise ClientRequestError('Please install "Github CLI" to run this command.') from ex if output.returncode: raise ClientRequestError('Please install "Github CLI" to run this command.') output = run_cmd(["gh", "auth", "status"], capture_output=True) if output.returncode: - run_subprocess("gh auth login", stdout_show=True) + run_subprocess(["gh", "auth", "login"], stdout_show=True) # Custom functions for server logs diff --git a/src/azure-cli/azure/cli/command_modules/rdbms/tests/latest/test_deploy_setup.py b/src/azure-cli/azure/cli/command_modules/rdbms/tests/latest/test_deploy_setup.py new file mode 100644 index 00000000000..8907c0cc48d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/rdbms/tests/latest/test_deploy_setup.py @@ -0,0 +1,369 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +import hashlib +import json +import ntpath +import os +import subprocess +import sys +import tempfile +import unittest +from types import SimpleNamespace +from unittest.mock import Mock, patch + +from azure.cli.core.azclierror import ClientRequestError +from azure.cli.command_modules.mysql import _util as mysql +from azure.cli.command_modules.mysql import custom as mysql_commands +from azure.cli.command_modules.postgresql.commands import deploy_commands as postgresql_commands +from azure.cli.command_modules.postgresql.utils import _flexible_server_util as postgresql +from azure.cli.command_modules.rdbms import _flexible_server_util as rdbms +from azure.cli.command_modules.rdbms import flexible_server_custom_common as rdbms_commands + + +MODULES = (mysql, postgresql, rdbms) + + +class DeploySetupTest(unittest.TestCase): + + def setUp(self): + for module in MODULES: + resolver = patch.object(module, 'resolve_executable', side_effect=lambda executable: executable) + resolver.start() + self.addCleanup(resolver.stop) + resolver = patch.object(postgresql_commands, 'resolve_executable', side_effect=lambda executable: executable) + resolver.start() + self.addCleanup(resolver.stop) + self.cmd = SimpleNamespace(cli_ctx=object()) + self.server = SimpleNamespace( + id='/subscriptions/test-sub/resourceGroups/test-rg/' + 'providers/Microsoft.DBforMySQL/flexibleServers/test-server', + name='test-server', + fully_qualified_domain_name='test.invalid') + self.secret = 'dummy-"quoted"\\secret\n\u00e9' + self.repository = 'test-owner/test-repository' + + def _app(self): + return { + 'appId': 'test-app', + 'password': self.secret, + 'tenant': 'test-tenant', + 'displayName': 'test-display', + 'name': 'test-name', + } + + def _register(self, module, kind): + if kind == 'credential': + module.register_credential_secrets( + self.cmd, 'postgresql' if module is postgresql else 'mysql', + self.server, self.repository) + else: + kwargs = dict( + server=self.server, database_name='test-db', + administrator_login='test-user', administrator_login_password=self.secret, + repository=self.repository, connection_string_name='TEST_CONNECTION') + if module is not mysql: + kwargs.update(cmd=self.cmd, database_engine='postgresql' if module is postgresql else 'mysql') + module.register_connection_secrets(**kwargs) + + def test_registration_uses_standard_input(self): + for module in MODULES: + for kind in ('credential', 'connection'): + with self.subTest(module=module.__name__, kind=kind), \ + patch.object(module, 'create_service_principal_for_rbac', return_value=self._app()), \ + patch.object(module, 'get_subscription_id', return_value='test-sub'), \ + patch.object(module, 'open', create=True) as open_file, \ + patch.object(module.os, 'remove') as remove_file, \ + patch.object(module.subprocess, 'run', return_value=Mock(returncode=0)) as run: + self._register(module, kind) + open_file.assert_not_called() + remove_file.assert_not_called() + name = 'AZURE_CREDENTIALS' if kind == 'credential' else 'TEST_CONNECTION' + self.assertEqual( + run.call_args.args, + (['gh', 'secret', 'set', name, '--repo', self.repository],)) + kwargs = run.call_args.kwargs + self.assertEqual(kwargs['stdout'], subprocess.DEVNULL) + self.assertEqual(kwargs['stderr'], subprocess.DEVNULL) + self.assertFalse(kwargs.get('shell', False)) + self.assertIsInstance(kwargs['input'], bytes) + if kind == 'credential': + self.assertEqual(json.loads(kwargs['input']), { + 'clientId': 'test-app', 'clientSecret': self.secret, + 'tenantId': 'test-tenant', 'subscriptionId': 'test-sub'}) + else: + value = kwargs['input'].decode('utf-8') + self.assertIn(self.secret, value) + self.assertIn('test.invalid', value) + self.assertIn('test-db', value) + self.assertIn('test-user', value) + + def test_registration_failure_does_not_report_success(self): + for module in MODULES: + for kind in ('credential', 'connection'): + for failure in (FileNotFoundError('gh missing'), PermissionError('launch denied'), + OSError('pipe failure'), 'nonzero'): + with self.subTest(module=module.__name__, kind=kind, failure=str(failure)), \ + patch.object(module, 'create_service_principal_for_rbac', return_value=self._app()), \ + patch.object(module, 'get_subscription_id', return_value='test-sub'), \ + patch.object(module, 'open', create=True) as open_file, \ + patch.object(module.os, 'remove') as remove_file, \ + patch.object(module, 'logger') as logger, \ + patch.object(module.subprocess, 'run') as run: + if failure == 'nonzero': + run.return_value = Mock(returncode=1, stdout=self.secret, stderr=self.secret) + error_type = ClientRequestError + else: + run.side_effect = failure + error_type = type(failure) + with self.assertRaises(error_type) as raised: + self._register(module, kind) + self.assertNotIn(self.secret, str(raised.exception)) + self.assertNotIn(self.secret, str(logger.mock_calls)) + self.assertNotIn('Added secret', str(logger.mock_calls)) + open_file.assert_not_called() + remove_file.assert_not_called() + + def test_upload_failure_stops_workflow_generation(self): + for module in MODULES: + with self.subTest(module=module.__name__), \ + patch.object(module, 'get_git_root_dir', return_value='test-root'), \ + patch.object(module.os.path, 'exists', return_value=True), \ + patch.object(module, 'run_cmd', return_value=Mock(stdout=b'')), \ + patch.object(module, 'create_service_principal_for_rbac', return_value=self._app()), \ + patch.object(module, 'get_subscription_id', return_value='test-sub'), \ + patch.object(module.subprocess, 'run', return_value=Mock(returncode=1)), \ + patch.object(module, 'register_connection_secrets') as connection, \ + patch.object(module, 'open', create=True) as open_file: + with self.assertRaises(ClientRequestError): + module.fill_action_template( + self.cmd, 'mysql', self.server, 'test-db', 'test-user', + self.secret, 'query.sql', 'test-action', self.repository) + connection.assert_not_called() + open_file.assert_not_called() + + def test_stdin_round_trip_with_local_process(self): + payload = self.secret.encode('utf-8') + digest = hashlib.sha256(payload).hexdigest() + script = ( + 'import hashlib, sys; ' + 'sys.exit(0 if hashlib.sha256(sys.stdin.buffer.read()).hexdigest() == sys.argv[1] else 1)' + ) + for module in MODULES: + with self.subTest(module=module.__name__): + module.run_subprocess([sys.executable, '-c', script, digest], input_data=payload) + + def test_setup_stops_before_git_commit_on_upload_failure(self): + self.server.network = SimpleNamespace(public_network_access='Enabled') + for commands in (mysql_commands, postgresql_commands): + with self.subTest(module=commands.__name__), \ + patch.object(commands, 'gitcli_check_and_login'), \ + patch.object(commands, 'fill_action_template', side_effect=ClientRequestError('Upload failed')), \ + patch.object(commands, 'run_subprocess') as run: + with self.assertRaises(ClientRequestError): + commands.github_actions_setup( + self.cmd, Mock(get=Mock(return_value=self.server)), + 'test-rg', 'test-server', 'test-db', 'test-user', self.secret, + 'query.sql', self.repository) + run.assert_not_called() + + def test_missing_gh_stops_setup(self): + self.server.network = SimpleNamespace(public_network_access='Enabled') + for commands in (mysql_commands, postgresql_commands): + with self.subTest(module=commands.__name__), \ + patch.object(commands, 'run_cmd', side_effect=FileNotFoundError('gh missing')), \ + patch.object(commands, 'fill_action_template') as fill, \ + patch.object(commands, 'run_subprocess') as run: + with self.assertRaises(ClientRequestError): + commands.github_actions_setup( + self.cmd, Mock(get=Mock(return_value=self.server)), + 'test-rg', 'test-server', 'test-db', 'test-user', self.secret, + 'query.sql', self.repository) + fill.assert_not_called() + run.assert_not_called() + + def test_empty_input_still_uses_pipe(self): + for module in MODULES: + with self.subTest(module=module.__name__), \ + patch.object(module.subprocess, 'run', return_value=Mock(returncode=0)) as run, \ + patch.object(module.subprocess, 'Popen') as popen: + module.run_subprocess(['gh', 'secret', 'set', 'EMPTY'], input_data=b'') + self.assertEqual(run.call_args.kwargs['input'], b'') + popen.assert_not_called() + + def test_stdin_uses_resolved_executable_without_mutating_arguments(self): + command = ['gh', 'secret', 'set', 'TEST_CONNECTION', '--repo', self.repository] + original = list(command) + executable = r'C:\Program Files\GitHub CLI\gh.exe' + payload = self.secret.encode('utf-8') + for module in MODULES: + with self.subTest(module=module.__name__), \ + patch.object(module, 'resolve_executable', return_value=executable) as resolve, \ + patch.object(module.subprocess, 'run', return_value=Mock(returncode=0)) as run: + module.run_subprocess(command, input_data=payload) + resolve.assert_called_once_with('gh') + run.assert_called_once_with( + [executable] + original[1:], input=payload, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.assertEqual(command, original) + + def test_stdin_stops_when_executable_resolution_fails(self): + command = ['gh', 'secret', 'set', 'TEST_CONNECTION'] + original = list(command) + for module in MODULES: + with self.subTest(module=module.__name__), \ + patch.object(module, 'resolve_executable', side_effect=FileNotFoundError('gh')) as resolve, \ + patch.object(module.subprocess, 'run') as run, \ + patch.object(module.subprocess, 'Popen') as popen: + with self.assertRaises(FileNotFoundError): + module.run_subprocess(command, input_data=self.secret.encode('utf-8')) + resolve.assert_called_once_with('gh') + run.assert_not_called() + popen.assert_not_called() + self.assertEqual(command, original) + + def test_existing_nonsecret_commands_keep_their_behavior(self): + for module in MODULES: + for show_output in (False, True): + with self.subTest(module=module.__name__, show_output=show_output), \ + patch.object(module.subprocess, 'Popen') as popen, \ + patch.object(module.subprocess, 'run') as run: + popen.return_value.returncode = 0 + command = ['git', 'status'] + module.run_subprocess(command, stdout_show=show_output) + kwargs = {} if show_output else dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if module is postgresql: + kwargs['shell'] = False + popen.assert_called_once_with(['git', 'status'], **kwargs) + popen.return_value.wait.assert_called_once_with() + run.assert_not_called() + + def test_existing_nonsecret_failure_still_logs_warning(self): + for module in MODULES: + with self.subTest(module=module.__name__), \ + patch.object(module.subprocess, 'Popen') as popen, \ + patch.object(module, 'logger') as logger: + popen.return_value.returncode = 1 + popen.return_value.stderr.read.return_value = b'nonsecret failure\n' + command = ['git', 'status'] + module.run_subprocess(command) + logger.warning.assert_called_once_with('nonsecret failure') + + def test_workflow_run_preserves_quoted_names_and_branches(self): + action = 'deploy "quoted" --repo other/repo' + branch = 'feature "quoted" --ref other-branch' + for commands in (mysql_commands, postgresql_commands, rdbms_commands): + with self.subTest(module=commands.__name__), \ + patch.object(commands, 'gitcli_check_and_login', return_value='gh'), \ + patch.object(commands, 'run_subprocess') as run: + commands.github_actions_run(action, branch) + run.assert_called_once_with(['gh', 'workflow', 'run', action + '.yml', '--ref', branch]) + + def test_setup_preserves_git_paths_and_branch_arguments(self): + self.server.network = SimpleNamespace(public_network_access='Enabled') + root = os.path.abspath('project with spaces') + action = 'deploy "quoted" --repo other/repo' + branch = 'feature "quoted" --ref other-branch' + for commands, module in ((mysql_commands, mysql), (postgresql_commands, postgresql)): + with self.subTest(module=commands.__name__), \ + patch.object(commands, 'gitcli_check_and_login'), \ + patch.object(commands, 'fill_action_template'), \ + patch.object(commands, 'get_git_root_dir', return_value=root), \ + patch.object(commands, 'run_subprocess') as run: + commands.github_actions_setup( + self.cmd, Mock(get=Mock(return_value=self.server)), + 'test-rg', 'test-server', 'test-db', 'test-user', self.secret, + 'query.sql', self.repository, action_name=action, branch=branch, allow_push=True) + action_path = root + module.GITHUB_ACTION_PATH + action + '.yml' + self.assertEqual(run.call_args_list, [ + unittest.mock.call(['git', 'add', action_path]), + unittest.mock.call(['git', 'commit', '-m', 'Add github action file']), + unittest.mock.call(['git', 'push', 'origin', branch]), + ]) + + def test_interactive_login_uses_argument_list(self): + for commands in (mysql_commands, postgresql_commands, rdbms_commands): + with self.subTest(module=commands.__name__), \ + patch.object(commands, 'run_cmd', side_effect=[Mock(returncode=0), Mock(returncode=1)]), \ + patch.object(commands, 'run_subprocess') as run: + commands.gitcli_check_and_login() + run.assert_called_once_with(['gh', 'auth', 'login'], stdout_show=True) + + +class WindowsDeploymentResolverTest(unittest.TestCase): + + def setUp(self): + temporary = tempfile.TemporaryDirectory(prefix='installed tools ') + self.addCleanup(temporary.cleanup) + self.executable = os.path.join(temporary.name, 'gh.exe') + with open(self.executable, 'w'): + pass + os.chmod(self.executable, 0o755) + + def test_windows_launches_use_safe_executable_for_stdin_and_normal_commands(self): + executable = r'C:\installed tools\gh.exe' + for module in (postgresql, rdbms): + for input_data in (None, b''): + with self.subTest(module=module.__name__, input_data=input_data), \ + patch.object(sys, 'platform', 'win32'), \ + patch.object(postgresql, 'is_windows', return_value=True), \ + patch.object(module.os, 'path', ntpath), \ + patch.object(ntpath, 'isfile', return_value=True), \ + patch.object(ntpath, 'samefile', return_value=False), \ + patch.object(module.os, 'access', return_value=True), \ + patch.object(module, 'get_safe_executable_path', return_value=executable) as resolve, \ + patch.object(module.subprocess, 'run', return_value=Mock(returncode=0)) as run, \ + patch.object(module.subprocess, 'Popen', return_value=Mock(returncode=0)) as popen: + command = ['gh', 'secret', 'set', 'TEST', '--repo', 'owner/repo'] + original = list(command) + module.run_subprocess(command, input_data=input_data) + resolve.assert_called_once_with('gh.exe') + if input_data is None: + kwargs = dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if module is postgresql: + kwargs['shell'] = False + popen.assert_called_once_with( + [executable] + original[1:], **kwargs) + run.assert_not_called() + else: + run.assert_called_once_with( + [executable] + original[1:], input=b'', + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + popen.assert_not_called() + self.assertEqual(command, original) + + def test_missing_windows_tool_never_launches_bare_name(self): + for module in (postgresql, rdbms): + with self.subTest(module=module.__name__), \ + patch.object(sys, 'platform', 'win32'), \ + patch.object(postgresql, 'is_windows', return_value=True), \ + patch.object(module, 'get_safe_executable_path', return_value=None), \ + patch.object(module.subprocess, 'run') as run, \ + patch.object(module.subprocess, 'Popen') as popen: + with self.assertRaises(FileNotFoundError): + module.run_subprocess(['gh', 'auth', 'login']) + with self.assertRaises(FileNotFoundError): + module.run_subprocess(['gh', 'secret', 'set', 'TEST'], input_data=b'') + with self.assertRaises(FileNotFoundError): + module.run_cmd(['gh', 'auth', 'status'], capture_output=True) + run.assert_not_called() + popen.assert_not_called() + + def test_login_queries_use_resolved_executable(self): + executable = self.executable + for commands, module in ((postgresql_commands, postgresql), (rdbms_commands, rdbms)): + with self.subTest(module=commands.__name__), \ + patch.object(module, 'resolve_executable', return_value=executable), \ + patch.object(postgresql_commands, 'resolve_executable', return_value=executable), \ + patch.object(module, 'core_run_cmd', return_value=Mock(returncode=0)) as run: + commands.gitcli_check_and_login() + self.assertEqual(run.call_args_list, [ + unittest.mock.call([executable], capture_output=True), + unittest.mock.call([executable, 'auth', 'status'], capture_output=True), + ]) + + +if __name__ == '__main__': + unittest.main()