anon-iclr-submission/benchname-bug-localization huggingface dataset:
Repository: kubernetes-client/python
Issue: Using usedforsecurity in dynamic/discovery.py makes kubernetes-client work only in python >= 3.9

**What happened (please include outputs or screenshots)**:
As discovered in https://github.com/devopsspiral/KubeLibrary/issues/118 latest changes to the dynamic/discovery.py depend on python3.9 where usedforsecurity was introduced:

```
[ ERROR ] Error in file '/opt/robotframework/tests/k8s/smoke.robot' on line 3: Initializing library 'KubeLibrary' with arguments [ incluster=True ] failed: TypeError: openssl_md5() takes at most 1 argument (2 given)
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/KubeLibrary/KubeLibrary.py", line 96, in __init__
    self.reload_config(kube_config=kube_config, context=context, api_url=api_url, bearer_token=bearer_token,
  File "/usr/local/lib/python3.8/site-packages/KubeLibrary/KubeLibrary.py", line 267, in reload_config
    self._add_api('dynamic', DynamicClient)
  File "/usr/local/lib/python3.8/site-packages/KubeLibrary/KubeLibrary.py", line 270, in _add_api
    self.__dict__[reference] = class_name(self.api_client)
  File "/usr/local/lib/python3.8/site-packages/kubernetes/dynamic/client.py", line 84, in __init__
    self.__discoverer = discoverer(self, cache_file)
  File "/usr/local/lib/python3.8/site-packages/kubernetes/dynamic/discovery.py", line 224, in __init__
    Discoverer.__init__(self, client, cache_file)
  File "/usr/local/lib/python3.8/site-packages/kubernetes/dynamic/discovery.py", line 48, in __init__
    default_cachefile_name = 'osrcp-{0}.json'.format(hashlib.md5(default_cache_id, usedforsecurity=False).hexdigest())
TypeError: openssl_md5() takes at most 1 argument (2 given)
```
**What you expected to happen**:
Support for python>=3.7 (still in life)

**Environment**:
- Python version (`python --version`)
Python 3.8
- Python client version (`pip list | grep kubernetes`)
kubernetes-25.3.0 vs kubernetes-24.2.0

Changed files:
kubernetes/base/dynamic/discovery.py

diff --git a/kubernetes/base/dynamic/discovery.py b/kubernetes/base/dynamic/discovery.py
index 4acf7cf24..eeac6120e 100644
--- a/kubernetes/base/dynamic/discovery.py
+++ b/kubernetes/base/dynamic/discovery.py
@@ -45,7 +45,11 @@ class Discoverer(object):
         default_cache_id = self.client.configuration.host
         if six.PY3:
             default_cache_id = default_cache_id.encode('utf-8')
-        default_cachefile_name = 'osrcp-{0}.json'.format(hashlib.md5(default_cache_id, usedforsecurity=False).hexdigest())
+        try:
+            default_cachefile_name = 'osrcp-{0}.json'.format(hashlib.md5(default_cache_id, usedforsecurity=False).hexdigest())
+        except TypeError:
+            # usedforsecurity is only supported in 3.9+
+            default_cachefile_name = 'osrcp-{0}.json'.format(hashlib.md5(default_cache_id).hexdigest())
         self.__cache_file = cache_file or os.path.join(tempfile.gettempdir(), default_cachefile_name)
         self.__init_cache()
Repository: kubernetes-client/python
Issue: `certificate-authority-data` from kubeconfig fails for long-running process due to tmpfs cleanup

**What happened (please include outputs or screenshots)**:
Long-running applications using a kubeconfig with `certificate-authority-data` encounter errors like:
```
Max retries exceeded with url: /api/v1/pods?fieldSelector=spec.nodeName%3Dip-172-18-66-203.ec2.internal (Caused by SSLError(FileNotFoundError(2, 'No such file or directory'),))
```

