Replace random with secrets (#83668)

Use secrets library instead of random.

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
pull/81364/merge
Abhijeet Kasurde 4 months ago committed by GitHub
parent 504f5b1230
commit fe1183f8ac
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,3 @@
---
minor_changes:
- replace random with secrets library.

@ -12,7 +12,7 @@ from ansible.cli import CLI
import datetime
import os
import platform
import random
import secrets
import shlex
import shutil
import socket
@ -140,7 +140,7 @@ class PullCLI(CLI):
if options.sleep:
try:
secs = random.randint(0, int(options.sleep))
secs = secrets.randbelow(int(options.sleep))
options.sleep = secs
except ValueError:
raise AnsibleOptionsError("%s is not a number." % options.sleep)

@ -8,7 +8,7 @@ import errno
import json
import os
import pkgutil
import random
import secrets
import re
from importlib import import_module
@ -318,7 +318,7 @@ def _create_powershell_wrapper(b_module_data, module_path, module_args,
exec_manifest["actions"].insert(0, 'async_watchdog')
exec_manifest["actions"].insert(0, 'async_wrapper')
exec_manifest["async_jid"] = f'j{random.randint(0, 999999999999)}'
exec_manifest["async_jid"] = f'j{secrets.randbelow(999999999999)}'
exec_manifest["async_timeout_sec"] = async_timeout
exec_manifest["async_startup_timeout"] = C.config.get_config_value("WIN_ASYNC_STARTUP_TIMEOUT", variables=task_vars)

@ -28,7 +28,7 @@ from __future__ import annotations
import copy
import functools
import itertools
import random
import secrets
import sys
import time
@ -131,7 +131,7 @@ def generate_jittered_backoff(retries=10, delay_base=3, delay_threshold=60):
:param delay_threshold: The maximum time in seconds for any delay.
"""
for retry in range(0, retries):
yield random.randint(0, min(delay_threshold, delay_base * 2 ** retry))
yield secrets.randbelow(min(delay_threshold, delay_base * 2 ** retry))
def retry_never(exception_or_result):

@ -365,8 +365,8 @@ import datetime
import fnmatch
import locale as locale_module
import os
import random
import re
import secrets
import shutil
import sys
import tempfile
@ -1387,7 +1387,7 @@ def main():
err = ''
update_cache_retries = module.params.get('update_cache_retries')
update_cache_retry_max_delay = module.params.get('update_cache_retry_max_delay')
randomize = random.randint(0, 1000) / 1000.0
randomize = secrets.randbelow(1000) / 1000.0
for retry in range(update_cache_retries):
try:

@ -174,9 +174,9 @@ import glob
import json
import os
import re
import secrets
import sys
import tempfile
import random
import time
from ansible.module_utils.basic import AnsibleModule
@ -743,7 +743,7 @@ def main():
if update_cache:
update_cache_retries = module.params.get('update_cache_retries')
update_cache_retry_max_delay = module.params.get('update_cache_retry_max_delay')
randomize = random.randint(0, 1000) / 1000.0
randomize = secrets.randbelow(1000) / 1000.0
cache = apt.Cache()
for retry in range(update_cache_retries):

@ -8,8 +8,8 @@ from __future__ import annotations
import base64
import json
import os
import random
import re
import secrets
import shlex
import stat
import tempfile
@ -1114,7 +1114,7 @@ class ActionBase(ABC):
remote_files.append(remote_async_module_path)
async_limit = self._task.async_val
async_jid = f'j{random.randint(0, 999999999999)}'
async_jid = f'j{secrets.randbelow(999999999999)}'
# call the interpreter for async_wrapper directly
# this permits use of a script for an interpreter on non-Linux platforms

@ -4,7 +4,7 @@
from __future__ import annotations
import random
import secrets
import time
from datetime import datetime, timedelta, timezone
@ -304,7 +304,7 @@ class ActionModule(ActionBase):
except AnsibleConnectionFailure:
pass
# Use exponential backoff with a max timeout, plus a little bit of randomness
random_int = random.randint(0, 1000) / 1000
random_int = secrets.randbelow(1000) / 1000
fail_sleep = 2 ** fail_count + random_int
if fail_sleep > max_fail_sleep:

@ -6,7 +6,7 @@ from __future__ import annotations
import shlex
from abc import abstractmethod
from random import choice
from secrets import choice
from string import ascii_lowercase
from gettext import dgettext

@ -31,7 +31,7 @@ RETURN = """
- random item
type: raw
"""
import random
import secrets
from ansible.errors import AnsibleError
from ansible.module_utils.common.text.converters import to_native
@ -45,7 +45,7 @@ class LookupModule(LookupBase):
ret = terms
if terms:
try:
ret = [random.choice(terms)]
ret = [secrets.choice(terms)]
except Exception as e:
raise AnsibleError("Unable to choose random term: %s" % to_native(e))

@ -18,8 +18,8 @@ from __future__ import annotations
import os
import os.path
import random
import re
import secrets
import shlex
import time
@ -82,7 +82,7 @@ class ShellBase(AnsiblePlugin):
@staticmethod
def _generate_temp_dir_name():
return 'ansible-tmp-%s-%s-%s' % (time.time(), os.getpid(), random.randint(0, 2**48))
return 'ansible-tmp-%s-%s-%s' % (time.time(), os.getpid(), secrets.randbelow(2**48))
def env_prefix(self, **kwargs):
return ' '.join(['%s=%s' % (k, self.quote(text_type(v))) for k, v in kwargs.items()])

@ -33,7 +33,7 @@ import getpass
import io
import logging
import os
import random
import secrets
import subprocess
import sys
import termios
@ -636,7 +636,7 @@ class Display(metaclass=Singleton):
if self.noncow:
thecow = self.noncow
if thecow == 'random':
thecow = random.choice(list(self.cows_available))
thecow = secrets.choice(list(self.cows_available))
runcmd.append(b'-f')
runcmd.append(to_bytes(thecow))
runcmd.append(to_bytes(msg))

@ -18,7 +18,7 @@
from __future__ import annotations
import keyword
import random
import secrets
import uuid
from collections.abc import MutableMapping, MutableSequence
@ -37,7 +37,7 @@ ADDITIONAL_PY2_KEYWORDS = frozenset(("True", "False", "None"))
_MAXSIZE = 2 ** 32
cur_id = 0
node_mac = ("%012x" % uuid.getnode())[:12]
random_int = ("%08x" % random.randint(0, _MAXSIZE))[:8]
random_int = ("%08x" % secrets.randbelow(_MAXSIZE))[:8]
def get_unique_id():

Loading…
Cancel
Save