From febd0de125ff9705ec26af23c02169db2c932838 Mon Sep 17 00:00:00 2001 From: Gabriel Lobo Date: Thu, 29 Oct 2026 22:24:48 -0600 Subject: [PATCH 1/5] [PostgreSQL] Resolve deployment tool paths consistently Reuse executable lookup and retain resolved Git and GitHub CLI paths throughout deployment operations. Preserve arguments containing spaces and cover the deployment flows with unit tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../postgresql/commands/deploy_commands.py | 28 ++- .../tests/unit/test_deploy_commands.py | 203 ++++++++++++++++++ .../postgresql/utils/_flexible_server_util.py | 61 ++++-- 3 files changed, 265 insertions(+), 27 deletions(-) create mode 100644 src/azure-cli/azure/cli/command_modules/postgresql/tests/unit/test_deploy_commands.py diff --git a/src/azure-cli/azure/cli/command_modules/postgresql/commands/deploy_commands.py b/src/azure-cli/azure/cli/command_modules/postgresql/commands/deploy_commands.py index 0a8a3bc3c46..2f64cfd38fb 100644 --- a/src/azure-cli/azure/cli/command_modules/postgresql/commands/deploy_commands.py +++ b/src/azure-cli/azure/cli/command_modules/postgresql/commands/deploy_commands.py @@ -8,6 +8,7 @@ from azure.cli.core.util import run_cmd from knack.log import get_logger from ..utils._flexible_server_util import ( + resolve_executable, run_subprocess, fill_action_template, get_git_root_dir, @@ -29,7 +30,8 @@ def github_actions_setup(cmd, client, resource_group_name, server_name, database raise RequiredArgumentMissingError("Provide remote branch name to allow pushing the action file to your remote branch.") if action_name is None: action_name = server.name + '_' + database_name + "_deploy" - gitcli_check_and_login() + gh_path = gitcli_check_and_login() + git_path = resolve_executable("git") database_engine = 'postgresql' @@ -41,32 +43,36 @@ def github_actions_setup(cmd, client, resource_group_name, server_name, database administrator_login_password=administrator_login_password, file_name=sql_file_path, repository=repository, - action_name=action_name) + action_name=action_name, + gh_path=gh_path, + git_path=git_path) - action_path = get_git_root_dir() + GITHUB_ACTION_PATH + action_name + '.yml' + action_path = get_git_root_dir(git_path) + GITHUB_ACTION_PATH + action_name + '.yml' logger.warning("Making git commit for file %s", action_path) - run_subprocess("git add {}".format(action_path)) - run_subprocess("git commit -m \"Add github action file\"") + run_subprocess([git_path, "add", action_path]) + run_subprocess([git_path, "commit", "-m", "Add github action file"]) if allow_push: logger.warning("Pushing the created action file to origin %s branch", branch) - run_subprocess("git push origin {}".format(branch)) + run_subprocess([git_path, "push", "origin", branch]) else: logger.warning('You did not set --allow-push parameter. Please push the prepared file %s to your remote repo and run "deploy run" command to activate the workflow.', action_path) def github_actions_run(action_name, branch): - gitcli_check_and_login() + gh_path = 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_path, "workflow", "run", action_name + ".yml", "--ref", branch]) def gitcli_check_and_login(): - output = run_cmd(["gh"], capture_output=True) + gh_path = resolve_executable("gh") + output = run_cmd([gh_path], capture_output=True) if output.returncode: raise ClientRequestError('Please install "Github CLI" to run this command.') - output = run_cmd(["gh", "auth", "status"], capture_output=True) + output = run_cmd([gh_path, "auth", "status"], capture_output=True) if output.returncode: - run_subprocess("gh auth login", stdout_show=True) + run_subprocess([gh_path, "auth", "login"], stdout_show=True) + return gh_path 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 new file mode 100644 index 00000000000..8b61e33d33c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/postgresql/tests/unit/test_deploy_commands.py @@ -0,0 +1,203 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +import os +import tempfile +import unittest +from unittest.mock import Mock, call, mock_open, patch + +from azure.cli.command_modules.postgresql.commands import deploy_commands as custom +from azure.cli.command_modules.postgresql.utils import _flexible_server_util as _util +from azure.cli.core.azclierror import ClientRequestError +from azure.cli.core.util import is_windows + + +class PostgresqlDeployTest(unittest.TestCase): + + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.cwd = os.path.join(temporary.name, 'work') + self.tools = os.path.join(temporary.name, 'tools with spaces') + os.mkdir(self.cwd) + os.mkdir(self.tools) + self.gh = os.path.join(self.tools, 'gh.exe' if is_windows() else 'gh') + self.git = os.path.join(self.tools, 'git.exe' if is_windows() else 'git') + self.files = {os.path.normcase(p) for p in (self.gh, self.git)} + self.server = Mock(name='server') + self.server.name = 'server' + self.server.id = '/subscriptions/sub/resourceGroups/rg/providers/Microsoft.DBforPostgreSQL/flexibleServers/server' + self.server.fully_qualified_domain_name = 'server.example' + self.server.network.public_network_access = 'Enabled' + self.run = Mock(side_effect=self.run_result) + self.process = Mock(returncode=0) + self.process.stderr.read.return_value = b'failed' + self.popen = Mock(return_value=self.process) + for patcher in ( + patch.dict('os.environ', {'PATH': self.tools, 'PATHEXT': '.EXE'}), + patch('os.getcwd', return_value=self.cwd), + patch('os.path.isfile', side_effect=lambda p: os.path.normcase(p) in self.files), + patch('os.access', return_value=True), + patch('subprocess.run', self.run), + patch('subprocess.Popen', self.popen), + patch('builtins.open', mock_open()), + patch.object(_util.os.path, 'exists', return_value=True), + patch.object(_util.os, 'remove'), + patch.object(_util.yaml, 'safe_load', return_value={ + 'jobs': {'build': {'steps': [{}, {}, {'with': {}}]}}}), + patch.object(_util, 'get_subscription_id', return_value='sub'), + patch.object(_util, 'create_service_principal_for_rbac', return_value={ + 'appId': 'app', 'password': 'unused', 'tenant': 'tenant', 'displayName': 'app', 'name': 'app'})): + patcher.start() + self.addCleanup(patcher.stop) + + @staticmethod + def run_result(args, **kwargs): + if args[1:] == ['auth', 'status']: + return Mock(returncode=1) + if args[1:] == ['rev-parse', '--show-toplevel']: + return Mock(returncode=0, stdout=b'C:/work with spaces\n') + return Mock(returncode=0, stdout=b'') + + def setup_deploy(self): + custom.github_actions_setup( + Mock(), Mock(get=Mock(return_value=self.server)), 'rg', 'server', 'database', + 'user', 'unused', 'file with spaces.sql', 'owner/repo', action_name='deploy action', + branch='topic branch', allow_push=True) + + def test_setup_pins_all_probe_login_secret_and_git_launches(self): + self.setup_deploy() + self.assertEqual([c.args[0] for c in self.run.call_args_list], [ + [self.gh], [self.gh, 'auth', 'status'], + [self.git, 'rev-parse', '--show-toplevel'], + [self.gh, 'secret', 'list', '--repo', 'owner/repo'], + [self.git, 'rev-parse', '--show-toplevel']]) + launches = [c.args[0] for c in self.popen.call_args_list] + self.assertEqual(launches[0], [self.gh, 'auth', 'login']) + self.assertEqual(launches[1], [self.gh, 'secret', 'set', 'AZURE_CREDENTIALS', + '--repo', 'owner/repo', '<', './temp_app_credential.txt']) + self.assertEqual(launches[2][:7], [ + self.gh, 'secret', 'set', 'SERVER_DATABASE_POSTGRESQL_CONNECTION_STRING', '--repo', 'owner/repo', '-b']) + self.assertEqual(len(launches[2]), 8) + self.assertEqual(launches[3:], [ + [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']]) + for invocation in self.popen.call_args_list: + self.assertIs(invocation.kwargs['shell'], False) + + def test_workflow_reuses_checked_path(self): + custom.github_actions_run('deploy action', 'topic branch') + self.assertEqual(self.popen.call_args_list[-1].args[0], + [self.gh, 'workflow', 'run', 'deploy action.yml', '--ref', 'topic branch']) + self.assertEqual([c.args[0][0] for c in self.run.call_args_list], [self.gh, self.gh]) + + def test_probe_path_is_retained_after_path_changes(self): + def probe(args, **kwargs): + os.environ['PATH'] = self.cwd + return self.run_result(args, **kwargs) + self.run.side_effect = probe + self.assertEqual(custom.gitcli_check_and_login(), self.gh) + self.assertEqual(self.popen.call_args.args[0], [self.gh, 'auth', 'login']) + + def test_missing_path_tools_never_launch(self): + for files in (set(), {os.path.normcase(os.path.join(self.cwd, os.path.basename(self.gh)))}): + with self.subTest(files=files): + self.files = files + with self.assertRaises(FileNotFoundError): + custom.github_actions_run('deploy', 'main') + self.run.assert_not_called() + self.popen.assert_not_called() + + def test_git_helper_requires_path_tool(self): + self.files = {os.path.normcase(os.path.join(self.cwd, os.path.basename(self.git)))} + with self.assertRaises(FileNotFoundError): + _util.get_git_root_dir() + with self.assertRaises(FileNotFoundError): + _util.run_subprocess(['git', 'add', 'file']) + self.run.assert_not_called() + self.popen.assert_not_called() + + def test_missing_gh_stops_secret_creation(self): + self.files = set() + with self.assertRaises(FileNotFoundError): + _util.register_credential_secrets(Mock(), 'postgresql', self.server, 'owner/repo') + _util.create_service_principal_for_rbac.assert_not_called() + self.popen.assert_not_called() + + def test_missing_git_stops_setup_before_secret_creation(self): + self.files = {os.path.normcase(self.gh)} + with self.assertRaises(FileNotFoundError): + self.setup_deploy() + _util.create_service_principal_for_rbac.assert_not_called() + self.assertEqual([c.args[0] for c in self.popen.call_args_list], [[self.gh, 'auth', 'login']]) + + def test_non_windows_lookup_preserves_which_semantics(self): + for executable in ('gh', './tools/gh', '/usr/local/bin/gh'): + with self.subTest(executable=executable), \ + patch.object(_util, 'is_windows', return_value=False), \ + patch('shutil.which', return_value=self.gh) as which: + self.assertEqual(_util.resolve_executable(executable), self.gh) + which.assert_called_once_with(executable) + with patch.object(_util, 'is_windows', return_value=False), \ + patch('shutil.which', return_value=None), self.assertRaises(FileNotFoundError): + _util.resolve_executable('gh') + + def test_probe_nonzero_preserves_install_message(self): + self.run.side_effect = None + self.run.return_value = Mock(returncode=1) + with self.assertRaisesRegex(ClientRequestError, 'Please install'): + custom.gitcli_check_and_login() + self.assertEqual(self.run.call_count, 1) + self.popen.assert_not_called() + + def test_authenticated_does_not_login(self): + self.run.side_effect = None + self.run.return_value = Mock(returncode=0) + self.assertEqual(custom.gitcli_check_and_login(), self.gh) + self.popen.assert_not_called() + + def test_subprocess_preserves_argv_and_nonzero_behavior(self): + self.process.returncode = 1 + arguments = ['gh', 'workflow', 'run', 'name with spaces.yml'] + with patch.object(_util.logger, 'warning') as warning: + _util.run_subprocess(arguments) + warning.assert_called_once_with('failed') + self.assertEqual(arguments[0], 'gh') + self.assertEqual(self.popen.call_args.args[0], [self.gh] + arguments[1:]) + self.process.returncode = 0 + self.process.stderr = None + _util.run_subprocess([self.gh, 'auth', 'login'], stdout_show=True) + self.assertEqual(self.popen.call_args, call([self.gh, 'auth', 'login'], shell=False)) + + @unittest.skipUnless(is_windows(), 'Windows executable lookup') + def test_windows_path_entries(self): + self.files.add(os.path.normcase(os.path.join(self.cwd, 'gh.exe'))) + for directory in ('', '.', 'tools', r'C:tools', r'\tools', self.cwd): + with self.subTest(directory=directory), patch.dict( + 'os.environ', {'PATH': directory + os.pathsep + '"' + self.tools + '"'}): + self.assertEqual(_util.resolve_executable('gh'), self.gh) + with patch.dict('os.environ', {'PATH': self.cwd}), self.assertRaises(FileNotFoundError): + _util.resolve_executable('gh') + + @unittest.skipUnless(is_windows(), 'Windows executable lookup') + def test_windows_requires_native_executable(self): + self.files = {os.path.normcase(os.path.join(self.tools, 'gh.cmd'))} + with patch.dict('os.environ', {'PATHEXT': '.CMD;.EXE'}): + for executable in ('gh', 'gh.cmd', os.path.join(self.tools, 'gh.cmd')): + with self.subTest(executable=executable), self.assertRaises(FileNotFoundError): + _util.resolve_executable(executable) + + @unittest.skipUnless(is_windows(), 'Windows executable lookup') + def test_windows_relative_explicit_paths_are_rejected(self): + for executable in (r'.\gh.exe', r'tools\gh.exe', r'C:gh.exe', r'\tools\gh.exe'): + with self.subTest(executable=executable), self.assertRaises(FileNotFoundError): + _util.resolve_executable(executable) + + @unittest.skipUnless(is_windows(), 'Windows executable lookup') + def test_windows_path_tool_link_to_working_directory_is_rejected(self): + with patch.object(os.path, 'realpath', return_value=os.path.join(self.cwd, 'gh.exe')): + with self.assertRaises(FileNotFoundError): + _util.resolve_executable('gh') 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 9957faeb0e2..d48893e69b8 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 @@ -10,13 +10,12 @@ import random import subprocess import secrets -import shlex import string 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.util import CLIError, run_cmd, get_safe_executable_path, is_windows from azure.cli.core.azclierror import AuthenticationError from azure.core.exceptions import HttpResponseError from azure.core.paging import ItemPaged @@ -253,18 +252,44 @@ def _resolve_api_version(client, provider_namespace, resource_type, parent_path) .format(resource_type)) +def resolve_executable(executable): + """Resolve deployment tools to absolute native executable paths on Windows.""" + import errno + import shutil + + if not is_windows(): + resolved = shutil.which(executable) + if resolved: + return os.path.abspath(resolved) + else: + explicit = bool(os.path.dirname(executable)) + name = executable if os.path.splitext(executable)[1] else executable + '.exe' + resolved = executable if explicit else get_safe_executable_path(name) + if resolved: + drive, tail = os.path.splitdrive(resolved) + if (drive and tail.startswith(('\\', '/')) and + os.path.splitext(resolved)[1].lower() in ('.exe', '.com') and + os.path.isfile(resolved) and os.access(resolved, os.X_OK)): + # A PATH entry may contain a link back into the working directory. + if explicit or not os.path.samefile(os.path.dirname(os.path.realpath(resolved)), os.getcwd()): + return os.path.abspath(resolved) + + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), executable) + + def run_subprocess(command, stdout_show=None): - commands = shlex.split(command) + command = [resolve_executable(command[0])] + command[1:] if stdout_show: - process = subprocess.Popen(commands) + process = subprocess.Popen(command, shell=False) else: - process = subprocess.Popen(commands, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) process.wait() if process.returncode: logger.warning(process.stderr.read().strip().decode('UTF-8')) -def register_credential_secrets(cmd, database_engine, server, repository): +def register_credential_secrets(cmd, database_engine, server, repository, gh_path=None): + gh_path = resolve_executable(gh_path or "gh") logger.warning('Adding secret "AZURE_CREDENTIALS" to github repository') resource_group = parse_resource_id(server.id)["resource_group"] provider = "DBforPostgreSQL" @@ -285,23 +310,25 @@ def register_credential_secrets(cmd, database_engine, server, repository): 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)) + run_subprocess([gh_path, 'secret', 'set', AZURE_CREDENTIALS, '--repo', repository, '<', credential_file]) os.remove(credential_file) -def register_connection_secrets(cmd, database_engine, server, database_name, administrator_login, administrator_login_password, repository, connection_string_name): +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 secret set {} --repo {} -b"{}"'.format(connection_string_name, repository, connection_string)) + run_subprocess([gh_path, 'secret', 'set', connection_string_name, '--repo', repository, '-b', connection_string]) -def fill_action_template(cmd, database_engine, server, database_name, administrator_login, administrator_login_password, file_name, action_name, repository): +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): - action_dir = get_git_root_dir() + GITHUB_ACTION_PATH + gh_path = resolve_executable(gh_path or "gh") + action_dir = get_git_root_dir(git_path) + GITHUB_ACTION_PATH if not os.path.exists(action_dir): os.makedirs(action_dir) - process = run_cmd(["gh", "secret", "list", "--repo", repository], capture_output=True) + process = run_cmd([gh_path, "secret", "list", "--repo", repository], capture_output=True) github_secrets = process.stdout.strip().decode('UTF-8') # connection_string = AZURE_POSTGRESQL_CONNECTION_STRING @@ -310,7 +337,8 @@ def fill_action_template(cmd, database_engine, server, database_name, administra register_credential_secrets(cmd, database_engine=database_engine, server=server, - repository=repository) + repository=repository, + gh_path=gh_path) except HttpResponseError: raise AuthenticationError('You do not have authorization to create a service principal to run azure service in github actions. \n' 'Please create a service principal that has access to the database server and add "AZURE_CREDENTIALS" secret to your github repository. \n' @@ -325,7 +353,8 @@ def fill_action_template(cmd, database_engine, server, database_name, administra administrator_login=administrator_login, administrator_login_password=administrator_login_password, repository=repository, - connection_string_name=connection_string_name) + connection_string_name=connection_string_name, + gh_path=gh_path) current_location = os.path.dirname(__file__) @@ -342,8 +371,8 @@ def fill_action_template(cmd, database_engine, server, database_name, administra yml_file.write(yaml.dump(template)) -def get_git_root_dir(): - process = run_cmd(["git", "rev-parse", "--show-toplevel"], capture_output=True) +def get_git_root_dir(git_path=None): + process = run_cmd([resolve_executable(git_path or "git"), "rev-parse", "--show-toplevel"], capture_output=True) return process.stdout.strip().decode('UTF-8') From da43add96b4c331a2943ebe82febfe532426e364 Mon Sep 17 00:00:00 2001 From: Gabriel Lobo Date: Thu, 29 Oct 2026 22:27:13 -0600 Subject: [PATCH 2/5] [RDBMS] Fix deployment setup subprocess input handling Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../azure/cli/command_modules/mysql/_util.py | 28 +- .../postgresql/utils/_flexible_server_util.py | 31 ++- .../rdbms/_flexible_server_util.py | 31 ++- .../rdbms/tests/latest/test_deploy_setup.py | 243 ++++++++++++++++++ 4 files changed, 286 insertions(+), 47 deletions(-) create mode 100644 src/azure-cli/azure/cli/command_modules/rdbms/tests/latest/test_deploy_setup.py 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/utils/_flexible_server_util.py b/src/azure-cli/azure/cli/command_modules/postgresql/utils/_flexible_server_util.py index 9957faeb0e2..c93642fa7cb 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 @@ -6,6 +6,7 @@ # pylint: disable=unused-argument, line-too-long, import-outside-toplevel, raise-missing-from import datetime as dt from datetime import datetime +import json import os import random import subprocess @@ -17,7 +18,7 @@ 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.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 @@ -253,8 +254,14 @@ 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 run_subprocess(command, stdout_show=None, input_data=None): + commands = shlex.split(command) if isinstance(command, str) else command + 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: @@ -276,23 +283,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 = "host={} port=5432 dbname={} user={} password={} sslmode=require".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_util.py b/src/azure-cli/azure/cli/command_modules/rdbms/_flexible_server_util.py index c870582db9c..b4888748a75 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,6 +6,7 @@ # pylint: disable=unused-argument, line-too-long, import-outside-toplevel, raise-missing-from import datetime as dt from datetime import datetime +import json import os import random import subprocess @@ -17,7 +18,7 @@ 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.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 +299,14 @@ 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 run_subprocess(command, stdout_show=None, input_data=None): + commands = shlex.split(command) if isinstance(command, str) else command + 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 +328,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/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..2bd415c8021 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/rdbms/tests/latest/test_deploy_setup.py @@ -0,0 +1,243 @@ +# -------------------------------------------------------------------------------------------- +# 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 subprocess +import sys +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 + + +MODULES = (mysql, postgresql, rdbms) + + +class DeploySetupTest(unittest.TestCase): + + def setUp(self): + resolver = patch.object(mysql, '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: + error_type = ClientRequestError if commands is mysql_commands else FileNotFoundError + with self.assertRaises(error_type): + 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_mysql_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') + with patch.object(mysql, 'resolve_executable', return_value=executable) as resolve, \ + patch.object(mysql.subprocess, 'run', return_value=Mock(returncode=0)) as run: + mysql.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_mysql_stdin_stops_when_executable_resolution_fails(self): + command = ['gh', 'secret', 'set', 'TEST_CONNECTION'] + original = list(command) + with patch.object(mysql, 'resolve_executable', side_effect=FileNotFoundError('gh')) as resolve, \ + patch.object(mysql.subprocess, 'run') as run, \ + patch.object(mysql.subprocess, 'Popen') as popen: + with self.assertRaises(FileNotFoundError): + mysql.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'] if module is mysql else 'git status' + module.run_subprocess(command, stdout_show=show_output) + kwargs = {} if show_output else dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE) + 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'] if module is mysql else 'git status' + module.run_subprocess(command) + logger.warning.assert_called_once_with('nonsecret failure') + + +if __name__ == '__main__': + unittest.main() From bd703ddba302ee53938cf0980c7dd0cf61ae0a9d Mon Sep 17 00:00:00 2001 From: Naia Scott Date: Mon, 9 Nov 2026 13:29:17 -0500 Subject: [PATCH 3/5] Apply fix --- .../postgresql/commands/deploy_commands.py | 17 +- .../postgresql/utils/_flexible_server_util.py | 25 ++- .../rdbms/_flexible_server_util.py | 25 ++- .../rdbms/flexible_server_custom_common.py | 13 +- .../rdbms/tests/latest/test_deploy_setup.py | 155 +++++++++++++++--- 5 files changed, 190 insertions(+), 45 deletions(-) diff --git a/src/azure-cli/azure/cli/command_modules/postgresql/commands/deploy_commands.py b/src/azure-cli/azure/cli/command_modules/postgresql/commands/deploy_commands.py index 0a8a3bc3c46..2ac2813602b 100644 --- a/src/azure-cli/azure/cli/command_modules/postgresql/commands/deploy_commands.py +++ b/src/azure-cli/azure/cli/command_modules/postgresql/commands/deploy_commands.py @@ -5,9 +5,9 @@ # pylint: disable=unused-argument, line-too-long from azure.cli.core.azclierror import ClientRequestError, RequiredArgumentMissingError -from azure.cli.core.util import run_cmd from knack.log import get_logger from ..utils._flexible_server_util import ( + run_cmd, run_subprocess, fill_action_template, get_git_root_dir, @@ -45,12 +45,12 @@ def github_actions_setup(cmd, client, resource_group_name, server_name, database action_path = get_git_root_dir() + GITHUB_ACTION_PATH + action_name + '.yml' logger.warning("Making git commit for file %s", action_path) - run_subprocess("git add {}".format(action_path)) - run_subprocess("git commit -m \"Add github action file\"") + run_subprocess(["git", "add", action_path]) + run_subprocess(["git", "commit", "-m", "Add github action file"]) if allow_push: logger.warning("Pushing the created action file to origin %s branch", branch) - run_subprocess("git push origin {}".format(branch)) + run_subprocess(["git", "push", "origin", branch]) else: logger.warning('You did not set --allow-push parameter. Please push the prepared file %s to your remote repo and run "deploy run" command to activate the workflow.', action_path) @@ -59,14 +59,17 @@ 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) 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 c93642fa7cb..4a39eb93e87 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 @@ -6,18 +6,19 @@ # 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.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 @@ -254,8 +255,26 @@ def _resolve_api_version(client, provider_namespace, resource_type, parent_path) .format(resource_type)) +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 = shlex.split(command) if isinstance(command, str) else command + 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) 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 b4888748a75..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,19 @@ # 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.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 @@ -299,8 +300,26 @@ def _resolve_api_version(client, provider_namespace, resource_type, parent_path) .format(resource_type)) +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 = shlex.split(command) if isinstance(command, str) else command + 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) 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 index 2bd415c8021..c5e225bf337 100644 --- 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 @@ -5,6 +5,7 @@ import hashlib import json +import os import subprocess import sys import unittest @@ -17,6 +18,7 @@ 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) @@ -25,9 +27,10 @@ class DeploySetupTest(unittest.TestCase): def setUp(self): - resolver = patch.object(mysql, 'resolve_executable', side_effect=lambda executable: executable) - resolver.start() - self.addCleanup(resolver.stop) + for module in MODULES: + resolver = patch.object(module, '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/' @@ -168,8 +171,7 @@ def test_missing_gh_stops_setup(self): 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: - error_type = ClientRequestError if commands is mysql_commands else FileNotFoundError - with self.assertRaises(error_type): + 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, @@ -186,32 +188,36 @@ def test_empty_input_still_uses_pipe(self): self.assertEqual(run.call_args.kwargs['input'], b'') popen.assert_not_called() - def test_mysql_stdin_uses_resolved_executable_without_mutating_arguments(self): + 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') - with patch.object(mysql, 'resolve_executable', return_value=executable) as resolve, \ - patch.object(mysql.subprocess, 'run', return_value=Mock(returncode=0)) as run: - mysql.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_mysql_stdin_stops_when_executable_resolution_fails(self): + 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) - with patch.object(mysql, 'resolve_executable', side_effect=FileNotFoundError('gh')) as resolve, \ - patch.object(mysql.subprocess, 'run') as run, \ - patch.object(mysql.subprocess, 'Popen') as popen: - with self.assertRaises(FileNotFoundError): - mysql.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) + 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: @@ -220,7 +226,7 @@ def test_existing_nonsecret_commands_keep_their_behavior(self): patch.object(module.subprocess, 'Popen') as popen, \ patch.object(module.subprocess, 'run') as run: popen.return_value.returncode = 0 - command = ['git', 'status'] if module is mysql else 'git status' + command = ['git', 'status'] module.run_subprocess(command, stdout_show=show_output) kwargs = {} if show_output else dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE) popen.assert_called_once_with(['git', 'status'], **kwargs) @@ -234,10 +240,105 @@ def test_existing_nonsecret_failure_still_logs_warning(self): 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'] if module is mysql else 'git status' + 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'), \ + 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 test_windows_launches_use_safe_executable_for_stdin_and_normal_commands(self): + executable = os.path.abspath(os.path.join('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(module.sys, 'platform', 'win32'), \ + 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: + popen.assert_called_once_with( + [executable] + original[1:], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + 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(module.sys, 'platform', 'win32'), \ + 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 = os.path.abspath(os.path.join('installed tools', 'gh.exe')) + 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(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() From 8fee9f2f05227b209d2a3dded6ac215827143e35 Mon Sep 17 00:00:00 2001 From: Gabriel Lobo Date: Mon, 9 Nov 2026 15:12:38 -0600 Subject: [PATCH 4/5] [PostgreSQL] Align deployment regression fixtures Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../tests/latest/test_deploy_commands.py | 51 +++++++++++-------- 1 file changed, 29 insertions(+), 22 deletions(-) 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 009236a45ae..59d57c393c9 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 @@ -47,24 +47,25 @@ def test_subprocess_preserves_arguments_in_each_output_mode(self): expected = [executable, *original[1:]] if stdout_show: - popen.assert_called_once_with(expected) + popen.assert_called_once_with(expected, shell=False) else: - popen.assert_called_once_with(expected, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + popen.assert_called_once_with( + expected, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) process.wait.assert_called_once_with() self.assertEqual(arguments, original) - def test_unix_and_explicit_paths_keep_existing_lookup(self): - with mock.patch.object(util.sys, 'platform', 'linux'), \ + def test_unix_lookup_uses_which_for_names_and_explicit_paths(self): + executable = os.path.abspath(os.path.join('installed tools', 'gh')) + with mock.patch.object(util, 'is_windows', return_value=False), \ + mock.patch('shutil.which', return_value=executable) as which, \ mock.patch.object(util, 'get_safe_executable_path') as find: - self.assertEqual(util.resolve_executable('gh'), 'gh') - find.assert_not_called() - - with mock.patch.object(util.sys, 'platform', 'win32'), \ - mock.patch.object(util, 'get_safe_executable_path') as find: - for executable in (os.path.abspath(os.path.join('installed tools', 'gh.exe')), - os.path.join('.', 'gh.exe'), os.path.join('tools', 'gh.exe')): - with self.subTest(executable=executable): - self.assertEqual(util.resolve_executable(executable), executable) + for argument in ('gh', executable, os.path.join('.', 'gh'), os.path.join('tools', 'gh')): + with self.subTest(argument=argument): + self.assertEqual(util.resolve_executable(argument), executable) + which.assert_called_with(argument) + which.return_value = None + with self.assertRaises(FileNotFoundError): + util.resolve_executable('gh') find.assert_not_called() @@ -75,6 +76,7 @@ def setUp(self): self.addCleanup(temporary.cleanup) self.project = temporary.name self.executable = os.path.join(self.project, 'installed tools', 'gh.exe') + self.git_executable = os.path.join(self.project, 'installed tools', 'git.exe') self.workflow = self.project + util.GITHUB_ACTION_PATH + 'deploy database.yml' server = SimpleNamespace( id='/subscriptions/test-subscription/resourceGroups/test-rg/' @@ -99,7 +101,8 @@ def setUp(self): self.upload = mock.Mock(return_value=subprocess.CompletedProcess([], 0, stdout=b'', stderr=b'')) self.git = mock.Mock() patches = ( - (deploy, 'gitcli_check_and_login', mock.Mock()), + (deploy, 'gitcli_check_and_login', mock.Mock(return_value=self.executable)), + (deploy, 'resolve_executable', mock.Mock(return_value=self.git_executable)), (deploy, 'get_git_root_dir', mock.Mock(return_value=self.project)), (deploy, 'run_subprocess', self.git), (util, 'get_git_root_dir', mock.Mock(return_value=self.project)), @@ -133,9 +136,9 @@ def test_setup_uploads_missing_credentials_through_stdin(self): 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, [ - mock.call(['git', 'add', self.workflow]), - mock.call(['git', 'commit', '-m', 'Add github action file']), - mock.call(['git', 'push', 'origin', 'feature/database']), + mock.call([self.git_executable, 'add', self.workflow]), + mock.call([self.git_executable, 'commit', '-m', 'Add github action file']), + mock.call([self.git_executable, 'push', 'origin', 'feature/database']), ]) def test_setup_stops_after_credential_upload_failure(self): @@ -159,6 +162,9 @@ def test_setup_stops_after_credential_upload_failure(self): class WindowsDeploymentToolsTest(unittest.TestCase): def setUp(self): + platform = mock.patch.object(util, 'is_windows', return_value=True) + platform.start() + self.addCleanup(platform.stop) temporary = tempfile.TemporaryDirectory() self.addCleanup(temporary.cleanup) self.project = os.path.join(temporary.name, 'project with spaces') @@ -196,7 +202,7 @@ def test_workflow_run_resolves_every_launch(self): ]) popen.assert_called_once_with( [self.gh, 'workflow', 'run', 'deploy database.yml', '--ref', 'feature/database'], - stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) def test_setup_resolves_git_and_preserves_paths(self): client = mock.Mock() @@ -217,13 +223,14 @@ def test_setup_resolves_git_and_preserves_paths(self): action_path = self.project + util.GITHUB_ACTION_PATH + 'deploy database.yml' expected = [ - mock.call([self.git, 'add', action_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE), + mock.call([self.git, 'add', action_path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False), mock.call([self.git, 'commit', '-m', 'Add github action file'], - stdout=subprocess.PIPE, stderr=subprocess.PIPE), + stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False), ] if allow_push: expected.append(mock.call([self.git, 'push', 'origin', 'feature/database'], - stdout=subprocess.PIPE, stderr=subprocess.PIPE)) + stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)) self.assertEqual(popen.call_args_list, expected) def test_interactive_login_uses_resolved_tool(self): @@ -232,7 +239,7 @@ def test_interactive_login_uses_resolved_tool(self): mock.patch.object(util.subprocess, 'Popen', return_value=mock.MagicMock(returncode=0)) as popen: deploy.gitcli_check_and_login() - popen.assert_called_once_with([self.gh, 'auth', 'login']) + popen.assert_called_once_with([self.gh, 'auth', 'login'], shell=False) def test_git_root_and_secret_queries_use_resolved_tools(self): completed = subprocess.CompletedProcess([], 0, stdout=self.project.encode('utf8')) From 6ed5c65f575512e5a589b86308aa03eb0455f6ac Mon Sep 17 00:00:00 2001 From: Naia Scott Date: Mon, 9 Nov 2026 21:53:09 -0500 Subject: [PATCH 5/5] PR comments --- .../tests/latest/test_deploy_commands.py | 20 ++++++++++++++----- .../postgresql/utils/_flexible_server_util.py | 10 ++++++++-- 2 files changed, 23 insertions(+), 7 deletions(-) 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 0ca2343dac3..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 @@ -143,19 +143,29 @@ 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 with exit code 1') as error: + with self.assertRaisesRegex(ClientRequestError, 'Failed to set the AZURE_CREDENTIALS secret') as error: deploy.github_actions_setup( mock.Mock(), self.client, 'test-rg', 'server', 'database', 'admin', 'unused', '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/utils/_flexible_server_util.py b/src/azure-cli/azure/cli/command_modules/postgresql/utils/_flexible_server_util.py index 30fe9d1cd9e..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 @@ -315,8 +315,14 @@ def register_credential_secrets(cmd, database_engine, server, repository, gh_pat app.pop('displayName') app.pop('name') - run_subprocess([gh_path, 'secret', 'set', AZURE_CREDENTIALS, '--repo', repository], - input_data=json.dumps(app).encode('utf-8')) + process = subprocess.run( + [gh_path, 'secret', 'set', AZURE_CREDENTIALS, '--repo', repository], + 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( + process.returncode), + recommendation='Check your GitHub CLI authentication and repository permissions, then retry.') def register_connection_secrets(cmd, database_engine, server, database_name, administrator_login, administrator_login_password, repository, connection_string_name, gh_path=None):