**What you expected to happen**:
Client should not expect tempfiles to live indefinitely. It is extremely common for servers to reap tempfiles.

**Anything else we need to know?**:
If you create a client you can easily see that it is using a temp file that cannot go away for the duration of the client:
```
>>> import kubernetes.config
>>> kubernetes.config.load_kube_config()
>>> api_client = kubernetes.client.ApiClient()
>>> api_client.rest_client.pool_manager.connection_pool_kw["ca_certs"]
'/tmp/tmpqkht2v2g'
```
You can reproduce the issue by deleting that temp file and attempting to make a request.

Code is here: https://github.com/kubernetes-client/python/blob/1271465acdb80bf174c50564a384fd6898635ea6/kubernetes/base/config/kube_config.py#L63-L78

In order for this to work reliably for long-running processes on standard linux systems, the temp file really needs to be created for each request rather than a single time at startup.

That said, on linux systems, a potential hack would be to use `/proc/self/fd/<fileno>` instead of the temfile path since that would share the lifecycle of the process.

**Environment**:
- Python version (`python --version`): 3.6
- Python client version (`pip list | grep kubernetes`): 21.7.0

Changed files:
kubernetes/base/config/kube_config.py

diff --git a/kubernetes/base/config/kube_config.py b/kubernetes/base/config/kube_config.py
index f37ed43ec..ed70df0ca 100644
--- a/kubernetes/base/config/kube_config.py
+++ b/kubernetes/base/config/kube_config.py
@@ -789,7 +789,8 @@ def list_kube_config_contexts(config_file=None):
 
 def load_kube_config(config_file=None, context=None,
                      client_configuration=None,
-                     persist_config=True):
+                     persist_config=True,
+                     temp_file_path=None):
     """Loads authentication and cluster information from kube-config file
     and stores them in kubernetes.client.configuration.
 
@@ -800,6 +801,7 @@ def load_kube_config(config_file=None, context=None,
         set configs to.
     :param persist_config: If True, config file will be updated when changed
         (e.g GCP token refresh).
+    :param temp_file_path: store temp files path.
     """
 
     if config_file is None:
@@ -807,7 +809,8 @@ def load_kube_config(config_file=None, context=None,
 
     loader = _get_kube_config_loader(
         filename=config_file, active_context=context,
-        persist_config=persist_config)
+        persist_config=persist_config,
+        temp_file_path=temp_file_path)
 
     if client_configuration is None:
         config = type.__call__(Configuration)
Repository: kubernetes-client/python
Issue: K8sDynamicClient fails on FIPS-enabled OpenShift cluster

**What happened (please include outputs or screenshots)**:

Ansible operator based on **operator-sdk** v1.20.0 and later fails with
```
fatal: [localhost]: FAILED! => {"attempts": 3, "changed": false, "error": "[digital envelope routines: EVP_DigestInit_ex] disabled for FIPS", "msg": "Failed to get client due to %s"}
```

**What you expected to happen**:

Ansible operator continues to work after upgrading **operator-sdk** from v1.19.1 to v1.20.0 (and later)

**How to reproduce it (as minimally and precisely as possible)**:

Run an Ansible operator using the `k8s_status` task on a FIPS-enabled OpenShift cluster.

**Anything else we need to know?**:

Please see https://github.com/operator-framework/operator-sdk/issues/5723#issuecomment-1175975274 for error details and a potential fix.

**Environment**:
- Kubernetes version (`kubectl version`):
- OS (e.g., MacOS 10.13.6):
- Python version (`python --version`)
- Python client version (`pip list | grep kubernetes`)


Changed files:
kubernetes/base/dynamic/discovery.py

diff --git a/kubernetes/base/dynamic/discovery.py b/kubernetes/base/dynamic/discovery.py
index dbf94101b..4acf7cf24 100644
--- a/kubernetes/base/dynamic/discovery.py
+++ b/kubernetes/base/dynamic/discovery.py
@@ -45,7 +45,7 @@ class Discoverer(object):
         default_cache_id = self.client.configuration.host
         if six.PY3:
             default_cache_id = default_cache_id.encode('utf-8')
