From ecca3c1d73d46a1d9837d44ec769d3381de5000e Mon Sep 17 00:00:00 2001 From: Fuming Zhang Date: Tue, 17 Nov 2026 10:31:45 +0000 Subject: [PATCH 1/4] [AKS] Fix kubelogin conversion for selected kubeconfig paths Pass the merged kubeconfig explicitly to kubelogin without changing its working directory. Reuse the resolved executable, skip stdout-only requests and preserve conversion failure warnings. Add regression coverage for file selection, stdout and real subprocess conversion without touching unrelated kubeconfig files. Fixes Azure/azure-cli#34091. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../azure/cli/command_modules/acs/custom.py | 15 +- .../acs/tests/latest/test_custom.py | 133 ++++++++++++++++++ 2 files changed, 143 insertions(+), 5 deletions(-) diff --git a/src/azure-cli/azure/cli/command_modules/acs/custom.py b/src/azure-cli/azure/cli/command_modules/acs/custom.py index 90fbfa76286..5df23a58f74 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/custom.py +++ b/src/azure-cli/azure/cli/command_modules/acs/custom.py @@ -2064,19 +2064,24 @@ def aks_get_credentials(cmd, client, resource_group_name, name, admin=False, path, kubeconfig, overwrite_existing, context_name) # Check if kubeconfig requires kubelogin with devicecode and convert it - if uses_kubelogin_devicecode(kubeconfig): - if which("kubelogin"): + if path != "-" and uses_kubelogin_devicecode(kubeconfig): + kubelogin_path = which("kubelogin") + if kubelogin_path: try: # Run kubelogin convert-kubeconfig -l azurecli subprocess.run( - ["kubelogin", "convert-kubeconfig", "-l", "azurecli"], - cwd=os.path.dirname(path), + [ + os.path.abspath(kubelogin_path), + "convert-kubeconfig", + "-l", "azurecli", + "--kubeconfig", os.path.abspath(path), + ], check=True, ) logger.warning("Converted kubeconfig to use Azure CLI authentication.") except subprocess.CalledProcessError as e: logger.warning("Failed to convert kubeconfig with kubelogin: %s", str(e)) - except Exception as e: # pylint: disable=broad-except + except OSError as e: logger.warning("Error running kubelogin: %s", str(e)) else: logger.warning( diff --git a/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py b/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py index 3cce5c56395..e5de133191f 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py +++ b/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py @@ -9,6 +9,7 @@ import io import shutil import subprocess +import sys import tarfile import tempfile import unittest @@ -2333,6 +2334,138 @@ def test_update_upgrade_settings(self, rg_def, get_resource_groups_client, get_r self.assertTrue(instance.upgrade_settings.override_settings.force_upgrade) self.assertEqual(instance.upgrade_settings.override_settings.until, parse("2024-01-01T13:00:00Z")) + +class AksGetCredentialsTest(unittest.TestCase): + def setUp(self): + self.cmd = mock.Mock() + self.cmd.cli_ctx.cloud.profile = "latest" + self.kubeconfig = yaml.safe_dump({ + "apiVersion": "v1", + "kind": "Config", + "clusters": [{"name": "cluster", "cluster": {"server": "https://example.com"}}], + "contexts": [{"name": "cluster", "context": {"cluster": "cluster", "user": "cluster-user"}}], + "current-context": "cluster", + "users": [{ + "name": "cluster-user", + "user": {"exec": {"command": "kubelogin", "args": ["get-token", "--login", "devicecode"]}}, + }], + }) + self.client = mock.Mock() + self.client.list_cluster_user_credentials.return_value.kubeconfigs = [ + mock.Mock(value=self.kubeconfig.encode("utf-8")), + ] + + def test_aks_get_credentials_converts_selected_file(self): + nested_path = os.path.join("config dir", "config") + absolute_path = os.path.abspath(nested_path) + default_path = os.path.join(os.path.expanduser("~"), ".kube", "config") + kubelogin_path = os.path.join("tools", "kubelogin") + for path, environment, selected_path in ( + ("config", "inherited-config", "config"), + (nested_path, "inherited-config", nested_path), + (absolute_path, "inherited-config", absolute_path), + (default_path, os.pathsep.join(("env-config", "unused-config")), "env-config"), + ): + with ( + self.subTest(path=path), + mock.patch.dict(os.environ, {"KUBECONFIG": environment}), + mock.patch.object(acs_custom, "_print_or_merge_credentials") as merge, + mock.patch.object(acs_custom, "which", return_value=kubelogin_path) as which, + mock.patch.object(acs_custom.subprocess, "run") as run, + ): + acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path=path) + + merge.assert_called_once_with(selected_path, self.kubeconfig, False, None) + which.assert_called_once_with("kubelogin") + run.assert_called_once_with( + [os.path.abspath(kubelogin_path), "convert-kubeconfig", "-l", "azurecli", + "--kubeconfig", os.path.abspath(selected_path)], + check=True, + ) + + @unittest.skipIf(os.name == "nt", "Requires a POSIX executable script.") + def test_aks_get_credentials_converts_relative_file(self): + with tempfile.TemporaryDirectory() as directory: + kubelogin_path = os.path.join(directory, "kubelogin") + unrelated_path = os.path.join(directory, "unrelated-config") + selected_path = os.path.join(directory, "config") + with open(kubelogin_path, "w") as stream: + stream.write( + "#!{}\n" + "import os, sys\n" + "from pathlib import Path\n" + "path = (sys.argv[sys.argv.index('--kubeconfig') + 1] if '--kubeconfig' in sys.argv\n" + " else os.environ['KUBECONFIG'])\n" + "config = Path(path)\n" + "config.write_text(config.read_text().replace('devicecode', 'azurecli'))\n".format(sys.executable) + ) + os.chmod(kubelogin_path, 0o700) + with open(unrelated_path, "w") as stream: + stream.write(self.kubeconfig) + original_directory = os.getcwd() + try: + os.chdir(directory) + with mock.patch.dict(os.environ, { + "PATH": directory + os.pathsep + os.environ.get("PATH", ""), + "KUBECONFIG": unrelated_path, + }): + acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path="config") + finally: + os.chdir(original_directory) + + with open(selected_path) as stream: + config = yaml.safe_load(stream) + self.assertEqual(config["users"][0]["user"]["exec"]["args"][-1], "azurecli") + with open(unrelated_path) as stream: + self.assertEqual(stream.read(), self.kubeconfig) + + def test_aks_get_credentials_stdout_skips_conversion(self): + with ( + mock.patch("sys.stdout", new_callable=io.StringIO) as stdout, + mock.patch.object(acs_custom, "which") as which, + mock.patch.object(acs_custom.subprocess, "run") as run, + ): + acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path="-") + + self.assertEqual(stdout.getvalue(), self.kubeconfig + "\n") + which.assert_not_called() + run.assert_not_called() + + def test_aks_get_credentials_other_auth_skips_conversion(self): + self.client.list_cluster_user_credentials.return_value.kubeconfigs[0].value = ( + self.kubeconfig.replace("devicecode", "azurecli").encode("utf-8") + ) + with ( + mock.patch.object(acs_custom, "_print_or_merge_credentials"), + mock.patch.object(acs_custom, "which") as which, + mock.patch.object(acs_custom.subprocess, "run") as run, + ): + acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path="config") + + which.assert_not_called() + run.assert_not_called() + + def test_aks_get_credentials_conversion_failures_warn(self): + for kubelogin_path, error, message in ( + (None, None, "Please install kubelogin"), + ("kubelogin", subprocess.CalledProcessError(1, ["kubelogin"]), "Failed to convert kubeconfig"), + ("kubelogin", OSError("Cannot execute kubelogin"), "Error running kubelogin"), + ): + with ( + self.subTest(message=message), + mock.patch.object(acs_custom, "_print_or_merge_credentials"), + mock.patch.object(acs_custom, "which", return_value=kubelogin_path), + mock.patch.object(acs_custom.subprocess, "run", side_effect=error) as run, + mock.patch.object(acs_custom, "logger") as logger, + ): + acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path="config") + + logger.warning.assert_called_once() + self.assertIn(message, logger.warning.call_args[0][0]) + if kubelogin_path is None: + run.assert_not_called() + + class TestAKSCommand(unittest.TestCase): def setUp(self): self.cli_ctx = MockCLI() From 22b6a0a86dee3bc43e22acebfdc9aa4ee32bdb7c Mon Sep 17 00:00:00 2001 From: Fuming Zhang Date: Thu, 19 Nov 2026 03:37:52 +0000 Subject: [PATCH 2/4] [AKS] Preserve kubeconfig directory symlink semantics Resolve the conversion target after credential merging so paths containing a directory symlink followed by dot-dot still select the file that was written. Preserve the existing rejection of symlink kubeconfig files. Cover relative, absolute and KUBECONFIG-provided paths and verify unrelated files remain unchanged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../azure/cli/command_modules/acs/custom.py | 4 +- .../acs/tests/latest/test_custom.py | 69 ++++++++++++++++++- 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/src/azure-cli/azure/cli/command_modules/acs/custom.py b/src/azure-cli/azure/cli/command_modules/acs/custom.py index 5df23a58f74..7e8c52ea7fe 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/custom.py +++ b/src/azure-cli/azure/cli/command_modules/acs/custom.py @@ -2068,13 +2068,13 @@ def aks_get_credentials(cmd, client, resource_group_name, name, admin=False, kubelogin_path = which("kubelogin") if kubelogin_path: try: - # Run kubelogin convert-kubeconfig -l azurecli + # Resolve directory symlinks after merging has rejected a symlink file. subprocess.run( [ os.path.abspath(kubelogin_path), "convert-kubeconfig", "-l", "azurecli", - "--kubeconfig", os.path.abspath(path), + "--kubeconfig", os.path.realpath(path), ], check=True, ) diff --git a/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py b/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py index e5de133191f..fa764d095f4 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py +++ b/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py @@ -2379,7 +2379,7 @@ def test_aks_get_credentials_converts_selected_file(self): which.assert_called_once_with("kubelogin") run.assert_called_once_with( [os.path.abspath(kubelogin_path), "convert-kubeconfig", "-l", "azurecli", - "--kubeconfig", os.path.abspath(selected_path)], + "--kubeconfig", os.path.realpath(selected_path)], check=True, ) @@ -2419,6 +2419,73 @@ def test_aks_get_credentials_converts_relative_file(self): with open(unrelated_path) as stream: self.assertEqual(stream.read(), self.kubeconfig) + @unittest.skipIf(os.name == "nt", "Requires directory symlinks.") + def test_aks_get_credentials_converts_symlink_parent_path(self): + def convert(args, check): + self.assertTrue(check) + path = args[args.index("--kubeconfig") + 1] + with open(path, "r+") as stream: + content = stream.read() + stream.seek(0) + stream.write(content.replace("devicecode", "azurecli")) + stream.truncate() + + with tempfile.TemporaryDirectory() as directory: + real_directory = os.path.join(directory, "actual") + nested_directory = os.path.join(real_directory, "nested") + os.makedirs(nested_directory) + os.symlink(nested_directory, os.path.join(directory, "linked"), target_is_directory=True) + original_directory = os.getcwd() + try: + os.chdir(directory) + for source in ("relative", "absolute", "environment"): + filename = source + "-config" + selected_path = os.path.join("linked", "..", filename) + if source != "relative": + selected_path = os.path.join(directory, selected_path) + output_path = os.path.join(real_directory, filename) + unrelated_path = os.path.join(directory, filename) + with open(unrelated_path, "w") as stream: + stream.write(self.kubeconfig) + path = (os.path.join(os.path.expanduser("~"), ".kube", "config") + if source == "environment" else selected_path) + with ( + self.subTest(source=source), + mock.patch.dict(os.environ, {"KUBECONFIG": selected_path}), + mock.patch.object(acs_custom, "which", return_value=os.path.join(directory, "kubelogin")), + mock.patch.object(acs_custom.subprocess, "run", side_effect=convert), + ): + acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path=path) + + with open(output_path) as stream: + config = yaml.safe_load(stream) + self.assertEqual(config["users"][0]["user"]["exec"]["args"][-1], "azurecli") + with open(unrelated_path) as stream: + self.assertEqual(stream.read(), self.kubeconfig) + finally: + os.chdir(original_directory) + + @unittest.skipIf(os.name == "nt", "Requires file symlinks.") + def test_aks_get_credentials_rejects_symlink_file_before_conversion(self): + with tempfile.TemporaryDirectory() as directory: + target_path = os.path.join(directory, "target") + link_path = os.path.join(directory, "config") + with open(target_path, "w") as stream: + stream.write(self.kubeconfig) + os.symlink(target_path, link_path) + with ( + mock.patch.object(acs_custom, "which") as which, + mock.patch.object(acs_custom.subprocess, "run") as run, + ): + with self.assertRaisesRegex(CLIError, "symbolic link"): + acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path=link_path) + + which.assert_not_called() + run.assert_not_called() + self.assertTrue(os.path.islink(link_path)) + with open(target_path) as stream: + self.assertEqual(stream.read(), self.kubeconfig) + def test_aks_get_credentials_stdout_skips_conversion(self): with ( mock.patch("sys.stdout", new_callable=io.StringIO) as stdout, From 5bd766cb0d419accfb432c91a4deeb0a31bccce2 Mon Sep 17 00:00:00 2001 From: Fuming Zhang Date: Thu, 19 Nov 2026 03:45:13 +0000 Subject: [PATCH 3/4] [AKS] Preserve resolved kubelogin executable paths Use the shared safe executable resolver for kubeconfig conversion and invoke its result directly. Avoid lexical normalization changing which executable is selected when PATH contains directory symlinks followed by dot-dot. Cover executable path identity and working-directory decoys while preserving kubeconfig selection, symlink-file protection and conversion warnings. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../azure/cli/command_modules/acs/custom.py | 6 +- .../acs/tests/latest/test_custom.py | 106 +++++++++++++++--- 2 files changed, 94 insertions(+), 18 deletions(-) diff --git a/src/azure-cli/azure/cli/command_modules/acs/custom.py b/src/azure-cli/azure/cli/command_modules/acs/custom.py index 7e8c52ea7fe..e226f48dbc9 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/custom.py +++ b/src/azure-cli/azure/cli/command_modules/acs/custom.py @@ -2017,6 +2017,8 @@ def aks_get_credentials(cmd, client, resource_group_name, name, admin=False, '~'), '.kube', 'config'), overwrite_existing=False, context_name=None, public_fqdn=False, credential_format=None): + from azure.cli.core.util import get_safe_executable_path + credentialResults = None serverType = None if public_fqdn: @@ -2065,13 +2067,13 @@ def aks_get_credentials(cmd, client, resource_group_name, name, admin=False, # Check if kubeconfig requires kubelogin with devicecode and convert it if path != "-" and uses_kubelogin_devicecode(kubeconfig): - kubelogin_path = which("kubelogin") + kubelogin_path = get_safe_executable_path("kubelogin") if kubelogin_path: try: # Resolve directory symlinks after merging has rejected a symlink file. subprocess.run( [ - os.path.abspath(kubelogin_path), + kubelogin_path, "convert-kubeconfig", "-l", "azurecli", "--kubeconfig", os.path.realpath(path), diff --git a/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py b/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py index fa764d095f4..67616fc1016 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py +++ b/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py @@ -2359,7 +2359,7 @@ def test_aks_get_credentials_converts_selected_file(self): nested_path = os.path.join("config dir", "config") absolute_path = os.path.abspath(nested_path) default_path = os.path.join(os.path.expanduser("~"), ".kube", "config") - kubelogin_path = os.path.join("tools", "kubelogin") + kubelogin_path = os.path.abspath(os.path.join("tools", "kubelogin")) for path, environment, selected_path in ( ("config", "inherited-config", "config"), (nested_path, "inherited-config", nested_path), @@ -2370,23 +2370,95 @@ def test_aks_get_credentials_converts_selected_file(self): self.subTest(path=path), mock.patch.dict(os.environ, {"KUBECONFIG": environment}), mock.patch.object(acs_custom, "_print_or_merge_credentials") as merge, - mock.patch.object(acs_custom, "which", return_value=kubelogin_path) as which, + mock.patch("azure.cli.core.util.get_safe_executable_path", return_value=kubelogin_path) as resolve, mock.patch.object(acs_custom.subprocess, "run") as run, ): acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path=path) merge.assert_called_once_with(selected_path, self.kubeconfig, False, None) - which.assert_called_once_with("kubelogin") + resolve.assert_called_once_with("kubelogin") run.assert_called_once_with( - [os.path.abspath(kubelogin_path), "convert-kubeconfig", "-l", "azurecli", + [kubelogin_path, "convert-kubeconfig", "-l", "azurecli", "--kubeconfig", os.path.realpath(selected_path)], check=True, ) + @unittest.skipIf(os.name == "nt", "Requires directory symlinks.") + def test_aks_get_credentials_preserves_executable_symlink_path(self): + with tempfile.TemporaryDirectory() as directory: + actual_directory = os.path.join(directory, "actual") + nested_directory = os.path.join(actual_directory, "nested") + os.makedirs(nested_directory) + for parent in (actual_directory, directory): + tools_directory = os.path.join(parent, "tools") + os.mkdir(tools_directory) + executable = os.path.join(tools_directory, "kubelogin") + with open(executable, "w"): + pass + os.chmod(executable, 0o700) + os.symlink(nested_directory, os.path.join(directory, "linked"), target_is_directory=True) + search_path = os.path.join(directory, "linked", "..", "tools") + with ( + mock.patch.dict(os.environ, {"PATH": search_path}), + mock.patch.object(acs_custom, "_print_or_merge_credentials"), + mock.patch.object(acs_custom.subprocess, "run") as run, + ): + acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path="config") + + executable = run.call_args.args[0][0] + self.assertTrue(os.path.samefile(executable, os.path.join(actual_directory, "tools", "kubelogin"))) + self.assertFalse(os.path.samefile(executable, os.path.join(directory, "tools", "kubelogin"))) + + def test_aks_get_credentials_ignores_working_directory_executable(self): + with tempfile.TemporaryDirectory() as directory: + working_directory = os.path.join(directory, "work") + tools_directory = os.path.join(directory, "tools") + executable_name = "kubelogin.exe" if os.name == "nt" else "kubelogin" + for executable_directory in (working_directory, tools_directory): + os.mkdir(executable_directory) + executable = os.path.join(executable_directory, executable_name) + with open(executable, "w"): + pass + os.chmod(executable, 0o700) + + original_directory = os.getcwd() + try: + os.chdir(working_directory) + for entry in ("", ".", working_directory): + for trusted in (True, False): + search_path = [entry, tools_directory] if trusted else [entry] + with ( + self.subTest(entry=entry, trusted=trusted), + mock.patch.dict(os.environ, { + "PATH": os.pathsep.join(search_path), + "PATHEXT": ".exe", + "SystemRoot": os.path.join(directory, "system"), + }), + mock.patch.object(acs_custom, "_print_or_merge_credentials"), + mock.patch.object(acs_custom.subprocess, "run") as run, + mock.patch.object(acs_custom, "logger") as logger, + ): + acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path="config") + + if trusted: + run.assert_called_once_with( + [os.path.join(tools_directory, executable_name), + "convert-kubeconfig", "-l", "azurecli", + "--kubeconfig", os.path.realpath("config")], + check=True, + ) + else: + run.assert_not_called() + self.assertIn("Please install kubelogin", logger.warning.call_args.args[0]) + finally: + os.chdir(original_directory) + @unittest.skipIf(os.name == "nt", "Requires a POSIX executable script.") def test_aks_get_credentials_converts_relative_file(self): with tempfile.TemporaryDirectory() as directory: - kubelogin_path = os.path.join(directory, "kubelogin") + tools_directory = os.path.join(directory, "tools") + os.mkdir(tools_directory) + kubelogin_path = os.path.join(tools_directory, "kubelogin") unrelated_path = os.path.join(directory, "unrelated-config") selected_path = os.path.join(directory, "config") with open(kubelogin_path, "w") as stream: @@ -2406,7 +2478,7 @@ def test_aks_get_credentials_converts_relative_file(self): try: os.chdir(directory) with mock.patch.dict(os.environ, { - "PATH": directory + os.pathsep + os.environ.get("PATH", ""), + "PATH": tools_directory + os.pathsep + os.environ.get("PATH", ""), "KUBECONFIG": unrelated_path, }): acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path="config") @@ -2452,7 +2524,8 @@ def convert(args, check): with ( self.subTest(source=source), mock.patch.dict(os.environ, {"KUBECONFIG": selected_path}), - mock.patch.object(acs_custom, "which", return_value=os.path.join(directory, "kubelogin")), + mock.patch("azure.cli.core.util.get_safe_executable_path", + return_value=os.path.join(directory, "kubelogin")), mock.patch.object(acs_custom.subprocess, "run", side_effect=convert), ): acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path=path) @@ -2474,13 +2547,13 @@ def test_aks_get_credentials_rejects_symlink_file_before_conversion(self): stream.write(self.kubeconfig) os.symlink(target_path, link_path) with ( - mock.patch.object(acs_custom, "which") as which, + mock.patch("azure.cli.core.util.get_safe_executable_path") as resolve, mock.patch.object(acs_custom.subprocess, "run") as run, ): with self.assertRaisesRegex(CLIError, "symbolic link"): acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path=link_path) - which.assert_not_called() + resolve.assert_not_called() run.assert_not_called() self.assertTrue(os.path.islink(link_path)) with open(target_path) as stream: @@ -2489,13 +2562,13 @@ def test_aks_get_credentials_rejects_symlink_file_before_conversion(self): def test_aks_get_credentials_stdout_skips_conversion(self): with ( mock.patch("sys.stdout", new_callable=io.StringIO) as stdout, - mock.patch.object(acs_custom, "which") as which, + mock.patch("azure.cli.core.util.get_safe_executable_path") as resolve, mock.patch.object(acs_custom.subprocess, "run") as run, ): acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path="-") self.assertEqual(stdout.getvalue(), self.kubeconfig + "\n") - which.assert_not_called() + resolve.assert_not_called() run.assert_not_called() def test_aks_get_credentials_other_auth_skips_conversion(self): @@ -2504,24 +2577,25 @@ def test_aks_get_credentials_other_auth_skips_conversion(self): ) with ( mock.patch.object(acs_custom, "_print_or_merge_credentials"), - mock.patch.object(acs_custom, "which") as which, + mock.patch("azure.cli.core.util.get_safe_executable_path") as resolve, mock.patch.object(acs_custom.subprocess, "run") as run, ): acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path="config") - which.assert_not_called() + resolve.assert_not_called() run.assert_not_called() def test_aks_get_credentials_conversion_failures_warn(self): + executable = os.path.abspath(os.path.join("tools", "kubelogin")) for kubelogin_path, error, message in ( (None, None, "Please install kubelogin"), - ("kubelogin", subprocess.CalledProcessError(1, ["kubelogin"]), "Failed to convert kubeconfig"), - ("kubelogin", OSError("Cannot execute kubelogin"), "Error running kubelogin"), + (executable, subprocess.CalledProcessError(1, [executable]), "Failed to convert kubeconfig"), + (executable, OSError("Cannot execute kubelogin"), "Error running kubelogin"), ): with ( self.subTest(message=message), mock.patch.object(acs_custom, "_print_or_merge_credentials"), - mock.patch.object(acs_custom, "which", return_value=kubelogin_path), + mock.patch("azure.cli.core.util.get_safe_executable_path", return_value=kubelogin_path), mock.patch.object(acs_custom.subprocess, "run", side_effect=error) as run, mock.patch.object(acs_custom, "logger") as logger, ): From 9e69fee04343d963564c50b47266787c276b2b55 Mon Sep 17 00:00:00 2001 From: Fuming Zhang Date: Thu, 19 Nov 2026 04:02:08 +0000 Subject: [PATCH 4/4] Revert "[AKS] Preserve resolved kubelogin executable paths" This reverts commit 5bd766cb0d419accfb432c91a4deeb0a31bccce2. Keep executable lookup changes scoped to Azure/azure-cli#34445. Preserve the kubeconfig output-path fixes and directory symlink regression coverage in this PR. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../azure/cli/command_modules/acs/custom.py | 6 +- .../acs/tests/latest/test_custom.py | 106 +++--------------- 2 files changed, 18 insertions(+), 94 deletions(-) diff --git a/src/azure-cli/azure/cli/command_modules/acs/custom.py b/src/azure-cli/azure/cli/command_modules/acs/custom.py index e226f48dbc9..7e8c52ea7fe 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/custom.py +++ b/src/azure-cli/azure/cli/command_modules/acs/custom.py @@ -2017,8 +2017,6 @@ def aks_get_credentials(cmd, client, resource_group_name, name, admin=False, '~'), '.kube', 'config'), overwrite_existing=False, context_name=None, public_fqdn=False, credential_format=None): - from azure.cli.core.util import get_safe_executable_path - credentialResults = None serverType = None if public_fqdn: @@ -2067,13 +2065,13 @@ def aks_get_credentials(cmd, client, resource_group_name, name, admin=False, # Check if kubeconfig requires kubelogin with devicecode and convert it if path != "-" and uses_kubelogin_devicecode(kubeconfig): - kubelogin_path = get_safe_executable_path("kubelogin") + kubelogin_path = which("kubelogin") if kubelogin_path: try: # Resolve directory symlinks after merging has rejected a symlink file. subprocess.run( [ - kubelogin_path, + os.path.abspath(kubelogin_path), "convert-kubeconfig", "-l", "azurecli", "--kubeconfig", os.path.realpath(path), diff --git a/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py b/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py index 67616fc1016..fa764d095f4 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py +++ b/src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_custom.py @@ -2359,7 +2359,7 @@ def test_aks_get_credentials_converts_selected_file(self): nested_path = os.path.join("config dir", "config") absolute_path = os.path.abspath(nested_path) default_path = os.path.join(os.path.expanduser("~"), ".kube", "config") - kubelogin_path = os.path.abspath(os.path.join("tools", "kubelogin")) + kubelogin_path = os.path.join("tools", "kubelogin") for path, environment, selected_path in ( ("config", "inherited-config", "config"), (nested_path, "inherited-config", nested_path), @@ -2370,95 +2370,23 @@ def test_aks_get_credentials_converts_selected_file(self): self.subTest(path=path), mock.patch.dict(os.environ, {"KUBECONFIG": environment}), mock.patch.object(acs_custom, "_print_or_merge_credentials") as merge, - mock.patch("azure.cli.core.util.get_safe_executable_path", return_value=kubelogin_path) as resolve, + mock.patch.object(acs_custom, "which", return_value=kubelogin_path) as which, mock.patch.object(acs_custom.subprocess, "run") as run, ): acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path=path) merge.assert_called_once_with(selected_path, self.kubeconfig, False, None) - resolve.assert_called_once_with("kubelogin") + which.assert_called_once_with("kubelogin") run.assert_called_once_with( - [kubelogin_path, "convert-kubeconfig", "-l", "azurecli", + [os.path.abspath(kubelogin_path), "convert-kubeconfig", "-l", "azurecli", "--kubeconfig", os.path.realpath(selected_path)], check=True, ) - @unittest.skipIf(os.name == "nt", "Requires directory symlinks.") - def test_aks_get_credentials_preserves_executable_symlink_path(self): - with tempfile.TemporaryDirectory() as directory: - actual_directory = os.path.join(directory, "actual") - nested_directory = os.path.join(actual_directory, "nested") - os.makedirs(nested_directory) - for parent in (actual_directory, directory): - tools_directory = os.path.join(parent, "tools") - os.mkdir(tools_directory) - executable = os.path.join(tools_directory, "kubelogin") - with open(executable, "w"): - pass - os.chmod(executable, 0o700) - os.symlink(nested_directory, os.path.join(directory, "linked"), target_is_directory=True) - search_path = os.path.join(directory, "linked", "..", "tools") - with ( - mock.patch.dict(os.environ, {"PATH": search_path}), - mock.patch.object(acs_custom, "_print_or_merge_credentials"), - mock.patch.object(acs_custom.subprocess, "run") as run, - ): - acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path="config") - - executable = run.call_args.args[0][0] - self.assertTrue(os.path.samefile(executable, os.path.join(actual_directory, "tools", "kubelogin"))) - self.assertFalse(os.path.samefile(executable, os.path.join(directory, "tools", "kubelogin"))) - - def test_aks_get_credentials_ignores_working_directory_executable(self): - with tempfile.TemporaryDirectory() as directory: - working_directory = os.path.join(directory, "work") - tools_directory = os.path.join(directory, "tools") - executable_name = "kubelogin.exe" if os.name == "nt" else "kubelogin" - for executable_directory in (working_directory, tools_directory): - os.mkdir(executable_directory) - executable = os.path.join(executable_directory, executable_name) - with open(executable, "w"): - pass - os.chmod(executable, 0o700) - - original_directory = os.getcwd() - try: - os.chdir(working_directory) - for entry in ("", ".", working_directory): - for trusted in (True, False): - search_path = [entry, tools_directory] if trusted else [entry] - with ( - self.subTest(entry=entry, trusted=trusted), - mock.patch.dict(os.environ, { - "PATH": os.pathsep.join(search_path), - "PATHEXT": ".exe", - "SystemRoot": os.path.join(directory, "system"), - }), - mock.patch.object(acs_custom, "_print_or_merge_credentials"), - mock.patch.object(acs_custom.subprocess, "run") as run, - mock.patch.object(acs_custom, "logger") as logger, - ): - acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path="config") - - if trusted: - run.assert_called_once_with( - [os.path.join(tools_directory, executable_name), - "convert-kubeconfig", "-l", "azurecli", - "--kubeconfig", os.path.realpath("config")], - check=True, - ) - else: - run.assert_not_called() - self.assertIn("Please install kubelogin", logger.warning.call_args.args[0]) - finally: - os.chdir(original_directory) - @unittest.skipIf(os.name == "nt", "Requires a POSIX executable script.") def test_aks_get_credentials_converts_relative_file(self): with tempfile.TemporaryDirectory() as directory: - tools_directory = os.path.join(directory, "tools") - os.mkdir(tools_directory) - kubelogin_path = os.path.join(tools_directory, "kubelogin") + kubelogin_path = os.path.join(directory, "kubelogin") unrelated_path = os.path.join(directory, "unrelated-config") selected_path = os.path.join(directory, "config") with open(kubelogin_path, "w") as stream: @@ -2478,7 +2406,7 @@ def test_aks_get_credentials_converts_relative_file(self): try: os.chdir(directory) with mock.patch.dict(os.environ, { - "PATH": tools_directory + os.pathsep + os.environ.get("PATH", ""), + "PATH": directory + os.pathsep + os.environ.get("PATH", ""), "KUBECONFIG": unrelated_path, }): acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path="config") @@ -2524,8 +2452,7 @@ def convert(args, check): with ( self.subTest(source=source), mock.patch.dict(os.environ, {"KUBECONFIG": selected_path}), - mock.patch("azure.cli.core.util.get_safe_executable_path", - return_value=os.path.join(directory, "kubelogin")), + mock.patch.object(acs_custom, "which", return_value=os.path.join(directory, "kubelogin")), mock.patch.object(acs_custom.subprocess, "run", side_effect=convert), ): acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path=path) @@ -2547,13 +2474,13 @@ def test_aks_get_credentials_rejects_symlink_file_before_conversion(self): stream.write(self.kubeconfig) os.symlink(target_path, link_path) with ( - mock.patch("azure.cli.core.util.get_safe_executable_path") as resolve, + mock.patch.object(acs_custom, "which") as which, mock.patch.object(acs_custom.subprocess, "run") as run, ): with self.assertRaisesRegex(CLIError, "symbolic link"): acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path=link_path) - resolve.assert_not_called() + which.assert_not_called() run.assert_not_called() self.assertTrue(os.path.islink(link_path)) with open(target_path) as stream: @@ -2562,13 +2489,13 @@ def test_aks_get_credentials_rejects_symlink_file_before_conversion(self): def test_aks_get_credentials_stdout_skips_conversion(self): with ( mock.patch("sys.stdout", new_callable=io.StringIO) as stdout, - mock.patch("azure.cli.core.util.get_safe_executable_path") as resolve, + mock.patch.object(acs_custom, "which") as which, mock.patch.object(acs_custom.subprocess, "run") as run, ): acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path="-") self.assertEqual(stdout.getvalue(), self.kubeconfig + "\n") - resolve.assert_not_called() + which.assert_not_called() run.assert_not_called() def test_aks_get_credentials_other_auth_skips_conversion(self): @@ -2577,25 +2504,24 @@ def test_aks_get_credentials_other_auth_skips_conversion(self): ) with ( mock.patch.object(acs_custom, "_print_or_merge_credentials"), - mock.patch("azure.cli.core.util.get_safe_executable_path") as resolve, + mock.patch.object(acs_custom, "which") as which, mock.patch.object(acs_custom.subprocess, "run") as run, ): acs_custom.aks_get_credentials(self.cmd, self.client, "rg", "cluster", path="config") - resolve.assert_not_called() + which.assert_not_called() run.assert_not_called() def test_aks_get_credentials_conversion_failures_warn(self): - executable = os.path.abspath(os.path.join("tools", "kubelogin")) for kubelogin_path, error, message in ( (None, None, "Please install kubelogin"), - (executable, subprocess.CalledProcessError(1, [executable]), "Failed to convert kubeconfig"), - (executable, OSError("Cannot execute kubelogin"), "Error running kubelogin"), + ("kubelogin", subprocess.CalledProcessError(1, ["kubelogin"]), "Failed to convert kubeconfig"), + ("kubelogin", OSError("Cannot execute kubelogin"), "Error running kubelogin"), ): with ( self.subTest(message=message), mock.patch.object(acs_custom, "_print_or_merge_credentials"), - mock.patch("azure.cli.core.util.get_safe_executable_path", return_value=kubelogin_path), + mock.patch.object(acs_custom, "which", return_value=kubelogin_path), mock.patch.object(acs_custom.subprocess, "run", side_effect=error) as run, mock.patch.object(acs_custom, "logger") as logger, ):