From 09497d2df0fbd4bb5ad798e5c0798a0faa632f11 Mon Sep 17 00:00:00 2001 From: Alexander Bokovoy Date: Mon, 7 Aug 2023 13:40:34 +0300 Subject: [PATCH] python 3.12: utcnow function is deprecated The following warning is displayed on a system running with Python 3.12: ------------------- /usr/lib/python3.12/site-packages/ipalib/rpc.py:925: DeprecationWarning: datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.now(datetime.UTC). timestamp=datetime.datetime.utcnow()) ------------------- Fixes: https://pagure.io/freeipa/issue/9425 Signed-off-by: Alexander Bokovoy Reviewed-By: Florence Blanc-Renaud --- ipaclient/install/ipa_epn.py | 8 ++++---- ipalib/parameters.py | 2 +- ipalib/rpc.py | 4 ++-- ipalib/x509.py | 6 ++++-- ipapython/certdb.py | 2 +- ipapython/cookie.py | 2 +- ipaserver/install/certs.py | 2 +- ipaserver/install/ipa_cacert_manage.py | 2 +- ipatests/create_external_ca.py | 2 +- ipatests/pytest_ipa/integration/create_caless_pki.py | 8 ++++---- ipatests/test_integration/test_epn.py | 9 ++++++--- ipatests/test_integration/test_ipahealthcheck.py | 4 ++-- ipatests/test_ipalib/test_x509.py | 8 ++++---- ipatests/test_ipapython/test_cookie.py | 2 +- ipatests/test_webui/crypto_utils.py | 6 +++--- 15 files changed, 36 insertions(+), 31 deletions(-) diff --git a/ipaclient/install/ipa_epn.py b/ipaclient/install/ipa_epn.py index a339c011c..7c6afbca5 100644 --- a/ipaclient/install/ipa_epn.py +++ b/ipaclient/install/ipa_epn.py @@ -33,7 +33,7 @@ import ssl import time from collections import deque -from datetime import datetime, timedelta +from datetime import datetime, timedelta, UTC from email.utils import formataddr, formatdate from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText @@ -337,7 +337,7 @@ class EPN(admintool.AdminTool): of days in the future. If only nbdays_end is specified, the range is 1d long. """ - now = datetime.utcnow() + now = datetime.now(tz=UTC) today_at_midnight = datetime.combine(now, datetime.min.time()) range_end = today_at_midnight + timedelta(days=nbdays_end) if nbdays_start is not None: @@ -568,7 +568,7 @@ class EPN(admintool.AdminTool): mail_from=mail_from, mail_from_name=api.env.mail_from_name, ) - now = datetime.utcnow() + now = datetime.now(tz=UTC) expdate = datetime.strptime( entry["krbpasswordexpiration"], '%Y-%m-%d %H:%M:%S') @@ -583,7 +583,7 @@ class EPN(admintool.AdminTool): def _gentestdata(self): """Generate a sample user to process through the template. """ - expdate = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') + expdate = datetime.now(tz=UTC).strftime('%Y-%m-%d %H:%M:%S') entry = dict( uid=["SAUSER"], cn=["SAMPLE USER"], diff --git a/ipalib/parameters.py b/ipalib/parameters.py index 88449d08c..435fb5c8f 100644 --- a/ipalib/parameters.py +++ b/ipalib/parameters.py @@ -1836,7 +1836,7 @@ class DateTime(Param): def _convert_scalar(self, value, index=None): if isinstance(value, str): if value == u'now': - time = datetime.datetime.utcnow() + time = datetime.datetime.now(tz=datetime.UTC) return time else: for date_format in self.accepted_formats: diff --git a/ipalib/rpc.py b/ipalib/rpc.py index 69756cea0..655b231b9 100644 --- a/ipalib/rpc.py +++ b/ipalib/rpc.py @@ -819,7 +819,7 @@ class KerbTransport(SSLTransport): session_cookie = ( Cookie.get_named_cookie_from_string( cookie, COOKIE_NAME, request_url, - timestamp=datetime.datetime.utcnow()) + timestamp=datetime.datetime.now(tz=datetime.UTC)) ) if session_cookie is not None: break @@ -922,7 +922,7 @@ class RPCClient(Connectible): try: session_cookie = Cookie.get_named_cookie_from_string( cookie_string, COOKIE_NAME, - timestamp=datetime.datetime.utcnow()) + timestamp=datetime.datetime.now(tz=datetime.UTC)) except Exception as e: logger.debug( 'Error retrieving cookie from the persistent storage: %s', diff --git a/ipalib/x509.py b/ipalib/x509.py index 0b65d3476..ecc6f0f9a 100644 --- a/ipalib/x509.py +++ b/ipalib/x509.py @@ -266,11 +266,13 @@ class IPACertificate(crypto_x509.Certificate): @property def not_valid_before(self): - return self._cert.not_valid_before + return datetime.datetime.fromtimestamp( + self._cert.not_valid_before.timestamp(), tz=datetime.UTC) @property def not_valid_after(self): - return self._cert.not_valid_after + return datetime.datetime.fromtimestamp( + self._cert.not_valid_after.timestamp(), tz=datetime.UTC) @property def tbs_certificate_bytes(self): diff --git a/ipapython/certdb.py b/ipapython/certdb.py index 9a18e3987..d2918ded8 100644 --- a/ipapython/certdb.py +++ b/ipapython/certdb.py @@ -943,7 +943,7 @@ class NSSDatabase: def _verify_cert_validity(self, cert): """Common checks for cert validity """ - utcnow = datetime.datetime.utcnow() + utcnow = datetime.datetime.now(tz=datetime.UTC) if cert.not_valid_before > utcnow: raise ValueError( f"not valid before {cert.not_valid_before} UTC is in the " diff --git a/ipapython/cookie.py b/ipapython/cookie.py index 15123122f..33c07189c 100644 --- a/ipapython/cookie.py +++ b/ipapython/cookie.py @@ -652,7 +652,7 @@ class Cookie: cookie_expiration = self.get_expiration() if cookie_expiration is not None: - now = datetime.datetime.utcnow() + now = datetime.datetime.now(tz=datetime.UTC) if cookie_expiration < now: raise Cookie.Expired("cookie named '%s'; expired at %s'" % \ (cookie_name, diff --git a/ipaserver/install/certs.py b/ipaserver/install/certs.py index e58517df7..0ec001a75 100644 --- a/ipaserver/install/certs.py +++ b/ipaserver/install/certs.py @@ -740,7 +740,7 @@ class _CrossProcessLock: self._do(self._release, owner) def _acquire(self, owner): - now = datetime.datetime.utcnow() + now = datetime.datetime.now(tz=datetime.UTC) if self._locked and now >= self._expire: self._locked = False diff --git a/ipaserver/install/ipa_cacert_manage.py b/ipaserver/install/ipa_cacert_manage.py index f6e87578f..32ef25b47 100644 --- a/ipaserver/install/ipa_cacert_manage.py +++ b/ipaserver/install/ipa_cacert_manage.py @@ -556,7 +556,7 @@ class CACertManage(admintool.AdminTool): api.env.realm, False) - now = datetime.datetime.utcnow() + now = datetime.datetime.now(tz=datetime.UTC) for ca_cert, ca_nickname, _ca_trust_flags in ca_certs: if ca_cert.not_valid_after < now: expired_certs.append(ca_nickname) diff --git a/ipatests/create_external_ca.py b/ipatests/create_external_ca.py index 7d14fdcf2..7c63157d1 100644 --- a/ipatests/create_external_ca.py +++ b/ipatests/create_external_ca.py @@ -35,7 +35,7 @@ class ExternalCA: """ def __init__(self, days=365, key_size=None): - self.now = datetime.datetime.utcnow() + self.now = datetime.datetime.now(tz=datetime.UTC) self.delta = datetime.timedelta(days=days) self.ca_key = None self.ca_public_key = None diff --git a/ipatests/pytest_ipa/integration/create_caless_pki.py b/ipatests/pytest_ipa/integration/create_caless_pki.py index a9778250b..cb8abd092 100644 --- a/ipatests/pytest_ipa/integration/create_caless_pki.py +++ b/ipatests/pytest_ipa/integration/create_caless_pki.py @@ -102,7 +102,7 @@ class KRB5PrincipalName(univ.Sequence): def profile_ca(builder, ca_nick, ca): - now = datetime.datetime.utcnow() + now = datetime.datetime.now(tz=datetime.UTC) builder = builder.not_valid_before(now) builder = builder.not_valid_after(now + 10 * YEAR) @@ -174,7 +174,7 @@ def profile_ca(builder, ca_nick, ca): def profile_server(builder, ca_nick, ca, warp=datetime.timedelta(days=0), dns_name=None, badusage=False, wildcard=False): - now = datetime.datetime.utcnow() + warp + now = datetime.datetime.now(tz=datetime.UTC) + warp builder = builder.not_valid_before(now) builder = builder.not_valid_after(now + YEAR) @@ -231,7 +231,7 @@ def profile_server(builder, ca_nick, ca, def profile_kdc(builder, ca_nick, ca, warp=datetime.timedelta(days=0), dns_name=None, badusage=False): - now = datetime.datetime.utcnow() + warp + now = datetime.datetime.now(tz=datetime.UTC) + warp builder = builder.not_valid_before(now) builder = builder.not_valid_after(now + YEAR) @@ -347,7 +347,7 @@ def gen_cert(profile, nick_base, subject, ca=None, **kwargs): def revoke_cert(ca, serial): - now = datetime.datetime.utcnow() + now = datetime.datetime.now(tz=datetime.UTC) crl_builder = x509.CertificateRevocationListBuilder() crl_builder = crl_builder.issuer_name(ca.cert.subject) diff --git a/ipatests/test_integration/test_epn.py b/ipatests/test_integration/test_epn.py index 33ae2ad12..74ffd5a49 100644 --- a/ipatests/test_integration/test_epn.py +++ b/ipatests/test_integration/test_epn.py @@ -467,7 +467,8 @@ class TestEPN(IntegrationTest): extra_args=[ "--password-expiration", datetime_to_generalized_time( - datetime.datetime.utcnow() + datetime.timedelta(days=7) + datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta( + days=7) ), ], ) @@ -495,7 +496,8 @@ class TestEPN(IntegrationTest): uid=uid, days=i, krbpasswordexpiration=datetime_to_generalized_time( - datetime.datetime.utcnow() + datetime.timedelta(days=i) + datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta( + days=i) ), ) @@ -810,7 +812,8 @@ class TestEPN(IntegrationTest): self.master.run_command( ['ipa', 'user-mod', 'admin', '--password-expiration', datetime_to_generalized_time( - datetime.datetime.utcnow() + datetime.timedelta(days=7) + datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta( + days=7) )] ) (unused, stderr_text, _unused) = self._check_epn_output( diff --git a/ipatests/test_integration/test_ipahealthcheck.py b/ipatests/test_integration/test_ipahealthcheck.py index c26f8cd7e..d1a86c814 100644 --- a/ipatests/test_integration/test_ipahealthcheck.py +++ b/ipatests/test_integration/test_ipahealthcheck.py @@ -8,7 +8,7 @@ Tests to verify that the ipa-healthcheck scenarios from __future__ import absolute_import from configparser import RawConfigParser, NoOptionError -from datetime import datetime, timedelta +from datetime import datetime, timedelta, UTC import json import os import re @@ -1547,7 +1547,7 @@ class TestIpaHealthCheck(IntegrationTest): tasks.uninstall_replica(self.master, self.replicas[0]) # Store the current date to restore at the end of the test - now = datetime.utcnow() + now = datetime.now(tz=UTC) now_str = datetime.strftime(now, "%Y-%m-%d %H:%M:%S Z") # Pick a cert to find the upcoming expiration diff --git a/ipatests/test_ipalib/test_x509.py b/ipatests/test_ipalib/test_x509.py index 619dfd096..f2621875a 100644 --- a/ipatests/test_ipalib/test_x509.py +++ b/ipatests/test_ipalib/test_x509.py @@ -234,8 +234,8 @@ class test_x509: # Verify certificate contents. This exercises python-cryptography # more than anything but confirms our usage of it. - not_before = datetime.datetime(2010, 6, 25, 13, 0, 42) - not_after = datetime.datetime(2015, 6, 25, 13, 0, 42) + not_before = datetime.datetime(2010, 6, 25, 13, 0, 42, 0, datetime.UTC) + not_after = datetime.datetime(2015, 6, 25, 13, 0, 42, 0, datetime.UTC) cert = x509.load_pem_x509_certificate(goodcert_headers) assert DN(cert.subject) == DN(('CN', 'ipa.example.com'), ('O', 'IPA')) @@ -279,8 +279,8 @@ class test_x509: assert DN(cert.issuer) == DN( "CN=Let's Encrypt Authority X3,O=Let's Encrypt,C=US") assert cert.serial_number == 0x03ad42a2a5ada59a131327cb0979623cb605 - not_before = datetime.datetime(2018, 7, 25, 5, 36, 59) - not_after = datetime.datetime(2018, 10, 23, 5, 36, 59) + not_before = datetime.datetime(2018, 7, 25, 5, 36, 59, 0, datetime.UTC) + not_after = datetime.datetime(2018, 10, 23, 5, 36, 59, 0, datetime.UTC) assert cert.not_valid_before == not_before assert cert.not_valid_after == not_after assert cert.san_general_names == [DNSName('ipa.demo1.freeipa.org')] diff --git a/ipatests/test_ipapython/test_cookie.py b/ipatests/test_ipapython/test_cookie.py index 89afeb0df..218bd1c1a 100644 --- a/ipatests/test_ipapython/test_cookie.py +++ b/ipatests/test_ipapython/test_cookie.py @@ -402,7 +402,7 @@ class TestHTTPReturn: assert cookie.http_return_ok(self.url) def test_expires(self): - now = datetime.datetime.utcnow().replace(microsecond=0) + now = datetime.datetime.now(tz=datetime.UTC).replace(microsecond=0) # expires 1 day from now expires = now + datetime.timedelta(days=1) diff --git a/ipatests/test_webui/crypto_utils.py b/ipatests/test_webui/crypto_utils.py index 2a03473f9..a761c12c2 100644 --- a/ipatests/test_webui/crypto_utils.py +++ b/ipatests/test_webui/crypto_utils.py @@ -2,7 +2,7 @@ # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # -from datetime import datetime, timedelta +from datetime import datetime, timedelta, UTC from cryptography import x509 from cryptography.hazmat.backends import default_backend @@ -63,9 +63,9 @@ def generate_certificate(hostname): ).serial_number( x509.random_serial_number() ).not_valid_before( - datetime.utcnow() + datetime.now(tz=UTC) ).not_valid_after( - datetime.utcnow() + timedelta(days=100) + datetime.now(tz=UTC) + timedelta(days=100) ).add_extension( x509.SubjectAlternativeName([x509.DNSName(hostname)]), critical=False