-        default_cachefile_name = 'osrcp-{0}.json'.format(hashlib.md5(default_cache_id).hexdigest())
+        default_cachefile_name = 'osrcp-{0}.json'.format(hashlib.md5(default_cache_id, usedforsecurity=False).hexdigest())
         self.__cache_file = cache_file or os.path.join(tempfile.gettempdir(), default_cachefile_name)
         self.__init_cache()
Repository: kubernetes-client/python
Issue: use unittest.mock instead of mock

Please consider to drop dependency on mock. unittest.mock can be used, as a fallback at least. As far as I tested, it works at least with 3.8, 3.9 and 3.10.

Changed files:
kubernetes/base/config/exec_provider_test.py, kubernetes/base/config/kube_config_test.py, kubernetes/base/watch/watch_test.py

diff --git a/kubernetes/base/config/exec_provider_test.py b/kubernetes/base/config/exec_provider_test.py
index a545b5565..d773edd94 100644
--- a/kubernetes/base/config/exec_provider_test.py
+++ b/kubernetes/base/config/exec_provider_test.py
@@ -15,7 +15,7 @@
 import os
 import unittest
 
-import mock
+from unittest import mock
 
 from .config_exception import ConfigException
 from .exec_provider import ExecProvider
diff --git a/kubernetes/base/config/kube_config_test.py b/kubernetes/base/config/kube_config_test.py
index 02127d154..6233e977d 100644
--- a/kubernetes/base/config/kube_config_test.py
+++ b/kubernetes/base/config/kube_config_test.py
@@ -22,7 +22,7 @@ import tempfile
 import unittest
 from collections import namedtuple
 
-import mock
+from unittest import mock
 import yaml
 from six import PY3, next
 
diff --git a/kubernetes/base/watch/watch_test.py b/kubernetes/base/watch/watch_test.py
index f87a4ea8b..8164e7b5d 100644
--- a/kubernetes/base/watch/watch_test.py
+++ b/kubernetes/base/watch/watch_test.py
@@ -14,7 +14,7 @@
 
 import unittest
 
-from mock import Mock, call
+from unittest.mock import Mock, call
 
 from kubernetes import client
Repository: kubernetes-client/python
Issue: Inconsistent timeout of WSClient.update

**What happened (please include outputs or screenshots)**:

https://github.com/kubernetes-client/python/blob/master/kubernetes/base/stream/ws_client.py#L182-L189
The timeout behavior of the `update` method is inconsistent.
Function `select.select` interprets timeout as floating-point seconds where the polling object (`poll` method) uses milliseconds.

**What you expected to happen**:

The timeout unit is the same in all cases.

**How to reproduce it (as minimally and precisely as possible)**:

Exec `update` with `select` and `poll`.

**Anything else we need to know?**:

**Environment**:
- Kubernetes version (`kubectl version`):
- OS (e.g., MacOS 10.13.6):
- Python version (`python --version`) `3.10.8`
- Python client version (`pip list | grep kubernetes`) `25.3.0`


Changed files:
kubernetes/base/stream/ws_client.py

diff --git a/kubernetes/base/stream/ws_client.py b/kubernetes/base/stream/ws_client.py
index 15cc3945f..4a7356a6d 100644
--- a/kubernetes/base/stream/ws_client.py
+++ b/kubernetes/base/stream/ws_client.py
@@ -182,6 +182,8 @@ class WSClient:
         if hasattr(select, "poll"):
             poll = select.poll()
             poll.register(self.sock.sock, select.POLLIN)
+            if timeout is not None:
+                timeout *= 1_000  # poll method uses milliseconds as the time unit
             r = poll.poll(timeout)
             poll.unregister(self.sock.sock)
         else:
