a }|gnF@sBdZddlZddlmZddlZddlmZddlZddl Z ddl Z ddl Z ddl m Z ddl Z ddlZddlZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlZddlmZddlmZddlmZddlm Z ddl!Z"ddl#m$Z$ddl%m&Z&ddl%m'Z'ddl(m)Z)ddl(m*Z*ddl(m+Z+ddl,m-Z.ddl/m0Z0ddl/m1Z1ddl2m'Z3ddl4m5Z5Gddde5j6Z7e8e8ddd Z9e8e:dd!d"Z;e8edd&d'Z?e8e$j@dd(d)ZAe8e"jBdd*d+ZCe8e"jDdd,d-ZEe8e$jFdd.d/ZGdTe8e8eHe8d1d2d3ZIejJd4d5d6ZKdUeeejJd7d8d9ZLGd:d;d;ZMeMd4dd?ZOeedd@dAdBZPGdCdDdDejQZRGdEdFdFeRZSe jTe jTe8ddGdHdIZUegefe8ddJdKdLZVe8eedMefgedMeffdNdOdPZWe8e8dQdRdSZXdS)VzTest utilities.N) ExitStack)reload) synchronize)Any)Callable)cast)IO)Iterable)List)Optional)Union)mock)default_backend) serialization) RSAPrivateKey)crypto) configuration)util) constants)lock)storage)obj) filesystem)os)commonc@seZdZdZeedddZeeeeeddddZdeeee e eefdd d d Z e edd d Z deee ddddZddddZddddZeedddddZddddZedddZdS) DummyInstallerz(Dummy installer plugin for test purpose.returncCsgSNselfrr6/usr/lib/python3.9/site-packages/certbot/tests/util.py get_all_names-szDummyInstaller.get_all_namesN)domain cert_pathkey_path chain_pathfullchain_pathrcCsdSrr)r!r$r%r&r'r(rrr" deploy_cert0szDummyInstaller.deploy_cert)r$ enhancementoptionsrcCsdSrr)r!r$r*r+rrr"enhance4szDummyInstaller.enhancecCsgSrrr rrr"supported_enhancements8sz%DummyInstaller.supported_enhancementsF)title temporaryrcCsdSrr)r!r.r/rrr"save;szDummyInstaller.savecCsdSrrr rrr" config_test>szDummyInstaller.config_testcCsdSrrr rrr"restartAszDummyInstaller.restart).N)addrcCsdSrr)clsr3rrr"add_parser_argumentsDsz#DummyInstaller.add_parser_argumentscCsdSrrr rrr"prepareHszDummyInstaller.preparecCsdS)Nrr rrr" more_infoKszDummyInstaller.more_info)N)NF)__name__ __module__ __qualname____doc__r strr#r)r r r r,r-boolr0r1r2 classmethodrr5r6r8rrrr"r+s"  r)namesrcGsFt}t|jtjtjdg|R}| tj |}t |S)zPath to a test vector.testdata) ratexitregisterclose importlib resourcesfiles __package__joinpath enter_contextZas_filer=)r@Z _file_manager vector_refpathrrr" vector_pathOs  rMcGsTtjtjdg|R}|}z|ddWSt yN|YS0dS)zLoad contents of a test vector.rAz  N) rErFrGrHrI read_bytesdecodereplaceencode ValueError)r@rKdatarrr" load_vectorXs  rU)filename loader_pem loader_derrcCs<tj|\}}|dkr |S|dkr0|StddS)Nz.pemz.derz1Loader could not be recognized based on extension)rrLsplitextlowerrS)rVrWrX_extrrr" _guess_loaderes   r]cGs$t|dtjtj}t|t|S)zLoad certificate.)r]r FILETYPE_PEM FILETYPE_ASN1Zload_certificaterUr@loaderrrr" load_certnsrccGs$t|dtjtj}t|t|S)zLoad certificate request.r^)r]rr_r`Zload_certificate_requestrUrarrr"load_csrusrdcGstt|S)z(Load ComparableX509 certificate request.)joseComparableX509rd)r@rrr"load_comparable_csr|srgc GsLt|dtjtj}|tjkr&tj}ntj}tt t |t |dt dS)zLoad RSA private key.r^N)passwordZbackend) r]rr_r`rZload_pem_private_keyZload_der_private_keyreComparableRSAKeyrrrUr)r@rbZ loader_fnrrr"load_rsa_private_keys rjcGs$t|dtjtj}t|t|S)zLoad pyOpenSSL private key.r^)r]rr_r`Zload_privatekeyrUrarrr"load_pyopenssl_private_keysrkT) config_dirtestfileecrc sp|dtd }tjtj}tjtj|}tjtj|}|||fD]}tj|sPt |qPt d |rzdnd}t |D]$} ttj|| tj|| qtjD]0} ttj|d | tj|d | qtj||} tt |T} t| d(} | fd d | DWdn1sB0YWdn1sb0Y| S) aCreates a lineage defined by testfile. This creates the archive, live, and renewal directories if necessary and creates a simple lineage. :param str config_dir: path to the configuration directory :param str testfile: configuration file to base the lineage on :param bool ec: True if we generate the lineage with an ECDSA key :returns: path to the renewal conf file for the created lineage :rtype: str Nz.confzsample-archive{}z-ecr7z{0}1.pemz{0}.pemwc3s|]}|dVqdS)ZMAGICDIRN)rQ).0linerlrr" szmake_lineage..)lenrrLjoinrZRENEWAL_CONFIGS_DIRZ ARCHIVE_DIRZLIVE_DIRexistsrmakedirsrMformatlistdirshutilcopyfilerZALL_FOURsymlinkopen writelines) rlrmrnZ lineage_nameZconf_dir archive_dirZlive_dirZ directoryZsample_archivekindZ conf_pathsrcdstrrrr" make_lineages:     HrrcCsttjtjdtdS)aDPatch certbot.display.util to use a special mock display utility. The mock display utility works like a regular mock object, except it also also asserts that methods are called with valid arguments. The mock created by this patch mocks out Certbot internals. That is, the mock object will be called by the certbot.display.util functions and the mock returned by that call will be used as the display utility. This was done to simplify the transition from zope.component and mocking certbot.display.util functions directly in test code should be preferred over using this function in the future. See https://github.com/certbot/certbot/issues/8948 :returns: patch on the function used internally by certbot.display.util to get a display utility instance :rtype: mock.MagicMock )certbot._internal.display.obj.get_display)Z new_callable)rr MagicMockpatch_create_display_util_mockrrrr"patch_display_utils r)stdoutrcCs*|r|nt}ttjtjdt|dS)aPatch certbot.display.util to use a special mock display utility. The mock display utility works like a regular mock object, except it also asserts that methods are called with valid arguments. The mock created by this patch mocks out Certbot internals. That is, the mock object will be called by the certbot.display.util functions and the mock returned by that call will be used as the display utility. This was done to simplify the transition from zope.component and mocking certbot.display.util functions directly in test code should be preferred over using this function in the future. See https://github.com/certbot/certbot/issues/8948 The `message` argument passed to the display utility methods is passed to stdout's write method. :param object stdout: object to write standard output to; it is expected to have a `write` method :returns: patch on the function used internally by certbot.display.util to get a display utility instance :rtype: mock.MagicMock r)new)ioStringIOrr rr%_create_display_util_mock_with_stdoutrrrr"patch_display_util_with_stdouts rc@seZdZdZddejjfeee de fe ddddZ ddd d Z e e ej d d d Zee dddZee ddddZdS) FreezableMockaMock object with the ability to freeze attributes. This class works like a regular mock.MagicMock object, except attributes and behavior set before the object is frozen cannot be changed during tests. If a func argument is provided to the constructor, this function is called first when an instance of FreezableMock is called, followed by the usual behavior defined by MagicMock. The return value of func is ignored. FN.)frozenfunc return_valuercCs>|r tndh|_||_t|_|tjjkr4||_||_ dS)Nfreeze) set _frozen_set_funcr r_mocksentinelDEFAULTr_frozen)r!rrrrrr"__init__s   zFreezableMock.__init__rcCs d|_dS)z)Freeze object preventing further changes.TN)rr rrr"rszFreezableMock.freezeargskwargsrcOs*|jdur|j|i||j|i|Sr)rr)r!rrrrr"__call__s zFreezableMock.__call__)namercCs||dkr.zt||WSty*YdS0nJ|dvrHtt|d|S|dksZ||jvrft||Stt|d|SdS)NrFrZ side_effectrr)object__getattribute__AttributeErrorgetattrr)r!rrrr"rs   zFreezableMock.__getattribute__)rvaluercCsb|jr*||jvrtd|t|j||S|dkr>|j||dvrTt|j||St|||S)a Before it is frozen, attributes are set on the FreezableMock instance and added to the _frozen_set. Attributes in the _frozen_set cannot be changed after the FreezableMock is frozen. In this case, they are set on the underlying _mock. In cases of return_value and side_effect, these attributes are always passed through to the instance's _mock and added to the _frozen_set before the object is frozen. zCannot change frozen attribute rr)rrrsetattrrr3r __setattr__)r!rrrrr"r&s    zFreezableMock.__setattr__)r9r:r;r<r rrr>r rrrrrrr=rrrrrr"rs   rcCsXt}ddttjD}|D]$}|dkrtdtd}t|||q|td|dS)NcSs*g|]"}tttj|r|ds|qS__callabler display_obj FileDisplay startswithrprrrr" Bs z-_create_display_util_mock.. notificationTrrrr)rdirrr_assert_valid_callrr)display method_listmethod frozen_mockrrr"r?s rcstttddfdd ttddfdd }t}ddttjD}|D]2}|d krftd d }n td |d }t|||qL|td |d S) N)message unused_args unused_kwargsrcs|r|dS)z$Write to message to stdout. N)write)rrrrrr" _write_msgNsz9_create_display_util_mock_with_stdout.._write_msgrcst|||i|dS)z< Mock function for display utility methods. N)r)rr)rrr" mock_methodTs z:_create_display_util_mock_with_stdout..mock_methodcSs*g|]"}tttj|r|ds|qSrrrrrr"r]s z9_create_display_util_mock_with_stdout..rTrr)r=rrrrrrr)rrrrrrr)rrr"rMsrrcOsN|r |dn|dg}|dd|dd|ddd}tj|i|dS)Nrrdefaultcli_flagforce_interactiveF)rrr)get display_utilZassert_valid_call)rrZ assert_argsZ assert_kwargsrrr"rls    rc@s,eZdZdZddddZddddZdS)TempDirTestCasezBBase test class which sets up and tears down a temporary directoryNrcCst|_dS)zExecute before testN)tempfileZmkdtemptempdirr rrr"setUp{szTempDirTestCase.setUpcCs*tgt_tt|jdS)zExecute after testN) loggingZshutdownZ getLoggerhandlersrZ_release_locksrzrmtreerr rrr"tearDowns zTempDirTestCase.tearDown)r9r:r;r<rrrrrr"rxsrcs&eZdZdZddfdd ZZS)ConfigTestCasez2Test class which sets up a NamespaceConfig object.Nrcstttjfittj |_ |j id|j j _ tj|jd|j j _tj|jd|j j _tj|jd|j j _tj d|j j _tj d|j j _tj d|j j _d|j j _dS)NZcertonlyconfigZworkZlogsZauth_cert_pathZauth_chain_pathzhttps://example.com)superrrZNamespaceConfigr rcopydeepcopyrZ CLI_DEFAULTSrZset_argument_sources namespaceZverbrrLrurrlZwork_dirZlogs_dirr%r(r'Zserverr  __class__rr"rs   zConfigTestCase.setUp)r9r:r;r<r __classcell__rrrr"rsr)event_in event_outrLrcCsFtj|rt|}n t|}z|W|n |0dS)a Acquire a file lock on given path, then wait to release it. This worker is coordinated using events to signal when the lock should be acquired and released. :param multiprocessing.Event event_in: event object to signal when to release the lock :param multiprocessing.Event event_out: event object to signal when the lock is acquired :param path: the path to lock N)rrLisdirrZlock_dirZLockFilerrelease)rrrLZmy_lockrrr" _handle_locks   r)callback path_to_lockrcCsRttt}t}tjt|||fd}||||jdddS)z Grab a lock on path_to_lock from a foreign process then execute the callback. :param callable callback: object to call after acquiring the lock :param str path_to_lock: path to file or directory to lock )targetr )timeoutN) reload_modulermultiprocessingEventZProcessrstartrru)rrZ emit_eventZ receive_eventZprocessrrr" lock_and_calls r.)reasonrcs(tdtftdtfdfdd }|S)zFDecorator to skip permanently a test on Windows. A reason is required..)functionrcsttjdk|S)zWrapped versionwin32)unittestZskipIfsysplatform)rrrr"wrappersz skip_on_windows..wrapper)rr)rrrrr"skip_on_windowss$r)rLrcCstjt|S)z Return the given path joined to the tempdir path for the current platform Eg.: 'cert' => /tmp/cert (Linux) or 'C:\Users\currentuser\AppData\Temp\cert' (Windows) )rrLrurZ gettempdir)rLrrr" temp_joinsr)T)N)Yr<rB contextlibrrrErrZimportlib.resourcesrrrrrzrrtypingrrrrr r r r rr Zcryptography.hazmat.backendsrZcryptography.hazmat.primitivesrZ-cryptography.hazmat.primitives.asymmetric.rsarZjosepyreZOpenSSLrZcertbotrrZcertbot._internalrrrZcertbot._internal.displayrrZcertbot.compatrrZcertbot.displayrZcertbot.pluginsrZ Installerrr=rMbytesrUintr]ZX509rcZX509ReqrdrfrgrirjZPKeyrkr>rrrrrrrrZTestCaserrrrrrrrrrr"s|                          $    - E *