Repository: kubernetes-client/python
Issue: setuptools is erroneously declared as a runtime dependency

The code base does not appear to use `setuptools` nor `pkg_resources`:

```
…\\kubernetes-client-python
❯ rg -M 150 "pkg_resources"

…\\kubernetes-client-python
❯ rg -M 150 "setuptools"
setup.py
15:from setuptools import setup
27:# prerequisite: setuptools
28:# http://pypi.python.org/pypi/setuptools

requirements.txt
4:setuptools>=21.0.0  # PSF/ZPL

kubernetes\\README.md
31:Install via [Setuptools](http://pypi.python.org/pypi/setuptools).
```

Changed files:
setup.py

diff --git a/setup.py b/setup.py
index 04bc04cd3..49fae21d4 100644
--- a/setup.py
+++ b/setup.py
@@ -35,7 +35,9 @@ with open('requirements.txt') as f:
     for line in f:
         line, _, _ = line.partition('#')
         line = line.strip()
-        if ';' in line:
+        if not line or line.startswith('setuptools'):
+            continue
+        elif ';' in line:
             requirement, _, specifier = line.partition(';')
             for_specifier = EXTRAS.setdefault(':{}'.format(specifier), [])
             for_specifier.append(requirement)
Repository: kubernetes-client/python
Issue: get_resources_for_api_version() expects sub-resource names to be of the format a/b

**What happened (please include outputs or screenshots)**:
get_resources_for_api_version() in https://github.com/kubernetes-client/python/blob/master/kubernetes/base/dynamic/discovery.py#L173, currently expects sub-resource names to be of the format a/b. This does not work with newly added apis in kubevirt which are of the format a/b/c. https://github.com/kubevirt/kubevirt/blame/9cf6dbb3e33c9ec9e9af8b18eb115c7fb9f7c311/pkg/virt-operator/resource/generate/rbac/cluster.go#L45-49

```14:46:39  INTERNALERROR>     resourcePart.resources = self.get_resources_for_api_version(
14:46:39  INTERNALERROR>   File "/cnv-tests/.venv/lib/python3.9/site-packages/kubernetes/dynamic/discovery.py", line 173, in get_resources_for_api_version
14:46:39  INTERNALERROR>     resource, name = subresource['name'].split('/')
14:46:39  INTERNALERROR> ValueError: too many values to unpack (expected 2)
```


**What you expected to happen**:
Are the sub-resource names supposed to be restricted to this a/b format because of any kubernetes or openshift restrictions? If not can we remove this restrictions?
**How to reproduce it (as minimally and precisely as possible)**:
Check with any subresources with the format of `virtualmachineinstances/sev/fetchcertchain`
**Anything else we need to know?**:

**Environment**:
- Kubernetes version (`kubectl version`): 1.27
- OS (e.g., MacOS 10.13.6): linux
- Python version (`python --version`): 3.9
- Python client version (`pip list | grep kubernetes`): 26.1.0


Changed files:
kubernetes/base/dynamic/discovery.py

diff --git a/kubernetes/base/dynamic/discovery.py b/kubernetes/base/dynamic/discovery.py
index eeac6120e..c00dfa3ef 100644
--- a/kubernetes/base/dynamic/discovery.py
+++ b/kubernetes/base/dynamic/discovery.py
@@ -170,7 +170,7 @@ class Discoverer(object):
         resources_raw = list(filter(lambda resource: '/' not in resource['name'], resources_response))
         subresources_raw = list(filter(lambda resource: '/' in resource['name'], resources_response))
         for subresource in subresources_raw:
-            resource, name = subresource['name'].split('/')
+            resource, name = subresource['name'].split('/', 1)
             if not subresources.get(resource):
                 subresources[resource] = {}
             subresources[resource][name] = subresource
Repository: kubernetes-client/python
Issue: ExecProvider swallows interactive messages

**What happened (please include outputs or screenshots)**:
When using [kubelogin](https://github.com/Azure/kubelogin) as an ExecProvider in kube config, upon initial use, kubelogin prints a message to stderr of the form:
```
To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code <device-code> to authenticate.
```
The current ExecProvider implementation swallows this message and blocks until the code times out and the kubelogin command returns (an exit code of 1).

**What you expected to happen**:
The ExecProvider implementation to provide some method to access the message such that it is either accessible to the python application to pass to a user, or passed to the user to action on some standard bus (stderr?).

**How to reproduce it (as minimally and precisely as possible)**:
Have kubelogin installed
Have a kube config setup with exec using kubelogin:
```yaml
<other config values>
users:
- name: aad-user
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1beta1
      command: kubelogin
      args: <kubelogin args depending on your azure auth setup>
```
*Don't authenticate through another means first (ie using kubectl)*
Attempt to auth using kubernetes library initially:
```python
from kubernetes import config

config.load_kube_config()
```

**Anything else we need to know?**:
I don't believe this is kubelogin specific, but rather any exec auth provider that prompts for user action will have the same issue. Let me know if I'm off basis and this should be a kubelogin issue instead tho :)

**Environment**:
kubernetes (python): 23.3.0
kubelogin: v0.0.10
Beyond that not environment specific

Changed files:
kubernetes/base/config/exec_provider.py

diff --git a/kubernetes/base/config/exec_provider.py b/kubernetes/base/config/exec_provider.py
index 08f0af2fb..3f9c8ca0d 100644
--- a/kubernetes/base/config/exec_provider.py
+++ b/kubernetes/base/config/exec_provider.py
@@ -57,11 +57,12 @@ class ExecProvider(object):
         self.cwd = cwd or None
 
     def run(self, previous_response=None):
+        is_interactive = sys.stdout.isatty()
         kubernetes_exec_info = {
             'apiVersion': self.api_version,
             'kind': 'ExecCredential',
             'spec': {
-                'interactive': sys.stdout.isatty()
+                'interactive': is_interactive
             }
         }
         if previous_response:
@@ -70,7 +71,8 @@ class ExecProvider(object):
         process = subprocess.Popen(
             self.args,
             stdout=subprocess.PIPE,
-            stderr=subprocess.PIPE,
+            stderr=sys.stderr if is_interactive else subprocess.PIPE,
+            stdin=sys.stdin if is_interactive else None,
             cwd=self.cwd,
             env=self.env,
             universal_newlines=True)
Repository: kubernetes-client/python
Issue: ExecPlugins are broken when using KubeConfigs loaded from dict

**What happened (please include outputs or screenshots)**:

We use https://github.com/kubernetes-client/python/blob/master/kubernetes/base/config/kube_config.py#L820 to load Kubeconfigs from memory in Python, these Kubeconfigs have a configuration to use an Exec plugin to get an auth token (specifically we are trying to auth with an EKS cluster.)

https://github.com/kubernetes-client/python-base/pull/275/files#diff-a994e720c2c925ca342b251f2d057ab3a730a1bdc166e5766249a30bdf170a47R73 this PR to python-base attempts to pass the cwd of the config file to the exec plugin, however the cwd of a config file loaded from a dict is empty string (https://github.com/kubernetes-client/python/blob/master/kubernetes/base/config/kube_config.py#L542). When empty string is passed to subprocess.Popen, subprocess.Popen errors with "ERROR:root:[Errno 2] No such file or directory: ''" and does not run the auth plugin. 

Commenting out https://github.com/kubernetes-client/python-base/pull/275/files#diff-a994e720c2c925ca342b251f2d057ab3a730a1bdc166e5766249a30bdf170a47R73 fixed our auth issues completely, but the longterm fix is probably checking if the base_path is empty string and if so, pass None as the cwd to Popen. 

The issue means that anyone using EKS with load_kube_config_from_dict has been broken since this PR was merged. 

**What you expected to happen**:
Run the ExecProvider and return a token
**How to reproduce it (as minimally and precisely as possible)**:
Use load_kube_config_from_dict with an Authentication configuration using "command" for the user

**Anything else we need to know?**:

**Environment**:
- Kubernetes version (`kubectl version`):
- OS (e.g., MacOS 10.13.6):
Linux
- Python version (`python --version`)
3.8.10
- Python client version (`pip list | grep kubernetes`)
23.3.0

Changed files:
kubernetes/base/config/exec_provider.py

diff --git a/kubernetes/base/config/exec_provider.py b/kubernetes/base/config/exec_provider.py
index ef3fac661..08f0af2fb 100644
--- a/kubernetes/base/config/exec_provider.py
+++ b/kubernetes/base/config/exec_provider.py
@@ -53,7 +53,8 @@ class ExecProvider(object):
                 value = item['value']
                 additional_vars[name] = value
             self.env.update(additional_vars)
-        self.cwd = cwd
+        
+        self.cwd = cwd or None
 
     def run(self, previous_response=None):
         kubernetes_exec_info = {
Repository: kubernetes-client/python
Issue: Python2 support dropped but installation works

**What happened (please include outputs or screenshots)**:
I have accidentally installed the git-Master-Branch with Python2 with these commands:
```
git clone --recursive https://github.com/kubernetes-client/python.git
cd python
python setup.py install
```
Everything works fine, but Python2 support is dropped (https://github.com/kubernetes-client/python/pull/1468)

**What you expected to happen**:
I expect an error Message like:
```
  File "setup.py", line 30, in <module>
    raise RuntimeError("kubernetes-client " + CLIENT_VERSION + " requires Python 3.6+")
RuntimeError: kubernetes-client 18.0.0-snapshot requires Python 3.6+
```


**How to reproduce it (as minimally and precisely as possible)**:
See in "What happened". 
You may have to use `python2 setup.py install` if `python --v` is not 2

**Anything else we need to know?**:
A possible fix in setup.py would be
```
import sys

from setuptools import setup

# Do not edit these constants. They will be updated automatically
# by scripts/update-client.sh.
CLIENT_VERSION = "18.0.0-snapshot"
PACKAGE_NAME = "kubernetes"
DEVELOPMENT_STATUS = "3 - Alpha"

# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools

if sys.version_info < (3, 6):
    raise RuntimeError("kubernetesclient " + CLIENT_VERSION + " requires Python 3.6+")
```
There is also some Python2 compatibility code in the python/ and python-base repo
For example:
- https://github.com/kubernetes-client/python/blob/master/kubernetes/client/apis/__init__.py#L1
- https://github.com/kubernetes-client/python-base/blob/0d4f822f4f654361764a6f8dcf7ca9bf5bbce3f9/leaderelection/leaderelection.py#L23
- https://github.com/kubernetes-client/python-base/blob/master/watch/watch.py#L32
- https://github.com/kubernetes-client/python-base/blob/b4d3aad42dc23e7a6c0e5c032691f8dc385a786c/dynamic/client.py#L60
Should that also be removed?

**Environment**:
- Kubernetes version (`kubectl version`):
v1.19.0
- OS (e.g., MacOS 10.13.6):
Fedora 29 (Workstation Edition)
- Python version (`python --version`)
Python 2.7.17
- Python client version (`pip list | grep kubernetes`)
18.0.0-snapshot


Changed files:
setup.py

diff --git a/setup.py b/setup.py
index 3796dc696..1368043ca 100644
--- a/setup.py
+++ b/setup.py
@@ -64,6 +64,7 @@ setup(
               'kubernetes.dynamic', 'kubernetes.leaderelection'],
     include_package_data=True,
     long_description="Python client for kubernetes http://kubernetes.io/",
+    python_requires='>=3.6',
     classifiers=[
         "Development Status :: %s" % DEVELOPMENT_STATUS,
         "Topic :: Utilities",