id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
16,300
create_external_ca.py
freeipa_freeipa/ipatests/create_external_ca.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import, print_function import argparse from cryptography import x509 from cryptography.x509.oid import NameOID from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization import datetime ISSUER_CN = 'example.test' class ExternalCA: """Provide external CA for testing """ def __init__(self, days=365, key_size=None): self.now = datetime.datetime.now(tz=datetime.timezone.utc) self.delta = datetime.timedelta(days=days) self.ca_key = None self.ca_public_key = None self.issuer = None self.key_size = key_size or 2048 def create_ca_key(self): """Create private and public key for CA Note: The test still creates 2048 although IPA CA uses 3072 bit RSA by default. This also tests that IPA supports an external signing CA with weaker keys than the IPA base CA. """ self.ca_key = rsa.generate_private_key( public_exponent=65537, key_size=self.key_size, backend=default_backend(), ) self.ca_public_key = self.ca_key.public_key() def sign(self, builder): return builder.sign( private_key=self.ca_key, algorithm=hashes.SHA256(), backend=default_backend(), ) def create_ca(self, cn=ISSUER_CN, path_length=None, extensions=()): """Create root CA. :returns: bytes -- Root CA in PEM format. """ if self.ca_key is None: self.create_ca_key() subject = self.issuer = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, str(cn)), ]) builder = x509.CertificateBuilder() builder = builder.subject_name(subject) builder = builder.issuer_name(self.issuer) builder = builder.public_key(self.ca_public_key) builder = builder.serial_number(x509.random_serial_number()) builder = builder.not_valid_before(self.now) builder = builder.not_valid_after(self.now + self.delta) builder = builder.add_extension( x509.KeyUsage( digital_signature=False, content_commitment=False, key_encipherment=False, data_encipherment=False, key_agreement=False, key_cert_sign=True, crl_sign=True, encipher_only=False, decipher_only=False, ), critical=True, ) builder = builder.add_extension( x509.BasicConstraints(ca=True, path_length=path_length), critical=True, ) builder = builder.add_extension( x509.SubjectKeyIdentifier.from_public_key(self.ca_public_key), critical=False, ) builder = builder.add_extension( x509.AuthorityKeyIdentifier.from_issuer_public_key( self.ca_public_key ), critical=False, ) for extension in extensions: builder = builder.add_extension(extension, critical=False) cert = builder.sign(self.ca_key, hashes.SHA256(), default_backend()) return cert.public_bytes(serialization.Encoding.PEM) def sign_csr(self, ipa_csr, path_length=1): """Sign certificate CSR. :param ipa_csr: CSR in PEM format. :type ipa_csr: bytes. :returns: bytes -- Signed CA in PEM format. """ csr_tbs = x509.load_pem_x509_csr(ipa_csr, default_backend()) csr_public_key = csr_tbs.public_key() csr_subject = csr_tbs.subject builder = x509.CertificateBuilder() builder = builder.public_key(csr_public_key) builder = builder.subject_name(csr_subject) builder = builder.serial_number(x509.random_serial_number()) builder = builder.issuer_name(self.issuer) builder = builder.not_valid_before(self.now) builder = builder.not_valid_after(self.now + self.delta) builder = builder.add_extension( x509.KeyUsage( digital_signature=False, content_commitment=False, key_encipherment=False, data_encipherment=False, key_agreement=False, key_cert_sign=True, crl_sign=True, encipher_only=False, decipher_only=False, ), critical=True, ) builder = builder.add_extension( x509.SubjectKeyIdentifier.from_public_key(csr_public_key), critical=False, ) builder = builder.add_extension( x509.AuthorityKeyIdentifier.from_issuer_public_key( self.ca_public_key ), critical=False, ) builder = builder.add_extension( x509.BasicConstraints(ca=True, path_length=path_length), critical=True, ) cert = self.sign(builder) return cert.public_bytes(serialization.Encoding.PEM) def main(): IPA_CSR = '/root/ipa.csr' ROOT_CA = '/tmp/rootca.pem' IPA_CA = '/tmp/ipaca.pem' parser = argparse.ArgumentParser("Create external CA") parser.add_argument( '--csr', type=argparse.FileType('rb'), default=IPA_CSR, help="Path to ipa.csr (default: {})".format(IPA_CSR) ) parser.add_argument( '--rootca', type=argparse.FileType('wb'), default=ROOT_CA, help="New root CA file (default: {})".format(ROOT_CA) ) parser.add_argument( '--ipaca', type=argparse.FileType('wb'), default=IPA_CA, help="New IPA CA file (default: {})".format(ROOT_CA) ) args = parser.parse_args() with args.csr as f: ipa_csr = f.read() external_ca = ExternalCA() root_ca = external_ca.create_ca() ipa_ca = external_ca.sign_csr(ipa_csr) with args.rootca as f: f.write(root_ca) with args.ipaca as f: f.write(ipa_ca) o = "ipa-server-install --external-cert-file={} --external-cert-file={}" print(o.format(args.rootca.name, args.ipaca.name)) if __name__ == '__main__': main()
7,061
Python
.py
179
30.513966
76
0.625548
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,301
i18n.py
freeipa_freeipa/ipatests/i18n.py
# Authors: # John Dennis <jdennis@redhat.com> # # Copyright (C) 2010 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from __future__ import print_function # WARNING: Do not import ipa modules, this is also used as a # stand-alone script (invoked from po Makefile). import optparse # pylint: disable=deprecated-module import sys import gettext import re import os import traceback import polib from collections import namedtuple import six ''' We test our translations by taking the original untranslated string (e.g. msgid) and prepend a prefix character and then append a suffix character. The test consists of asserting that the first character in the translated string is the prefix, the last character in the translated string is the suffix and the everything between the first and last character exactly matches the original msgid. We use unicode characters not in the ascii character set for the prefix and suffix to enhance the test. To make reading the translated string easier the prefix is the unicode right pointing arrow and the suffix left pointing arrow, thus the translated string looks like the original string enclosed in arrows. In ASCII art the string "foo" would render as: -->foo<-- ''' #------------------------------------------------------------------------------- verbose = False print_traceback = False pedantic = False show_strings = True # Unicode right pointing arrow prefix = u'\u2192' # utf-8 == '\xe2\x86\x92' # Unicode left pointing arrow suffix = u'\u2190' # utf-8 == '\xe2\x86\x90' page_width = 80 section_seperator = '=' * page_width entry_seperator = '-' * page_width # Python 3: Enforce ASCII mode so \w matches only ASCII chars. This avoids # false positives in Chinese translation. ASCII = getattr(re, "ASCII", 0) # -------------------------------------------------------------------------- # For efficiency compile these regexps just once _substitution_regexps = [ re.compile(r'%[srduoxf]'), # e.g. %s re.compile(r'%\(\w+\)[srduoxf]', ASCII), # e.g. %(foo)s re.compile(r'\$\w+', ASCII), # e.g. $foo re.compile(r'\${\w+}', ASCII), # e.g. ${foo} re.compile(r'\$\(\w+\)', ASCII) # e.g. $(foo) ] # Python style substitution, e.g. %(foo)s # where foo is the key and s is the format char # group 1: whitespace between % and ( # group 2: whitespace between ( and key # group 3: whitespace between key and ) # group 4: whitespace between ) and format char # group 5: format char _python_substitution_regexp = re.compile( r'%(\s*)\((\s*)\w+(\s*)\)(\s*)([srduoxf])?', ASCII ) # Shell style substitution, e.g. $foo $(foo) ${foo} # where foo is the variable _shell_substitution_regexp = re.compile( r'\$(\s*)([({]?)(\s*)\w+(\s*)([)}]?)', ASCII ) # group 1: whitespace between $ and delimiter # group 2: begining delimiter # group 3: whitespace between beginning delmiter and variable # group 4: whitespace between variable and ending delimiter # group 5: ending delimiter printf_fmt_re = re.compile( r"%" # start r"(\d+\$)?" # fmt_arg (group 1) r"(([#0 +'I]|-(?!\d))*)" # flags (group 2) r"(([+-]?([1-9][0-9]*)?)|(\*|\*\d+\$))?" # width (group 4) r"(\.((-?\d*)|(\*|)|(\*\d+\$)))?" # precision (group 8) r"(h|hh|l|ll|L|j|z|t)?" # length (group 13) r"([diouxXeEfFgGaAcspnm%])") # conversion (group 14) #------------------------------------------------------------------------------- def get_prog_langs(entry): ''' Given an entry in a pot or po file return a set of the programming languges it was found in. It needs to be a set because the same msgid may appear in more than one file which may be in different programming languages. Note: One might think you could use the c-format etc. flags to attached to entry to make this determination, but you can't. Those flags refer to the style of the string not the programming language it came from. Also the flags are often omitted and/or are inaccurate. For now we just look at the file extension. If we knew the path to the file we could use other heuristics such as looking for the shbang interpreter string. The set of possible language types witch might be returned are: * c * python ''' result = set() for location in entry.occurrences: filename = location[0] ext = os.path.splitext(filename)[1] if ext in ('.c', '.h', '.cxx', '.cpp', '.hxx'): result.add('c') elif ext in ('.py'): result.add('python') return result def parse_printf_fmt(s): ''' Parse a printf style format string and return a list of format conversions found in the string. Each conversion specification is introduced by the character %, and ends with a conversion specifier. In between there may be (in this order) zero or more flags, an optional minimum field width, an optional precision and an optional length modifier. See "man 3 printf" for details. Each item in the returned list is a dict whose keys are the sub-parts of a conversion specification. The key and values are: fmt The entire format conversion specification fmt_arg The positional index of the matching argument in the argument list, e.g. %1$ indicates the first argument in the argument will be read for this conversion, excludes the leading % but includes the trailing $, 1$ is the fmt_arg in %1$. flags The flag characaters, e.g. 0 is the flag in %08d width The width field, e.g. 20 is the width in %20s precision The precisioin field, e.g. .2 is the precision in %8.2f length The length modifier field, e.g. l is the length modifier in %ld conversion The conversion specifier character, e.g. d is the conversion specification character in %ld If the part is not found in the format it's value will be None. ''' result = [] # get list of all matches, but skip escaped % matches = [x for x in printf_fmt_re.finditer(s) if x.group(0) != "%%"] # build dict of each sub-part of the format, append to result for match in matches: parts = {} parts['fmt'] = match.group(0) parts['fmt_arg'] = match.group(1) parts['flags'] = match.group(2) or None parts['width'] = match.group(4) or None parts['precision'] = match.group(8) parts['length'] = match.group(13) parts['conversion'] = match.group(14) result.append(parts) return result def validate_substitutions_match(s1, s2, s1_name='string1', s2_name='string2'): ''' Validate both s1 and s2 have the same number of substitution strings. A substitution string would be something that looked like this: * %(foo)s * $foo * ${foo} * $(foo) The substitutions may appear in any order in s1 and s2, however their format must match exactly and the exact same number of each must exist in both s1 and s2. A list of error diagnostics is returned explaining how s1 and s2 failed the validation check. If the returned error list is empty then the validation succeeded. :param s1: First string to validate :param s2: First string to validate :param s1_name: In diagnostic messages the name for s1 :param s2_name: In diagnostic messages the name for s2 :return: List of diagnostic error messages, if empty then success ''' errors = [] def get_subs(s): ''' Return a dict whoses keys are each unique substitution and whose value is the count of how many times that substitution appeared. ''' subs = {} for regexp in _substitution_regexps: for match in regexp.finditer(s): matched = match.group(0) subs[matched] = subs.get(matched, 0) + 1 return subs # Get the substitutions and their occurance counts subs1 = get_subs(s1) subs2 = get_subs(s2) # Form a set for each strings substitutions and # do set subtraction and interesection set1 = set(subs1.keys()) set2 = set(subs2.keys()) missing1 = set2 - set1 missing2 = set1 - set2 common = set1 & set2 # Test for substitutions which are absent in either string if missing1: errors.append("The following substitutions are absent in %s: %s" % (s1_name, ' '.join(missing1))) if missing2: errors.append("The following substitutions are absent in %s: %s" % (s2_name, ' '.join(missing2))) if pedantic: # For the substitutions which are shared assure they occur an equal number of times for sub in common: if subs1[sub] != subs2[sub]: errors.append("unequal occurances of '%s', %s has %d occurances, %s has %d occurances" % (sub, s1_name, subs1[sub], s2_name, subs2[sub])) if errors: if show_strings: errors.append('>>> %s <<<' % s1_name) errors.append(s1.rstrip()) errors.append('>>> %s <<<' % s2_name) errors.append(s2.rstrip()) return errors def validate_substitution_syntax(s, s_name='string'): ''' If s has one or more substitution variables then validate they are syntactically correct. A substitution string would be something that looked like this: * %(foo)s * $foo * ${foo} * $(foo) A list of error diagnostics is returned explaining how s1 and s2 failed the validation check. If the returned error list is empty then the validation succeeded. :param s: String to validate :param s_name: In diagnostic messages the name for s :return: List of diagnostic error messages, if empty then success ''' errors = [] # Look for Python style substitutions, e.g. %(foo)s for match in _python_substitution_regexp.finditer(s): if match.group(1): errors.append("%s has whitespace between %% and key in '%s'" % (s_name, match.group(0))) if match.group(2) or match.group(3): errors.append("%s has whitespace next to key in '%s'" % (s_name, match.group(0))) if match.group(4): errors.append("%s has whitespace between key and format character in '%s'" % (s_name, match.group(0))) if not match.group(5): errors.append("%s has no format character in '%s'" % (s_name, match.group(0))) # Look for shell style substitutions, e.g. $foo $(foo) ${foo} for match in _shell_substitution_regexp.finditer(s): if match.group(1): errors.append("%s has whitespace between $ and variable in '%s'" % (s_name, match.group(0))) if match.group(3) or (match.group(4) and match.group(5)): errors.append("%s has whitespace next to variable in '%s'" % (s_name, match.group(0))) beg_delimiter = match.group(2) end_delimiter = match.group(5) matched_delimiters = {'': '', '(': ')', '{': '}'} if beg_delimiter is not None or end_delimiter is not None: if matched_delimiters[beg_delimiter] != end_delimiter: errors.append("%s variable delimiters do not match in '%s', begin delimiter='%s' end delimiter='%s'" % (s_name, match.group(0), beg_delimiter, end_delimiter)) if errors: if show_strings: errors.append('>>> %s <<<' % s_name) errors.append(s.rstrip()) return errors def validate_positional_substitutions(s, prog_langs, s_name='string'): ''' We do not permit multiple positional substitutions in translation strings (e.g. '%s') because they do not allow translators to reorder the wording. Instead keyword substitutions should be used when there are more than one. ''' errors = [] fmts = parse_printf_fmt(s) n_fmts = len(fmts) errors = [] if n_fmts > 1: for fmt_parts in fmts: fmt = fmt_parts['fmt'] fmt_arg = fmt_parts['fmt_arg'] width = fmt_parts['width'] if width == '*': errors.append("Error: * width arg in format '%s should be indexed" % fmt) if fmt_arg is None: if 'c' in prog_langs: errors.append("%s format '%s' is positional, should use indexed argument" % (s_name, fmt)) else: errors.append("%s format '%s' is positional, should use keyword substitution" % (s_name, fmt)) if errors: if show_strings: errors.append('>>> %s <<<' % s_name) errors.append(s.rstrip()) return errors def validate_file(file_path, validation_mode, reference_pot=None): ''' Given a pot or po file scan all it's entries looking for problems with variable substitutions. See the following functions for details on how the validation is performed. * validate_substitutions_match() * validate_substitution_syntax() * validate_positional_substitutions() Returns the number of entries with errors. For po files, ``reference_pot`` gives a pot file to merge with (to recover comments and file locations) ''' def emit_messages(): if n_warnings: warning_lines.insert(0, section_seperator) warning_lines.insert(1, "%d validation warnings in %s" % (n_warnings, file_path)) print('\n'.join(warning_lines)) if n_errors: error_lines.insert(0, section_seperator) error_lines.insert(1, "%d validation errors in %s" % (n_errors, file_path)) print('\n'.join(error_lines)) Result = namedtuple('ValidateFileResult', ['n_entries', 'n_msgids', 'n_msgstrs', 'n_warnings', 'n_errors']) warning_lines = [] error_lines = [] n_entries = 0 n_msgids = 0 n_msgstrs = 0 n_entries = 0 n_warnings = 0 n_errors = 0 n_plural_forms = 0 if not os.path.isfile(file_path): error_lines.append(entry_seperator) error_lines.append('file does not exist "%s"' % (file_path)) n_errors += 1 emit_messages() return Result(n_entries=n_entries, n_msgids=n_msgids, n_msgstrs=n_msgstrs, n_warnings=n_warnings, n_errors=n_errors) try: po = polib.pofile(file_path) except Exception as e: error_lines.append(entry_seperator) error_lines.append('Unable to parse file "%s": %s' % (file_path, e)) n_errors += 1 emit_messages() return Result(n_entries=n_entries, n_msgids=n_msgids, n_msgstrs=n_msgstrs, n_warnings=n_warnings, n_errors=n_errors) if validation_mode == 'po' and reference_pot: # Merge the .pot file for comments and file locations po.merge(reference_pot) if validation_mode == 'po': plural_forms = po.metadata.get('Plural-Forms') if not plural_forms: error_lines.append(entry_seperator) error_lines.append("%s: does not have Plural-Forms header" % file_path) n_errors += 1 match = re.search(r'\bnplurals\s*=\s*(\d+)', plural_forms) if match: n_plural_forms = int(match.group(1)) else: error_lines.append(entry_seperator) error_lines.append("%s: does not specify integer nplurals in Plural-Forms header" % file_path) n_errors += 1 n_entries = len(po) for entry in po: entry_warnings = [] entry_errors = [] have_msgid = entry.msgid.strip() != '' have_msgid_plural = entry.msgid_plural.strip() != '' have_msgstr = entry.msgstr.strip() != '' if have_msgid: n_msgids += 1 if have_msgid_plural: n_msgids += 1 if have_msgstr: n_msgstrs += 1 if validation_mode == 'pot': prog_langs = get_prog_langs(entry) if have_msgid: errors = validate_positional_substitutions(entry.msgid, prog_langs, 'msgid') entry_errors.extend(errors) if have_msgid_plural: errors = validate_positional_substitutions(entry.msgid_plural, prog_langs, 'msgid_plural') entry_errors.extend(errors) elif validation_mode == 'po': if have_msgid: if have_msgstr: errors = validate_substitutions_match(entry.msgid, entry.msgstr, 'msgid', 'msgstr') entry_errors.extend(errors) if have_msgid_plural and have_msgstr: n_plurals = 0 for index, msgstr in entry.msgstr_plural.items(): have_msgstr_plural = msgstr.strip() != '' if have_msgstr_plural: n_plurals += 1 errors = validate_substitutions_match(entry.msgid_plural, msgstr, 'msgid_plural', 'msgstr_plural[%s]' % index) entry_errors.extend(errors) else: entry_errors.append('msgstr_plural[%s] is empty' % (index)) if n_plural_forms != n_plurals: entry_errors.append('%d plural forms specified, but this entry has %d plurals' % (n_plural_forms, n_plurals)) if pedantic: if have_msgid: errors = validate_substitution_syntax(entry.msgid, 'msgid') entry_warnings.extend(errors) if have_msgid_plural: errors = validate_substitution_syntax(entry.msgid_plural, 'msgid_plural') entry_warnings.extend(errors) errors = validate_substitutions_match(entry.msgid, entry.msgid_plural, 'msgid', 'msgid_plural') entry_warnings.extend(errors) for index, msgstr in entry.msgstr_plural.items(): have_msgstr_plural = msgstr.strip() != '' if have_msgstr_plural: errors = validate_substitution_syntax(msgstr, 'msgstr_plural[%s]' % index) entry_warnings.extend(errors) if have_msgstr: errors = validate_substitution_syntax(entry.msgstr, 'msgstr') entry_warnings.extend(errors) if entry_warnings: warning_lines.append(entry_seperator) warning_lines.append('locations: %s' % (', '.join(["%s:%d" % (x[0], int(x[1])) for x in entry.occurrences]))) warning_lines.extend(entry_warnings) n_warnings += 1 if entry_errors: error_lines.append(entry_seperator) error_lines.append('locations: %s' % (', '.join(["%s:%d" % (x[0], int(x[1])) for x in entry.occurrences]))) error_lines.extend(entry_errors) n_errors += 1 emit_messages() return Result(n_entries=n_entries, n_msgids=n_msgids, n_msgstrs=n_msgstrs, n_warnings=n_warnings, n_errors=n_errors) #---------------------------------------------------------------------- def create_po(pot_file, po_file, mo_file): if not os.path.isfile(pot_file): print('file does not exist "%s"' % (pot_file), file=sys.stderr) return 1 try: po = polib.pofile(pot_file) except Exception as e: print('Unable to parse file "%s": %s' % (pot_file, e), file=sys.stderr) return 1 # Update the metadata in the po file header # It's case insensitive so search the keys in a case insensitive manner # # We need to update the Plural-Forms otherwise gettext.py will raise the # following error: # # raise ValueError, 'plural forms expression could be dangerous' # # It is demanding the rhs of plural= only contains the identifer 'n' for k in po.metadata: if k.lower() == 'plural-forms': po.metadata[k] = 'nplurals=2; plural=(n != 1)' # the auto-generated PO file should have charset set to UTF-8 # because we are using UTF-8 prefix and suffix below elif k.lower() == 'content-type': po.metadata[k] = 'Content-Type: text/plain; charset=UTF-8' # Iterate over all msgid's and form a msgstr by prepending # the prefix and appending the suffix for entry in po: if entry.msgid_plural: entry.msgstr_plural = {0: prefix + entry.msgid + suffix, 1: prefix + entry.msgid_plural + suffix} else: entry.msgstr = prefix + entry.msgid + suffix # Write out the po and mo files po.save(po_file) print("Wrote: %s" % (po_file)) po.save_as_mofile(mo_file) print("Wrote: %s" % (mo_file)) return 0 #---------------------------------------------------------------------- def validate_unicode_edit(msgid, msgstr): # Verify the first character is the test prefix if msgstr[0] != prefix: raise ValueError('First char in translated string "%s" not equal to prefix "%s"' % (msgstr.encode('utf-8'), prefix.encode('utf-8'))) # Verify the last character is the test suffix if msgstr[-1] != suffix: raise ValueError('Last char in translated string "%s" not equal to suffix "%s"' % (msgstr.encode('utf-8'), suffix.encode('utf-8'))) # Verify everything between the first and last character is the # original untranslated string if msgstr[1:-1] != msgid: raise ValueError('Translated string "%s" minus the first & last character is not equal to msgid "%s"' % (msgstr.encode('utf-8'), msgid)) if verbose: msg = 'Success: message string "%s" maps to translated string "%s"' % (msgid, msgstr) print(msg.encode('utf-8')) def test_translations(po_file, lang, domain, locale_dir): # The test installs the test message catalog under the xh_ZA # (e.g. Zambia Xhosa) language by default. It would be nice to # use a dummy language not associated with any real language, # but the setlocale function demands the locale be a valid # known locale, Zambia Xhosa is a reasonable choice :) locale_envs = ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG') os.environ.update( {locale_env: lang for locale_env in locale_envs} ) # Create a gettext translation object specifying our domain as # 'ipa' and the locale_dir as 'test_locale' (i.e. where to # look for the message catalog). Then use that translation # object to obtain the translation functions. t = gettext.translation(domain, locale_dir) if six.PY2: get_msgstr = t.ugettext get_msgstr_plural = t.ungettext else: get_msgstr = t.gettext get_msgstr_plural = t.ngettext return po_file_iterate(po_file, get_msgstr, get_msgstr_plural) def po_file_iterate(po_file, get_msgstr, get_msgstr_plural): try: # Iterate over the msgid's if not os.path.isfile(po_file): print('file does not exist "%s"' % (po_file), file=sys.stderr) return 1 try: po = polib.pofile(po_file) except Exception as e: print('Unable to parse file "%s": %s' % (po_file, e), file=sys.stderr) return 1 n_entries = 0 n_translations = 0 n_valid = 0 n_fail = 0 for entry in po: if entry.msgid_plural: msgid = entry.msgid msgid_plural = entry.msgid_plural msgstr = get_msgstr_plural(msgid, msgid_plural, 1) msgstr_plural = get_msgstr_plural(msgid, msgid_plural, 2) try: n_translations += 1 validate_unicode_edit(msgid, msgstr) n_valid += 1 except Exception as e: n_fail += 1 if print_traceback: traceback.print_exc() print("ERROR: %s" % e, file=sys.stderr) try: n_translations += 1 validate_unicode_edit(msgid_plural, msgstr_plural) n_valid += 1 except Exception as e: n_fail += 1 if print_traceback: traceback.print_exc() print("ERROR: %s" % e, file=sys.stderr) else: msgid = entry.msgid msgstr = get_msgstr(msgid) try: n_translations += 1 validate_unicode_edit(msgid, msgstr) n_valid += 1 except Exception as e: n_fail += 1 if print_traceback: traceback.print_exc() print("ERROR: %s" % e, file=sys.stderr) n_entries += 1 except Exception as e: if print_traceback: traceback.print_exc() print("ERROR: %s" % e, file=sys.stderr) return 1 if not n_entries: print("ERROR: no translations found in %s" % (po_file), file=sys.stderr) return 1 if n_fail: print("ERROR: %d failures out of %d translations" % (n_fail, n_entries), file=sys.stderr) return 1 print("%d translations in %d messages successfully tested" % (n_translations, n_entries)) return 0 #---------------------------------------------------------------------- usage =''' %prog --test-gettext %prog --create-test %prog --validate-pot [pot_file1, ...] %prog --validate-po po_file1 [po_file2, ...] ''' def main(): global verbose, print_traceback, pedantic, show_strings parser = optparse.OptionParser(usage=usage) mode_group = optparse.OptionGroup(parser, 'Operational Mode', 'You must select one these modes to run in') mode_group.add_option('-g', '--test-gettext', action='store_const', const='test_gettext', dest='mode', help='create the test translation file(s) and exercise them') mode_group.add_option('-c', '--create-test', action='store_const', const='create_test', dest='mode', help='create the test translation file(s)') mode_group.add_option('-P', '--validate-pot', action='store_const', const='validate_pot', dest='mode', help='validate pot file(s)') mode_group.add_option('-p', '--validate-po', action='store_const', const='validate_po', dest='mode', help='validate po file(s)') parser.add_option_group(mode_group) parser.set_defaults(mode='') parser.add_option('-s', '--show-strings', action='store_true', dest='show_strings', default=False, help='show the offending string when an error is detected') parser.add_option('--pedantic', action='store_true', dest='pedantic', default=False, help='be aggressive when validating') parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='be informative') parser.add_option('--traceback', action='store_true', dest='print_traceback', default=False, help='print the traceback when an exception occurs') param_group = optparse.OptionGroup(parser, 'Run Time Parameters', 'These may be used to modify the run time defaults') param_group.add_option('--test-lang', action='store', dest='test_lang', default='test', help="test po file uses this as it's basename (default=test)") param_group.add_option('--lang', action='store', dest='lang', default='xh_ZA', help='lang used for locale, MUST be a valid lang (default=xh_ZA)') param_group.add_option('--domain', action='store', dest='domain', default='ipa', help='translation domain used during test (default=ipa)') param_group.add_option('--locale-dir', action='store', dest='locale_dir', default='test_locale', help='locale directory used during test (default=test_locale)') param_group.add_option('--pot-file', action='store', dest='pot_file', default='ipa.pot', help='default pot file, used when validating pot file or generating test po and mo files (default=ipa.pot)') parser.add_option_group(param_group) options, args = parser.parse_args() verbose = options.verbose print_traceback = options.print_traceback pedantic = options.pedantic show_strings = options.show_strings if not options.mode: print('ERROR: no mode specified', file=sys.stderr) return 1 if options.mode in ('validate_pot', 'validate_po'): if options.mode == 'validate_pot': files = args if not files: files = [options.pot_file] validation_mode = 'pot' reference_pot = None elif options.mode == 'validate_po': files = args if not files: print('ERROR: no po files specified', file=sys.stderr) return 1 validation_mode = 'po' reference_pot = polib.pofile(options.pot_file) else: print('ERROR: unknown validation mode "%s"' % (options.mode), file=sys.stderr) return 1 total_entries = 0 total_msgids = 0 total_msgstrs = 0 total_warnings = 0 total_errors = 0 for f in files: result = validate_file(f, validation_mode, reference_pot) total_entries += result.n_entries total_msgids += result.n_msgids total_msgstrs += result.n_msgstrs total_warnings += result.n_warnings total_errors += result.n_errors print("%s: %d entries, %d msgid, %d msgstr, %d warnings %d errors" % \ (f, result.n_entries, result.n_msgids, result.n_msgstrs, result.n_warnings, result.n_errors)) if total_errors: print(section_seperator) print("%d errors in %d files" % (total_errors, len(files))) return 1 else: return 0 elif options.mode in ('create_test', 'test_gettext'): po_file = '%s.po' % options.test_lang pot_file = options.pot_file msg_dir = os.path.join(options.locale_dir, options.lang, 'LC_MESSAGES') if not os.path.exists(msg_dir): os.makedirs(msg_dir) mo_basename = '%s.mo' % options.domain mo_file = os.path.join(msg_dir, mo_basename) result = create_po(pot_file, po_file, mo_file) if result: return result if options.mode == 'create_test': return result # The test installs the test message catalog under the xh_ZA # (e.g. Zambia Xhosa) language by default. It would be nice to # use a dummy language not associated with any real language, # but the setlocale function demands the locale be a valid # known locale, Zambia Xhosa is a reasonable choice :) lang = options.lang # Create a gettext translation object specifying our domain as # 'ipa' and the locale_dir as 'test_locale' (i.e. where to # look for the message catalog). Then use that translation # object to obtain the translation functions. domain = options.domain locale_dir = options.locale_dir return test_translations(po_file, lang, domain, locale_dir) else: print('ERROR: unknown mode "%s"' % (options.mode), file=sys.stderr) return 1 if __name__ == "__main__": sys.exit(main())
32,885
Python
.py
706
37.365439
138
0.596859
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,302
__init__.py
freeipa_freeipa/ipatests/__init__.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Package containing all unit tests. """
822
Python
.py
21
38.095238
71
0.77125
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,303
test_util.py
freeipa_freeipa/ipatests/test_util.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `tests.util` module. """ import re import six from ipatests import util from ipatests.util import raises, TYPE, VALUE, LEN, KEYS import pytest if six.PY3: unicode = str pytestmark = pytest.mark.tier0 pattern_type = type(re.compile("")) class Prop: def __init__(self, *ops): self.__ops = frozenset(ops) self.__prop = 'prop value' def __get_prop(self): if 'get' not in self.__ops: raise AttributeError('get prop') return self.__prop def __set_prop(self, value): if 'set' not in self.__ops: raise AttributeError('set prop') self.__prop = value def __del_prop(self): if 'del' not in self.__ops: raise AttributeError('del prop') self.__prop = None prop = property(__get_prop, __set_prop, __del_prop) class test_Fuzzy: klass = util.Fuzzy def test_init(self): inst = self.klass() assert inst.regex is None assert inst.type is None assert inst.test is None assert inst.re is None inst = self.klass('(foo|bar)') assert inst.regex == '(foo|bar)' assert inst.type is unicode assert inst.test is None assert isinstance(inst.re, pattern_type) inst = self.klass('(foo|bar)', type=str) assert inst.regex == '(foo|bar)' assert inst.type is str assert inst.test is None assert isinstance(inst.re, pattern_type) def t(other): return other > 500 inst = self.klass(test=t) assert inst.regex is None assert inst.type is None assert inst.test is t assert inst.re is None inst = self.klass(type=(int, float), test=t) assert inst.regex is None assert inst.type == (int, float) assert inst.test is t assert inst.re is None def test_repr(self): s = 'Fuzzy(%r, %r, %r)' def t(other): return 0.0 <= other <= 1.0 inst = self.klass() assert repr(inst) == s % (None, None, None) inst = self.klass('foo') assert repr(inst) == s % ('foo', unicode, None) inst = self.klass(type=(int, float)) assert repr(inst) == s % (None, (int, float), None) inst = self.klass(type=(int, float), test=t) assert repr(inst) == s % (None, (int, float), t) inst = self.klass(test=t) assert repr(inst) == s % (None, None, t) def test_eq(self): assert (self.klass('bar') == u'foobar') is True assert (self.klass('^bar') == u'foobar') is False assert (self.klass('bar', type=bytes) == u'foobar') is False assert ('18' == self.klass()) is True assert ('18' == self.klass(type=int)) is False assert (18 == self.klass(type=int)) is True assert ('18' == self.klass(type=(int, str))) is True assert (self.klass() == '18') is True assert (self.klass(type=int) == '18') is False assert (self.klass(type=int) == 18) is True assert (self.klass(type=(int, str)) == '18') is True def t(other): return other.endswith('bar') assert (self.klass(test=t) == 'foobar') is True assert (self.klass(test=t, type=unicode) == b'foobar') is False assert (self.klass(test=t) == 'barfoo') is False assert (False == self.klass()) is True # noqa assert (True == self.klass()) is True # noqa assert (None == self.klass()) is True # noqa def test_assert_deepequal(pytestconfig): f = util.assert_deepequal try: pretty = pytestconfig.getoption("pretty_print") except (AttributeError, ValueError): pretty = False # LEN and KEYS formats use special function to pretty print structures # depending on a pytest environment settings def got_str(s): return util.struct_to_string(s, util.GOT_LEN) if pretty else str(s) def exp_str(s): ret = util.struct_to_string(s, util.EXPECTED_LEN) if pretty else str(s) return ret # Test with good scalar values: f(u'hello', u'hello') f(util.Fuzzy(), u'hello') f(util.Fuzzy(type=unicode), u'hello') f(util.Fuzzy('ell'), u'hello') f(util.Fuzzy(test=lambda other: other.endswith('llo')), u'hello') f(18, 18) f(util.Fuzzy(), 18) f(util.Fuzzy(type=int), 18) f(util.Fuzzy(type=(int, float), test=lambda other: other > 17.9), 18) # Test with bad scalar values: e = raises(AssertionError, f, u'hello', u'world', 'foo') assert str(e) == VALUE % ( 'foo', u'hello', u'world', tuple() ) e = raises(AssertionError, f, b'hello', u'hello', 'foo') assert str(e) == TYPE % ( 'foo', bytes, unicode, b'hello', u'hello', tuple() ) e = raises(AssertionError, f, 18, 18.0, 'foo') assert str(e) == TYPE % ( 'foo', int, float, 18, 18.0, tuple() ) # Test with good compound values: a = [ u'hello', dict(profession=u'nurse'), 18, ] b = [ u'hello', dict(profession=u'nurse'), 18, ] f(a, b) # Test with bad compound values: b = [ b'hello', dict(profession=u'nurse'), 18, ] e = raises(AssertionError, f, a, b, 'foo') assert str(e) == TYPE % ( 'foo', unicode, bytes, u'hello', b'hello', (2 if six.PY2 else 0,) ) b = [ u'hello', dict(profession=b'nurse'), 18, ] e = raises(AssertionError, f, a, b, 'foo') assert str(e) == TYPE % ( 'foo', unicode, bytes, u'nurse', b'nurse', (1, 'profession') ) b = [ u'hello', dict(profession=u'nurse'), 18.0, ] e = raises(AssertionError, f, a, b, 'foo') assert str(e) == TYPE % ( 'foo', int, float, 18, 18.0, (0 if six.PY2 else 2,) ) # List length mismatch b = [ u'hello', dict(profession=u'nurse'), 18, 19 ] e = raises(AssertionError, f, a, b, 'foo') assert str(e) == LEN % ( 'foo', 3, 4, exp_str(a), got_str(b), tuple() ) b = [ dict(profession=u'nurse'), 18, ] e = raises(AssertionError, f, a, b, 'foo') assert str(e) == LEN % ( 'foo', 3, 2, exp_str(a), got_str(b), tuple() ) # Dict keys mismatch: # Missing b = [ u'hello', dict(), 18, ] e = raises(AssertionError, f, a, b, 'foo') assert str(e) == KEYS % ( 'foo', ['profession'], [], exp_str(dict(profession=u'nurse')), got_str(dict()), (1,) ) # Extra b = [ u'hello', dict(profession=u'nurse', status=u'RN'), 18, ] e = raises(AssertionError, f, a, b, 'foo') assert str(e) == KEYS % ( 'foo', [], ['status'], exp_str(dict(profession=u'nurse')), got_str(dict(profession=u'nurse', status=u'RN')), (1,) ) # Missing + Extra b = [ u'hello', dict(status=u'RN'), 18, ] e = raises(AssertionError, f, a, b, 'foo') assert str(e) == KEYS % ( 'foo', ['profession'], ['status'], exp_str(dict(profession=u'nurse')), got_str(dict(status=u'RN')), (1,) ) def test_yes_raised(): f = util.raises class SomeError(Exception): pass class AnotherError(Exception): pass def callback1(): 'raises correct exception' raise SomeError() def callback2(): 'raises wrong exception' raise AnotherError() def callback3(): 'raises no exception' f(SomeError, callback1) raised = False try: f(SomeError, callback2) except AnotherError: raised = True assert raised raised = False try: f(SomeError, callback3) except util.ExceptionNotRaised: raised = True assert raised def test_no_set(): # Tests that it works when prop cannot be set: util.no_set(Prop('get', 'del'), 'prop') # Tests that ExceptionNotRaised is raised when prop *can* be set: raised = False try: util.no_set(Prop('set'), 'prop') except util.ExceptionNotRaised: raised = True assert raised def test_no_del(): # Tests that it works when prop cannot be deleted: util.no_del(Prop('get', 'set'), 'prop') # Tests that ExceptionNotRaised is raised when prop *can* be set: raised = False try: util.no_del(Prop('del'), 'prop') except util.ExceptionNotRaised: raised = True assert raised def test_read_only(): # Test that it works when prop is read only: assert util.read_only(Prop('get'), 'prop') == 'prop value' # Test that ExceptionNotRaised is raised when prop can be set: raised = False try: util.read_only(Prop('get', 'set'), 'prop') except util.ExceptionNotRaised: raised = True assert raised # Test that ExceptionNotRaised is raised when prop can be deleted: raised = False try: util.read_only(Prop('get', 'del'), 'prop') except util.ExceptionNotRaised: raised = True assert raised # Test that ExceptionNotRaised is raised when prop can be both set and # deleted: raised = False try: util.read_only(Prop('get', 'del'), 'prop') except util.ExceptionNotRaised: raised = True assert raised # Test that AttributeError is raised when prop can't be read: raised = False try: util.read_only(Prop(), 'prop') except AttributeError: raised = True assert raised
10,420
Python
.py
326
25.279141
79
0.586768
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,304
data.py
freeipa_freeipa/ipatests/data.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Data frequently used in the unit tests, especially Unicode related tests. """ import struct # A string that should have bytes 'x\00' through '\xff': binary_bytes = b''.join(struct.pack('B', d) for d in range(256)) assert b'\x00' in binary_bytes and b'\xff' in binary_bytes assert type(binary_bytes) is bytes and len(binary_bytes) == 256 # A UTF-8 encoded str: utf8_bytes = b'\xd0\x9f\xd0\xb0\xd0\xb2\xd0\xb5\xd0\xbb' # The same UTF-8 data decoded (a unicode instance): unicode_str = u'\u041f\u0430\u0432\u0435\u043b' assert utf8_bytes.decode('UTF-8') == unicode_str assert unicode_str.encode('UTF-8') == utf8_bytes
1,403
Python
.py
32
42.65625
73
0.756044
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,305
test_kinit.py
freeipa_freeipa/ipatests/test_ipalib_install/test_kinit.py
# # Copyright (C) 2024 FreeIPA Contributors see COPYING for license # """Tests for ipalib.install.kinit module """ import pytest from ipalib.install.kinit import validate_principal # None means no exception is expected @pytest.mark.parametrize('principal, exception', [ ('testuser', None), ('testuser@EXAMPLE.TEST', None), ('test/ipa.example.test', None), ('test/ipa.example.test@EXAMPLE.TEST', None), ('test/ipa@EXAMPLE.TEST', RuntimeError), ('test/-ipa.example.test@EXAMPLE.TEST', RuntimeError), ('test/ipa.1example.test@EXAMPLE.TEST', None), ('test /ipa.example,test', RuntimeError), ('testuser@OTHER.TEST', None), ('test/ipa.example.test@OTHER.TEST', None) ]) def test_validate_principal(principal, exception): try: validate_principal(principal) except Exception as e: assert e.__class__ == exception else: if exception is not None: raise RuntimeError('Test should have failed')
976
Python
.py
28
30.571429
66
0.698093
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,306
__init__.py
freeipa_freeipa/ipatests/test_ipatests_plugins/__init__.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # """ Sub-package containing unit tests for IPA internal test plugins """
144
Python
.py
6
22.833333
66
0.781022
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,307
test_ipa_run_tests.py
freeipa_freeipa/ipatests/test_ipatests_plugins/test_ipa_run_tests.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # import os import pytest MOD_NAME = "test_module_{}" FUNC_NAME = "test_func_{}" MODS_NUM = 5 @pytest.fixture def ipatestdir(testdir, monkeypatch): """ Create MODS_NUM test modules within testdir/ipatests. Each module contains 1 test function. Patch PYTHONPATH with created package path to override the system's ipatests """ ipatests_dir = testdir.mkpydir("ipatests") for i in range(MODS_NUM): ipatests_dir.join("{}.py".format(MOD_NAME.format(i))).write( "def {}(): pass".format(FUNC_NAME.format(i))) python_path = os.pathsep.join( filter(None, [str(testdir.tmpdir), os.environ.get("PYTHONPATH", "")])) monkeypatch.setenv("PYTHONPATH", python_path) def run_ipa_tests(*args): cmdargs = ["ipa-run-tests", "-v"] + list(args) return testdir.run(*cmdargs, timeout=60) testdir.run_ipa_tests = run_ipa_tests return testdir def test_ipa_run_tests_basic(ipatestdir): """ Run ipa-run-tests with default arguments """ result = ipatestdir.run_ipa_tests() assert result.ret == 0 result.assert_outcomes(passed=MODS_NUM) for mod_num in range(MODS_NUM): result.stdout.fnmatch_lines(["*{mod}.py::{func} PASSED*".format( mod=MOD_NAME.format(mod_num), func=FUNC_NAME.format(mod_num))]) def test_ipa_run_tests_glob1(ipatestdir): """ Run ipa-run-tests using glob patterns to collect tests """ result = ipatestdir.run_ipa_tests("{mod}".format( mod="test_modul[!E]?[0-5]*")) assert result.ret == 0 result.assert_outcomes(passed=MODS_NUM) for mod_num in range(MODS_NUM): result.stdout.fnmatch_lines(["*{mod}.py::{func} PASSED*".format( mod=MOD_NAME.format(mod_num), func=FUNC_NAME.format(mod_num))]) def test_ipa_run_tests_glob2(ipatestdir): """ Run ipa-run-tests using glob patterns to collect tests """ result = ipatestdir.run_ipa_tests("{mod}".format( mod="test_module_{0,1}*")) assert result.ret == 0 result.assert_outcomes(passed=2) for mod_num in range(2): result.stdout.fnmatch_lines(["*{mod}.py::{func} PASSED*".format( mod=MOD_NAME.format(mod_num), func=FUNC_NAME.format(mod_num))]) def test_ipa_run_tests_specific_nodeid(ipatestdir): """ Run ipa-run-tests using nodeid to collect test """ mod_num = 0 result = ipatestdir.run_ipa_tests("{mod}.py::{func}".format( mod=MOD_NAME.format(mod_num), func=FUNC_NAME.format(mod_num))) assert result.ret == 0 result.assert_outcomes(passed=1) result.stdout.fnmatch_lines(["*{mod}.py::{func} PASSED*".format( mod=MOD_NAME.format(mod_num), func=FUNC_NAME.format(mod_num))]) @pytest.mark.parametrize( "expr", [["-k", "not {func}".format(func=FUNC_NAME.format(0))], ["-k not {func}".format(func=FUNC_NAME.format(0))]]) def test_ipa_run_tests_expression(ipatestdir, expr): """ Run ipa-run-tests using expression """ result = ipatestdir.run_ipa_tests(*expr) assert result.ret == 0 result.assert_outcomes(passed=4) for mod_num in range(1, MODS_NUM): result.stdout.fnmatch_lines(["*{mod}.py::{func} PASSED*".format( mod=MOD_NAME.format(mod_num), func=FUNC_NAME.format(mod_num))]) def test_ipa_run_tests_empty_expression(ipatestdir): """ Run ipa-run-tests using an empty expression. Expected result: all tests should pass. """ result = ipatestdir.run_ipa_tests('-k', '') assert result.ret == 0 result.assert_outcomes(passed=5) for mod_num in range(0, MODS_NUM): result.stdout.fnmatch_lines(["*{mod}.py::{func} PASSED*".format( mod=MOD_NAME.format(mod_num), func=FUNC_NAME.format(mod_num))]) def test_ipa_run_tests_ignore_basic(ipatestdir): """ Run ipa-run-tests ignoring one test module """ result = ipatestdir.run_ipa_tests( "--ignore", "{mod}.py".format(mod=MOD_NAME.format(0)), "--ignore", "{mod}.py".format(mod=MOD_NAME.format(1)), ) assert result.ret == 0 result.assert_outcomes(passed=MODS_NUM - 2) for mod_num in range(2, MODS_NUM): result.stdout.fnmatch_lines(["*{mod}.py::{func} PASSED*".format( mod=MOD_NAME.format(mod_num), func=FUNC_NAME.format(mod_num))]) def test_ipa_run_tests_defaultargs(ipatestdir): """ Checking the ipa-run-tests defaults: * cachedir * rootdir """ mod_num = 0 result = ipatestdir.run_ipa_tests("{mod}.py::{func}".format( mod=MOD_NAME.format(mod_num), func=FUNC_NAME.format(mod_num))) assert result.ret == 0 result.assert_outcomes(passed=1) result.stdout.re_match_lines([ "^cachedir: {cachedir}$".format( cachedir=os.path.join(os.getcwd(), ".pytest_cache")), "^rootdir: {rootdir}([,].*)?$".format( rootdir=os.path.join(str(ipatestdir.tmpdir), "ipatests")) ]) def test_ipa_run_tests_confcutdir(ipatestdir): """ Checking the ipa-run-tests defaults: * confcutdir """ mod_num = 0 ipatestdir.makeconftest("import somenotexistedpackage") result = ipatestdir.run_ipa_tests("{mod}.py::{func}".format( mod=MOD_NAME.format(mod_num), func=FUNC_NAME.format(mod_num))) assert result.ret == 0 result.assert_outcomes(passed=1) result.stdout.fnmatch_lines(["*{mod}.py::{func} PASSED*".format( mod=MOD_NAME.format(mod_num), func=FUNC_NAME.format(mod_num))])
5,630
Python
.py
150
31.393333
78
0.640264
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,308
test_slicing.py
freeipa_freeipa/ipatests/test_ipatests_plugins/test_slicing.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # import glob import pytest MOD_NAME = "test_module_{}" FUNC_NAME = "test_func_{}" PYTEST_INTERNAL_ERROR = 3 MODS_NUM = 5 @pytest.fixture def ipatestdir(testdir): """ Create MODS_NUM test modules within testdir. Each module contains 1 test function. """ testdir.makeconftest( """ pytest_plugins = ["ipatests.pytest_ipa.slicing"] """ ) for i in range(MODS_NUM): testdir.makepyfile( **{MOD_NAME.format(i): """ def {func}(): pass """.format(func=FUNC_NAME.format(i)) } ) return testdir @pytest.mark.parametrize( "nslices,nslices_d,groups", [(2, 0, [[x for x in range(MODS_NUM) if x % 2 == 0], [x for x in range(MODS_NUM) if x % 2 != 0]]), (2, 1, [[0], list(range(1, MODS_NUM))]), (1, 0, [list(range(MODS_NUM))]), (1, 1, [list(range(MODS_NUM))]), (MODS_NUM, MODS_NUM, [[x] for x in range(MODS_NUM)]), ]) def test_slicing(ipatestdir, nslices, nslices_d, groups): """ Positive tests. Run `nslices` slices, including `nslices_d` dedicated slices. The `groups` is an expected result of slices grouping. For example, there are 5 test modules. If one runs them in two slices (without dedicated ones) the expected result will be [[0, 2, 4], [1, 3]]. This means, that first slice will run modules 0, 2, 4, second one - 1 and 3. Another example, there are 5 test modules. We want to run them in two slices. Also we specify module 0 as dedicated. The expected result will be [[0], [1, 2, 3, 4]], which means, that first slice will run module 0, second one - 1, 2, 3, 4. If the given slice count is one, then this plugin does nothing. """ for sl in range(nslices): args = [ "-v", "--slices={}".format(nslices), "--slice-num={}".format(sl + 1) ] for dslice in range(nslices_d): args.append( "--slice-dedicated={}.py".format(MOD_NAME.format(dslice))) result = ipatestdir.runpytest(*args) assert result.ret == 0 result.assert_outcomes(passed=len(groups[sl])) for mod_num in groups[sl]: result.stdout.fnmatch_lines(["*{mod}.py::{func} PASSED*".format( mod=MOD_NAME.format(mod_num), func=FUNC_NAME.format(mod_num))]) @pytest.mark.parametrize( "nslices,nslices_d,nslice,dmod,err_message", [(2, 3, 1, None, "Dedicated slice number({}) shouldn't be greater than" " the number of slices({})".format(3, 2)), (MODS_NUM, 0, MODS_NUM + 1, None, "Slice number({}) shouldn't be greater than the number of slices" "({})".format( MODS_NUM + 1, MODS_NUM)), (MODS_NUM + 1, 1, 1, None, "Total number of slices({}) shouldn't be greater" " than the number of Python test modules({})".format( MODS_NUM + 1, MODS_NUM)), (MODS_NUM, MODS_NUM, 1, "notexisted_module", "The number of dedicated slices({}) should be equal to the " "number of dedicated modules({})".format( [], ["notexisted_module.py"])), (MODS_NUM - 1, MODS_NUM - 1, 1, None, "The total number of slices({}) is not sufficient to" " run dedicated modules({}) as well as usual ones({})".format( MODS_NUM - 1, MODS_NUM - 1, 1)), ]) def test_slicing_negative(ipatestdir, nslices, nslices_d, nslice, dmod, err_message): """ Negative scenarios """ args = [ "-v", "--slices={}".format(nslices), "--slice-num={}".format(nslice) ] if dmod is None: for dslice in range(nslices_d): args.append( "--slice-dedicated={}.py".format(MOD_NAME.format(dslice))) else: args.append( "--slice-dedicated={}.py".format(dmod)) result = ipatestdir.runpytest(*args) assert result.ret == PYTEST_INTERNAL_ERROR result.assert_outcomes() result.stdout.fnmatch_lines(["*ValueError: {err_message}*".format( err_message=glob.escape(err_message))])
4,247
Python
.py
114
29.754386
76
0.583981
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,309
test_depr_frameworks.py
freeipa_freeipa/ipatests/test_ipatests_plugins/test_depr_frameworks.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # import pytest @pytest.fixture def ipa_testdir(testdir): """ Create conftest within testdir. """ testdir.makeconftest( """ pytest_plugins = ["ipatests.pytest_ipa.deprecated_frameworks"] """ ) return testdir @pytest.fixture def xunit_testdir(ipa_testdir): """ Create xnit style test module within testdir. """ ipa_testdir.makepyfile(""" def setup_module(): pass def teardown_module(): pass def setup_function(): pass def teardown_function(): pass class TestClass: @classmethod def setup_class(cls): pass @classmethod def teardown_class(cls): pass def setup_method(self): pass def teardown_method(self): pass def test_m(self): pass """) return ipa_testdir @pytest.fixture def unittest_testdir(ipa_testdir): """ Create unittest style test module within testdir. """ ipa_testdir.makepyfile(""" import unittest def setUpModule(): pass def tearDownModule(): pass class TestClass(unittest.TestCase): @classmethod def setUp(self): pass def tearDown(self): pass @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def test_m(self): pass """) return ipa_testdir def test_xunit(xunit_testdir): result = xunit_testdir.runpytest() result.assert_outcomes(passed=1) result.stdout.fnmatch_lines([ "* PytestIPADeprecationWarning: xunit style is deprecated in favour of " "fixtures style", "* 8 warning*", ]) def test_unittest(unittest_testdir): result = unittest_testdir.runpytest() result.assert_outcomes(passed=1) result.stdout.fnmatch_lines([ "* PytestIPADeprecationWarning: unittest is deprecated in favour of " "fixtures style", "* 1 warning*", ])
2,315
Python
.py
87
17.793103
80
0.560921
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,310
slicing.py
freeipa_freeipa/ipatests/pytest_ipa/slicing.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # """ The main purpose of this plugin is to slice a test suite into several pieces to run each within its own test environment(for example, an Agent of Azure Pipelines). Tests within a slice are grouped by test modules because not all of the tests within the module are independent from each other. Slices are balanced by the number of tests within test module. * Actually, tests should be grouped by the execution duration. This could be achieved by the caching of tests results. Azure Pipelines caching is in development. * To workaround slow tests a dedicated slice is added. :param slices: A total number of slices to split the test suite into :param slice-num: A number of slice to run :param slice-dedicated: A file path to the module to run in its own slice **Examples** Inputs: ipa-run-tests test_cmdline --collectonly -qq ... test_cmdline/test_cli.py: 39 test_cmdline/test_help.py: 7 test_cmdline/test_ipagetkeytab.py: 16 ... * Split tests into 2 slices and run the first one: ipa-run-tests --slices=2 --slice-num=1 test_cmdline The outcome would be: ... Running slice: 1 (46 tests) Modules: test_cmdline/test_cli.py: 39 test_cmdline/test_help.py: 7 ... * Split tests into 2 slices, move one module out to its own slice and run the second one ipa-run-tests --slices=2 --slice-dedicated=test_cmdline/test_cli.py \ --slice-num=2 test_cmdline The outcome would be: ... Running slice: 2 (23 tests) Modules: test_cmdline/test_ipagetkeytab.py: 16 test_cmdline/test_help.py: 7 ... """ import pytest def pytest_addoption(parser): group = parser.getgroup("slicing") group.addoption( '--slices', dest='slices_num', type=int, help='The number of slices to split the test suite into') group.addoption( '--slice-num', dest='slice_num', type=int, help='The specific number of slice to run') group.addoption( '--slice-dedicated', action="append", dest='slices_dedicated', help='The file path to the module to run in dedicated slice') @pytest.hookimpl(hookwrapper=True) def pytest_collection_modifyitems(session, config, items): yield slice_count = config.getoption('slices_num') slice_id = config.getoption('slice_num') modules_dedicated = config.getoption('slices_dedicated') # deduplicate if modules_dedicated: modules_dedicated = list(set(modules_dedicated)) # sanity check if not slice_count or not slice_id: return # nothing to do if slice_count == 1: return if modules_dedicated and len(modules_dedicated) > slice_count: raise ValueError( "Dedicated slice number({}) shouldn't be greater than the number " "of slices({})".format(len(modules_dedicated), slice_count)) if slice_id > slice_count: raise ValueError( "Slice number({}) shouldn't be greater than the number of slices" "({})".format(slice_id, slice_count)) modules = [] # Calculate modules within collection # Note: modules within pytest collection could be placed in not consecutive # order for number, item in enumerate(items): name = item.nodeid.split("::", 1)[0] if not modules or name != modules[-1]["name"]: modules.append({"name": name, "begin": number, "end": number}) else: modules[-1]["end"] = number if slice_count > len(modules): raise ValueError( "Total number of slices({}) shouldn't be greater than the number " "of Python test modules({})".format(slice_count, len(modules))) slices_dedicated = [] if modules_dedicated: slices_dedicated = [ [m] for m in modules for x in modules_dedicated if x in m["name"] ] if modules_dedicated and len(slices_dedicated) != len(modules_dedicated): raise ValueError( "The number of dedicated slices({}) should be equal to the " "number of dedicated modules({})".format( slices_dedicated, modules_dedicated)) if (slices_dedicated and len(slices_dedicated) == slice_count and len(slices_dedicated) != len(modules)): raise ValueError( "The total number of slices({}) is not sufficient to run dedicated" " modules({}) as well as usual ones({})".format( slice_count, len(slices_dedicated), len(modules) - len(slices_dedicated))) # remove dedicated modules from usual ones for s in slices_dedicated: for m in s: if m in modules: modules.remove(m) avail_slice_count = slice_count - len(slices_dedicated) # initialize slices with empty lists slices = [[] for i in range(slice_count)] # initialize slices with dedicated ones for sn, s in enumerate(slices_dedicated): slices[sn] = s # initial reverse sort by the number of tests in a test module modules.sort(reverse=True, key=lambda x: x["end"] - x["begin"] + 1) reverse = True while modules: for sslice_num, sslice in enumerate(sorted( modules[:avail_slice_count], reverse=reverse, key=lambda x: x["end"] - x["begin"] + 1)): slices[len(slices_dedicated) + sslice_num].append(sslice) modules[:avail_slice_count] = [] reverse = not reverse calc_ntests = sum(x["end"] - x["begin"] + 1 for s in slices for x in s) assert calc_ntests == len(items) assert len(slices) == slice_count # the range of the given argument `slice_id` begins with 1(one) sslice = slices[slice_id - 1] new_items = [] for m in sslice: new_items += items[m["begin"]:m["end"] + 1] items[:] = new_items tw = config.get_terminal_writer() if tw: tw.line() tw.write( "Running slice: {} ({} tests)\n".format( slice_id, len(items), ), cyan=True, bold=True, ) tw.write( "Modules:\n", yellow=True, bold=True, ) for module in sslice: tw.write( "{}: {}\n".format( module["name"], module["end"] - module["begin"] + 1), yellow=True, ) tw.line()
6,400
Python
.py
166
31.638554
79
0.639677
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,311
beakerlib.py
freeipa_freeipa/ipatests/pytest_ipa/beakerlib.py
# Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """Test integration with BeakerLib IPA-specific configuration for the BeakerLib plugin (from pytest-beakerlib). If the plugin is active, sets up IPA logging to also log to Beaker. """ import logging from ipapython.ipa_log_manager import Formatter def pytest_configure(config): plugin = config.pluginmanager.getplugin('BeakerLibPlugin') if plugin: root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) handler = BeakerLibLogHandler(plugin.run_beakerlib_command) handler.setLevel(logging.INFO) handler.setFormatter(Formatter('[%(name)s] %(message)s')) root_logger.addHandler(handler) class BeakerLibLogHandler(logging.Handler): def __init__(self, beakerlib_command): super(BeakerLibLogHandler, self).__init__() self.beakerlib_command = beakerlib_command def emit(self, record): command = { 'DEBUG': 'rlLogDebug', 'INFO': 'rlLogInfo', 'WARNING': 'rlLogWarning', 'ERROR': 'rlLogError', 'CRITICAL': 'rlLogFatal', }.get(record.levelname, 'rlLog') self.beakerlib_command([command, self.format(record)])
1,909
Python
.py
44
38.409091
76
0.717907
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,312
additional_config.py
freeipa_freeipa/ipatests/pytest_ipa/additional_config.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # def pytest_addoption(parser): parser.addoption("--no-pretty-print", action="store_false", dest="pretty_print", help="Don't pretty-print structures")
247
Python
.py
6
35.666667
79
0.690377
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,313
nose_compat.py
freeipa_freeipa/ipatests/pytest_ipa/nose_compat.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Provides command-line options for very limited Nose compatibility""" import os import sys import logging from ipapython.ipa_log_manager import Formatter, convert_log_level def pytest_addoption(parser): group = parser.getgroup("IPA nosetests compatibility shim") group.addoption('--with-xunit', action="store_const", dest="xmlpath", metavar="path", default=None, const=os.environ.get('IPATEST_XUNIT_PATH', './nosetests.xml'), help="create junit-xml style report file at $IPATEST_XUNIT_PATH," "or nosetests.xml by default") group.addoption('--logging-level', action="store", dest="logging_level", metavar="level", default='CRITICAL', help="level for logging to stderr. " "Bypasses pytest logging redirection." "May be used to show progress of long-running tests.") def pytest_configure(config): if config.getoption('logging_level'): # Forward IPA logging to a normal Python logger. Nose's logcapture plugin # can't work with IPA-managed loggers class LogHandler(logging.Handler): name = 'forwarding log handler' logger = logging.getLogger('IPA') def emit(self, record): capture = config.pluginmanager.getplugin('capturemanager') orig_stdout, orig_stderr = sys.stdout, sys.stderr if capture: capture.suspend_global_capture() sys.stderr.write(self.format(record)) sys.stderr.write('\n') if capture: capture.resume_global_capture() sys.stdout, sys.stderr = orig_stdout, orig_stderr level = convert_log_level(config.getoption('logging_level')) handler = LogHandler() handler.setFormatter(Formatter('[%(name)s] %(message)s')) handler.setLevel(level) root_logger = logging.getLogger() root_logger.addHandler(handler)
2,777
Python
.py
58
40.137931
81
0.674178
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,314
deprecated_frameworks.py
freeipa_freeipa/ipatests/pytest_ipa/deprecated_frameworks.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # """Warns about xunit/unittest/nose tests. FreeIPA is a rather old project and hereby includes all the most famous in the past and present Python test idioms. Of course, this is difficult to play around all of them. For now, the runner of the IPA's test suite is Pytest. Pytest supports xunit style setups, unittest, nose tests. But this support is limited and may be dropped in the future releases. Worst of all is that the mixing of various test frameworks results in weird conflicts and of course, is not widely tested. In other words, there is a big risk. To eliminate this risk and to not pin Pytest to 3.x branch IPA's tests were refactored. This plugin is intended to issue warnings on collecting tests, which employ unittest/nose frameworks or xunit style. To treat these warnings as errors it's enough to run Pytest with: -W error:'xunit style is deprecated':pytest.PytestIPADeprecationWarning """ from unittest import TestCase from ipatests.conftest import PytestIPADeprecationWarning forbidden_module_scopes = [ 'setup_module', 'setup_function', 'teardown_module', 'teardown_function', ] forbidden_class_scopes = [ 'setup_class', 'setup_method', 'teardown_class', 'teardown_method', ] def pytest_collection_finish(session): for item in session.items: cls = getattr(item, 'cls', None) if cls is not None and issubclass(cls, TestCase): item.warn(PytestIPADeprecationWarning( "unittest is deprecated in favour of fixtures style")) continue def xunit_depr_warn(item, attr, names): for n in names: obj = getattr(item, attr, None) method = getattr(obj, n, None) fixtured = hasattr(method, '__pytest_wrapped__') if method is not None and not fixtured: item.warn(PytestIPADeprecationWarning( "xunit style is deprecated in favour of " "fixtures style")) xunit_depr_warn(item, 'module', forbidden_module_scopes) xunit_depr_warn(item, 'cls', forbidden_class_scopes)
2,210
Python
.py
51
36.960784
71
0.701632
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,315
declarative.py
freeipa_freeipa/ipatests/pytest_ipa/declarative.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Pytest plugin for Declarative tests""" def pytest_generate_tests(metafunc): """Generates Declarative tests""" if 'declarative_test_definition' in metafunc.fixturenames: tests = [] descriptions = [] for i, test in enumerate(metafunc.cls.tests): if callable(test): description = '%s: %s' % ( str(i).zfill(4), test.__name__, ) else: description = '%s: %s: %s' % (str(i).zfill(4), test['command'][0], test.get('desc', '')) test = dict(test) test['nice'] = description tests.append(test) descriptions.append(description) metafunc.parametrize( ['index', 'declarative_test_definition'], enumerate(tests), ids=descriptions, )
1,741
Python
.py
43
31.418605
71
0.60177
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,316
expect.py
freeipa_freeipa/ipatests/pytest_ipa/integration/expect.py
import time import logging import pexpect from pexpect.exceptions import ExceptionPexpect, TIMEOUT logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) class IpaTestExpect(pexpect.spawn): """A wrapper class around pexpect.spawn for easier usage in automated tests Please see pexpect documentation at https://pexpect.readthedocs.io/en/stable/api/index.html for general usage instructions. Note that usage of "+", "*" and '?' at the end of regular expressions arguments to .expect() is meaningless. This wrapper adds ability to use the class as a context manager, which will take care of verifying process return status and terminating the process if it did not do it normally. The context manager is the recommended way of using the class in tests. Basic usage example: ``` with IpaTestExpect('some_command') as e: e.expect_exact('yes or no?') e.sendline('yes') ``` At exit from context manager the following checks are performed by default: 1. there is nothing in output since last call to .expect() 2. the process has terminated 3. return code is 0 If any check fails, an exceptio is raised. If you want to override checks 1 and 3 you can call .expect_exit() explicitly: ``` with IpaTestExpect('some_command') as e: ... e.expect_exit(ok_returncode=1, ignore_remaining_output=True) ``` All .expect* methods are strict, meaning that if they do not find the pattern in the output during given amount of time, the exception is raised. So they can directly be used to verify output for presence of specific strings. Another addition is .get_last_output() method which can be used get process output from penultimate up to the last call to .expect(). The result can be used for more complex checks which can not be expressed as simple regexes, for example we can check for absence of string in output: ``` with IpaTestExpect('some_command') as e: ... e.expect('All done') output = e.get_last_output() assert 'WARNING' not in output ``` """ def __init__(self, argv, default_timeout=10, encoding='utf-8'): if isinstance(argv, str): command = argv args = [] else: command = argv[0] args = argv[1:] logger.debug('Expect will spawn command "%s" with args %s', command, args) super().__init__( command, args, timeout=default_timeout, encoding=encoding, echo=False ) def expect_exit(self, timeout=-1, ok_returncode=0, raiseonerr=True, ignore_remaining_output=False): if timeout == -1: timeout = self.timeout wait_to_exit_until = time.time() + timeout if not self.eof(): self.expect(pexpect.EOF, timeout) errors = [] if not ignore_remaining_output and self.before.strip(): errors.append('Unexpected output at program exit: {!r}' .format(self.before)) while time.time() < wait_to_exit_until: if not self.isalive(): break time.sleep(0.1) else: errors.append('Program did not exit after waiting for {} seconds' .format(self.timeout)) if (not self.isalive() and raiseonerr and self.exitstatus != ok_returncode): errors.append('Program exited with unexpected status {}' .format(self.exitstatus)) self.exit_checked = True if errors: raise ExceptionPexpect( 'Program exited with an unexpected state:\n' + '\n'.join(errors)) def send(self, s): """Wrapper to provide logging input string""" logger.debug('Sending %r', s) return super().send(s) def expect_list(self, pattern_list, *args, **kwargs): """Wrapper to provide logging output string and expected patterns""" try: result = super().expect_list(pattern_list, *args, **kwargs) finally: self._log_output(pattern_list) return result def expect_exact(self, pattern_list, *args, **kwargs): """Wrapper to provide logging output string and expected patterns""" try: result = super().expect_exact(pattern_list, *args, **kwargs) finally: self._log_output(pattern_list) return result def get_last_output(self): """Return output consumed by last call to .expect*()""" output = self.before if isinstance(self.after, str): output += self.after return output def _log_output(self, expected): logger.debug('Output received: %r, expected: "%s", ', self.get_last_output(), expected) def __enter__(self): self.exit_checked = False return self def __exit__(self, exc_type, exc_val, exc_tb): exception_occurred = bool(exc_type) try: if not self.exit_checked: self.expect_exit(raiseonerr=not exception_occurred, ignore_remaining_output=exception_occurred) except TIMEOUT: if not exception_occurred: raise finally: if self.isalive(): logger.error('Command still active, terminating.') self.terminate(True)
5,561
Python
.py
132
32.583333
79
0.615982
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,317
config.py
freeipa_freeipa/ipatests/pytest_ipa/integration/config.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # Tomas Babej <tbabej@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Utilities for configuration of multi-master tests""" import logging import random import pytest import pytest_multihost.config from ipapython.dn import DN from ipalib.constants import MAX_DOMAIN_LEVEL class Config(pytest_multihost.config.Config): extra_init_args = { 'admin_name', 'admin_password', 'dirman_dn', 'dirman_password', 'nis_domain', 'ntp_server', 'ad_admin_name', 'ad_admin_password', 'dns_forwarder', 'domain_level', 'log_journal_since', 'fips_mode', 'token_name', 'token_password', 'token_library', } def __init__(self, **kwargs): kwargs.setdefault('test_dir', '/root/ipatests') super(Config, self).__init__(**kwargs) admin_password = kwargs.get('admin_password') or 'Secret123' self.admin_name = kwargs.get('admin_name') or 'admin' self.admin_password = admin_password self.dirman_dn = DN(kwargs.get('dirman_dn') or 'cn=Directory Manager') self.dirman_password = kwargs.get('dirman_password') or admin_password self.nis_domain = kwargs.get('nis_domain') or 'ipatest' self.ntp_server = str(kwargs.get('ntp_server') or ( '%s.pool.ntp.org' % random.randint(0, 3))) self.ad_admin_name = kwargs.get('ad_admin_name') or 'Administrator' self.ad_admin_password = kwargs.get('ad_admin_password') or 'Secret123' self.domain_level = kwargs.get('domain_level', MAX_DOMAIN_LEVEL) # 8.8.8.8 is probably the best-known public DNS self.dns_forwarder = kwargs.get('dns_forwarder') or '8.8.8.8' self.debug = False self.log_journal_since = kwargs.get('log_journal_since') or '-1h' if self.domain_level is None: self.domain_level = MAX_DOMAIN_LEVEL self.fips_mode = kwargs.get('fips_mode', False) self.token_name = kwargs.get('token_name', None) self.token_password = kwargs.get('token_password', None) self.token_library = kwargs.get('token_library', None) def get_domain_class(self): return Domain def get_logger(self, name): logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) return logger @property def ad_domains(self): return [d for d in self.domains if d.is_ad_type] def get_all_hosts(self): for domain in self.domains: for host in domain.hosts: yield host def get_all_ipa_hosts(self): for ipa_domain in (d for d in self.domains if d.is_ipa_type): for ipa_host in ipa_domain.hosts: yield ipa_host def to_dict(self): extra_args = self.extra_init_args - {'dirman_dn'} result = super(Config, self).to_dict(extra_args) result['dirman_dn'] = str(self.dirman_dn) return result @classmethod def from_env(cls, env): from .env_config import config_from_env # pylint: disable=cyclic-import return config_from_env(env) def to_env(self, **kwargs): from .env_config import config_to_env # pylint: disable=cyclic-import return config_to_env(self, **kwargs) def filter(self, descriptions): """Destructively filters hosts and orders domains to fit description By default make_multihost_fixture() skips a test case, when filter() returns a FilterError. Let's turn FilterError into a fatal error instead. """ try: super(Config, self).filter(descriptions) except pytest_multihost.config.FilterError as e: pytest.fail(str(e)) class Domain(pytest_multihost.config.Domain): """Configuration for an IPA / AD domain""" def __init__(self, config, name, domain_type): self.type = str(domain_type) self.config = config self.name = str(name) self.hosts = [] assert self.is_ipa_type or self.is_ad_type self.realm = self.name.upper() self.basedn = DN(*(('dc', p) for p in name.split('.'))) @property def is_ipa_type(self): return self.type == 'IPA' @property def is_ad_type(self): return self.type == 'AD' or self.type.startswith('AD_') @property def static_roles(self): # Specific roles for each domain type are hardcoded if self.type == 'IPA': return ('master', 'replica', 'client', 'other') elif self.type == 'AD': return ('ad',) elif self.type == 'AD_SUBDOMAIN': return ('ad_subdomain',) elif self.type == 'AD_TREEDOMAIN': return ('ad_treedomain',) else: raise LookupError(self.type) def get_host_class(self, host_dict): from .host import Host, WinHost # pylint: disable=cyclic-import if self.is_ipa_type: return Host elif self.is_ad_type: return WinHost else: raise LookupError(self.type) @property def master(self): return self.host_by_role('master') @property def masters(self): return self.hosts_by_role('master') @property def replicas(self): return self.hosts_by_role('replica') @property def clients(self): return self.hosts_by_role('client') @property def ads(self): return self.hosts_by_role('ad') @property def other_hosts(self): return self.hosts_by_role('other') @classmethod def from_env(cls, env, config, index, domain_type): from ipatests.pytest_ipa.integration.env_config import domain_from_env return domain_from_env(env, config, index, domain_type) def to_env(self, **kwargs): from ipatests.pytest_ipa.integration.env_config import domain_to_env return domain_to_env(self, **kwargs)
6,689
Python
.py
169
32.16568
80
0.639729
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,318
env_config.py
freeipa_freeipa/ipatests/pytest_ipa/integration/env_config.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # Tomas Babej <tbabej@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Support for configuring multihost testing via environment variables This is here to support tests configured for Beaker, such as the ones at https://github.com/freeipa/tests/ """ import os import json import collections from ipapython import ipautil from ipatests.pytest_ipa.integration.config import Config, Domain from ipalib.constants import MAX_DOMAIN_LEVEL TESTHOST_PREFIX = 'TESTHOST_' _SettingInfo = collections.namedtuple('Setting', 'name var_name default') _setting_infos = ( # Directory on which test-specific files will be stored, _SettingInfo('test_dir', 'IPATEST_DIR', '/root/ipatests'), # File with root's private RSA key for SSH (default: ~/.ssh/id_rsa) _SettingInfo('ssh_key_filename', 'IPA_ROOT_SSH_KEY', None), # SSH password for root (used if root_ssh_key_filename is not set) _SettingInfo('ssh_password', 'IPA_ROOT_SSH_PASSWORD', None), _SettingInfo('admin_name', 'ADMINID', 'admin'), _SettingInfo('admin_password', 'ADMINPW', 'Secret123'), _SettingInfo('dirman_dn', 'ROOTDN', 'cn=Directory Manager'), _SettingInfo('dirman_password', 'ROOTDNPWD', None), # 8.8.8.8 is probably the best-known public DNS _SettingInfo('dns_forwarder', 'DNSFORWARD', '8.8.8.8'), _SettingInfo('nis_domain', 'NISDOMAIN', 'ipatest'), _SettingInfo('ntp_server', 'NTPSERVER', None), _SettingInfo('ad_admin_name', 'ADADMINID', 'Administrator'), _SettingInfo('ad_admin_password', 'ADADMINPW', 'Secret123'), _SettingInfo('ipv6', 'IPv6SETUP', False), _SettingInfo('debug', 'IPADEBUG', False), _SettingInfo('domain_level', 'DOMAINLVL', MAX_DOMAIN_LEVEL), _SettingInfo('log_journal_since', 'LOG_JOURNAL_SINCE', '-1h'), # userspace FIPS mode _SettingInfo('fips_mode', 'IPA_FIPS_MODE', False), ) def get_global_config(env=None): """Create a test config from environment variables If env is None, uses os.environ; otherwise env is an environment dict. If IPATEST_YAML_CONFIG or IPATEST_JSON_CONFIG is set, configuration is read from the named file. For YAML, the PyYAML (python-yaml) library needs to be installed. Otherwise, configuration is read from various curiously named environment variables: See _setting_infos for test-wide settings MASTER_env1: FQDN of the master REPLICA_env1: space-separated FQDNs of the replicas CLIENT_env1: space-separated FQDNs of the clients AD_env1: space-separated FQDNs of the Active Directories OTHER_env1: space-separated FQDNs of other hosts (same for _env2, _env3, etc) BEAKERREPLICA1_IP_env1: IP address of replica 1 in env 1 (same for MASTER, CLIENT, or any extra defined ROLE) For each machine that should be accessible to tests via extra roles, the following environment variable is necessary: TESTHOST_<role>_env1: FQDN of the machine with the extra role <role> You can also optionally specify the IP address of the host: BEAKER<role>_IP_env1: IP address of the machine of the extra role The framework will try to resolve the hostname to its IP address if not passed via this environment variable. Also see env_normalize() for alternate variable names """ if env is None: env = os.environ env = dict(env) return config_from_env(env) def config_from_env(env): if 'IPATEST_YAML_CONFIG' in env: try: import yaml except ImportError as e: raise ImportError( "%s, please install PyYAML package to fix it" % e) with open(env['IPATEST_YAML_CONFIG']) as file: confdict = yaml.safe_load(file) return Config.from_dict(confdict) if 'IPATEST_JSON_CONFIG' in env: with open(env['IPATEST_JSON_CONFIG']) as file: confdict = json.load(file) return Config.from_dict(confdict) env_normalize(env) kwargs = {s.name: env.get(s.var_name, s.default) for s in _setting_infos} kwargs['domains'] = [] # $IPv6SETUP needs to be 'TRUE' to enable ipv6 if isinstance(kwargs['ipv6'], str): kwargs['ipv6'] = (kwargs['ipv6'].upper() == 'TRUE') config = Config(**kwargs) # Either IPA master or AD can define a domain domain_index = 1 while (env.get('MASTER_env%s' % domain_index) or env.get('AD_env%s' % domain_index) or env.get('AD_SUBDOMAIN_env%s' % domain_index) or env.get('AD_TREEDOMAIN_env%s' % domain_index)): if env.get('MASTER_env%s' % domain_index): # IPA domain takes precedence to AD domain in case of conflict config.domains.append(domain_from_env(env, config, domain_index, domain_type='IPA')) else: for domain_type in ('AD', 'AD_SUBDOMAIN', 'AD_TREEDOMAIN'): if env.get('%s_env%s' % (domain_type, domain_index)): config.domains.append( domain_from_env(env, config, domain_index, domain_type=domain_type)) break domain_index += 1 return config def config_to_env(config, simple=True): """Convert this test config into environment variables""" try: env = collections.OrderedDict() except AttributeError: # Older Python versions env = {} for setting in _setting_infos: value = getattr(config, setting.name) if value in (None, False): env[setting.var_name] = '' elif value is True: env[setting.var_name] = 'TRUE' else: env[setting.var_name] = str(value) for domain in config.domains: env_suffix = '_env%s' % (config.domains.index(domain) + 1) env['DOMAIN%s' % env_suffix] = domain.name env['RELM%s' % env_suffix] = domain.realm env['BASEDN%s' % env_suffix] = str(domain.basedn) for role in domain.roles: hosts = domain.hosts_by_role(role) prefix = ('' if role in domain.static_roles else TESTHOST_PREFIX) hostnames = ' '.join(h.hostname for h in hosts) env['%s%s%s' % (prefix, role.upper(), env_suffix)] = hostnames ext_hostnames = ' '.join(h.external_hostname for h in hosts) env['BEAKER%s%s' % (role.upper(), env_suffix)] = ext_hostnames ips = ' '.join(h.ip for h in hosts) env['BEAKER%s_IP%s' % (role.upper(), env_suffix)] = ips for i, host in enumerate(hosts, start=1): suffix = '%s%s' % (role.upper(), i) prefix = ('' if role in domain.static_roles else TESTHOST_PREFIX) ext_hostname = host.external_hostname env['%s%s%s' % (prefix, suffix, env_suffix)] = host.hostname env['BEAKER%s%s' % (suffix, env_suffix)] = ext_hostname env['BEAKER%s_IP%s' % (suffix, env_suffix)] = host.ip if simple: # Simple Vars for simplicity and backwards compatibility with older # tests. This means no _env<NUM> suffix. if config.domains: default_domain = config.domains[0] if default_domain.master: env['MASTER'] = default_domain.master.hostname env['BEAKERMASTER'] = default_domain.master.external_hostname env['MASTERIP'] = default_domain.master.ip if default_domain.replicas: env['SLAVE'] = env['REPLICA'] = env['REPLICA_env1'] env['BEAKERSLAVE'] = env['BEAKERREPLICA_env1'] env['SLAVEIP'] = env['BEAKERREPLICA_IP_env1'] if default_domain.clients: client = default_domain.clients[0] env['CLIENT'] = client.hostname env['BEAKERCLIENT'] = client.external_hostname if len(default_domain.clients) >= 2: client = default_domain.clients[1] env['CLIENT2'] = client.hostname env['BEAKERCLIENT2'] = client.external_hostname return env def env_normalize(env): """Fill env variables from alternate variable names MASTER_env1 <- MASTER REPLICA_env1 <- REPLICA, SLAVE CLIENT_env1 <- CLIENT similarly for BEAKER* variants: BEAKERMASTER1_env1 <- BEAKERMASTER, etc. CLIENT_env1 gets extended with CLIENT2 or CLIENT2_env1 """ def coalesce(name, *other_names): """If name is not set, set it to first existing env[other_name]""" if name not in env: for other_name in other_names: try: env[name] = env[other_name] except KeyError: pass else: return env[name] = '' coalesce('MASTER_env1', 'MASTER') coalesce('REPLICA_env1', 'REPLICA', 'SLAVE') coalesce('CLIENT_env1', 'CLIENT') coalesce('BEAKERMASTER1_env1', 'BEAKERMASTER') coalesce('BEAKERREPLICA1_env1', 'BEAKERREPLICA', 'BEAKERSLAVE') coalesce('BEAKERCLIENT1_env1', 'BEAKERCLIENT') def extend(name, name2): value = env.get(name2) if value and value not in env[name].split(' '): env[name] += ' ' + value extend('CLIENT_env1', 'CLIENT2') extend('CLIENT_env1', 'CLIENT2_env1') def domain_from_env(env, config, index, domain_type): # Roles available in the domain depend on the type of the domain # Unix machines are added only to the IPA domains, Windows machines # only to the AD domains if domain_type == 'IPA': master_role = 'MASTER' else: master_role = domain_type env_suffix = '_env%s' % index master_env = '%s%s' % (master_role, env_suffix) hostname, _dot, domain_name = env[master_env].partition('.') domain = Domain(config, domain_name, domain_type) for role in _roles_from_env(domain, env, env_suffix): prefix = '' if role in domain.static_roles else TESTHOST_PREFIX value = env.get('%s%s%s' % (prefix, role.upper(), env_suffix), '') for host_index, hostname in enumerate(value.split(), start=1): host = host_from_env(env, domain, hostname, role, host_index, index) domain.hosts.append(host) if not domain.hosts: raise ValueError('No hosts defined for %s' % env_suffix) return domain def _roles_from_env(domain, env, env_suffix): for role in domain.static_roles: yield role # Extra roles are defined via env variables of form TESTHOST_key_envX roles = set() for var in sorted(env): if var.startswith(TESTHOST_PREFIX) and var.endswith(env_suffix): variable_split = var.split('_') role_name = '_'.join(variable_split[1:-1]) if (role_name and not role_name[-1].isdigit()): roles.add(role_name.lower()) for role in sorted(roles): yield role def domain_to_env(domain, **kwargs): """Return environment variables specific to this domain""" env = domain.config.to_env(**kwargs) env['DOMAIN'] = domain.name env['RELM'] = domain.realm env['BASEDN'] = str(domain.basedn) return env def host_from_env(env, domain, hostname, role, index, domain_index): ip = env.get('BEAKER%s%s_IP_env%s' % (role.upper(), index, domain_index), None) external_hostname = env.get( 'BEAKER%s%s_env%s' % (role.upper(), index, domain_index), None) cls = domain.get_host_class({}) return cls(domain, hostname, role, ip=ip, external_hostname=external_hostname) def host_to_env(host, **kwargs): """Return environment variables specific to this host""" env = host.domain.to_env(**kwargs) index = host.domain.hosts.index(host) + 1 domain_index = host.config.domains.index(host.domain) + 1 role = host.role.upper() if host.role != 'master': role += str(index) env['MYHOSTNAME'] = host.hostname env['MYBEAKERHOSTNAME'] = host.external_hostname env['MYIP'] = host.ip prefix = ('' if host.role in host.domain.static_roles else TESTHOST_PREFIX) env_suffix = '_env%s' % domain_index env['MYROLE'] = '%s%s%s' % (prefix, role, env_suffix) env['MYENV'] = str(domain_index) return env def env_to_script(env): return ''.join(['export %s=%s\n' % (key, ipautil.shell_quote(value)) for key, value in env.items()])
13,361
Python
.py
288
37.909722
77
0.631429
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,319
transport.py
freeipa_freeipa/ipatests/pytest_ipa/integration/transport.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """Enhanced SSH transport for pytest multihost Provides SSH password login for OpenSSH transport """ import os from .expect import IpaTestExpect from pytest_multihost.transport import OpenSSHTransport class IPAOpenSSHTransport(OpenSSHTransport): def _get_ssh_argv(self): """Return the path to SSH and options needed for every call""" control_file = os.path.join(self.control_dir.path, "control") known_hosts_file = os.path.join(self.control_dir.path, "known_hosts") argv = [ "ssh", "-l", self.host.ssh_username, "-o", "ControlPath=%s" % control_file, "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=%s" % known_hosts_file, ] if self.host.ssh_key_filename: key_filename = os.path.expanduser(self.host.ssh_key_filename) argv.extend(["-i", key_filename]) elif self.host.ssh_password: password_file = os.path.join(self.control_dir.path, "password") with open(password_file, "w") as f: os.fchmod(f.fileno(), 0o600) f.write(self.host.ssh_password) f.write("\n") argv = ["sshpass", f"-f{password_file}"] + argv else: self.log.critical("No SSH credentials configured") raise RuntimeError("No SSH credentials configured") argv.append(self.host.external_hostname) self.log.debug("SSH invocation: %s", argv) return argv def spawn_expect(self, argv, default_timeout, encoding, extra_ssh_options): self.log.debug('Starting pexpect ssh session') if isinstance(argv, str): argv = [argv] if extra_ssh_options is None: extra_ssh_options = [] argv = self._get_ssh_argv() + ['-q'] + extra_ssh_options + argv return IpaTestExpect(argv, default_timeout, encoding)
2,036
Python
.py
49
32.183673
79
0.611027
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,320
tasks.py
freeipa_freeipa/ipatests/pytest_ipa/integration/tasks.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Common tasks for FreeIPA integration tests""" from __future__ import absolute_import import logging import os from io import StringIO import textwrap import re import collections import itertools import shutil import copy import subprocess import tempfile import time from shlex import quote import configparser from contextlib import contextmanager from pkg_resources import parse_version import uuid import dns from ldif import LDIFWriter import pytest from cryptography import x509 from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.backends import default_backend from datetime import datetime, timedelta from ipapython import certdb from ipapython import ipautil from ipapython.dnsutil import DNSResolver from ipaplatform.paths import paths from ipaplatform.services import knownservices from ipapython.dn import DN from ipalib import errors from ipalib.util import get_reverse_zone_default from ipalib.constants import ( DEFAULT_CONFIG, DOMAIN_SUFFIX_NAME, DOMAIN_LEVEL_0, MIN_DOMAIN_LEVEL, MAX_DOMAIN_LEVEL ) from ipatests.create_external_ca import ExternalCA from .env_config import env_to_script from .host import Host from .firewall import Firewall from .resolver import ResolvedResolver from .fips import is_fips_enabled, enable_crypto_subpolicy logger = logging.getLogger(__name__) def check_arguments_are(slice, instanceof): """ :param: slice - tuple of integers denoting the beginning and the end of argument list to be checked :param: instanceof - name of the class the checked arguments should be instances of Example: @check_arguments_are((1, 3), int) will check that the second and third arguments are integers """ def wrapper(func): def wrapped(*args, **kwargs): for i in args[slice[0]:slice[1]]: assert isinstance(i, instanceof), "Wrong type: %s: %s" % ( i, type(i)) return func(*args, **kwargs) return wrapped return wrapper def prepare_reverse_zone(host, ip): zone = get_reverse_zone_default(ip) result = host.run_command( ["ipa", "dnszone-add", zone, '--skip-overlap-check'], raiseonerr=False ) if result.returncode > 0: logger.warning("%s", result.stderr_text) return zone, result.returncode def prepare_host(host): if isinstance(host, Host): env_filename = os.path.join(host.config.test_dir, 'env.sh') # First we try to run simple echo command to test the connection host.run_command(['true'], set_env=False) try: host.transport.mkdir_recursive(host.config.test_dir) except IOError: # The folder already exists pass host.put_file_contents(env_filename, env_to_script(host.to_env())) def rpcbind_kadmin_workaround(host): """Restart rpcbind in case it blocks 749/TCP, 464/UDP, or 464/TCP See https://pagure.io/freeipa/issue/7769 See https://bugzilla.redhat.com/show_bug.cgi?id=1592883 """ cmd = [ 'ss', '--all', # listening and non-listening sockets '--tcp', '--udp', # only TCP and UDP sockets '--numeric', # don't resolve host and service names '--processes', # show processes ] # run once to list all ports for debugging host.run_command(cmd) # check for blocked kadmin port cmd.extend(( '-o', 'state', 'all', # ports in any state, not just listening '( sport = :749 or dport = :749 or sport = :464 or dport = :464 )' )) for _i in range(5): result = host.run_command(cmd) if 'rpcbind' in result.stdout_text: logger.error("rpcbind blocks 749, restarting") host.run_command(['systemctl', 'restart', 'rpcbind.service']) time.sleep(2) else: break def disable_systemd_resolved_cache(host): if not ResolvedResolver.is_our_resolver(host): return resolved_conf_file = ( '/etc/systemd/resolved.conf.d/zzzz-ipatests-disable-cache.conf') resolved_conf = textwrap.dedent(''' # generated by IPA tests [Resolve] Cache=no ''') host.run_command(['mkdir', '-p', os.path.dirname(resolved_conf_file)]) host.put_file_contents(resolved_conf_file, resolved_conf) host.run_command(['systemctl', 'restart', 'systemd-resolved']) def apply_common_fixes(host): prepare_host(host) fix_hostname(host) rpcbind_kadmin_workaround(host) disable_systemd_resolved_cache(host) def prepare_dse_changes(host, log_level=8192): """Put custom changes for dse.ldif on the host """ ipatests_dse_path = os.path.join(host.config.test_dir, "ipatests_dse.ldif") ldif = textwrap.dedent( """\ # replication debugging dn: cn=config changetype: modify replace: nsslapd-errorlog-level nsslapd-errorlog-level: {log_level} # server writes all access log entries directly to disk dn: cn=config changetype: modify replace: nsslapd-accesslog-logbuffering nsslapd-accesslog-logbuffering: off """ ).format(log_level=log_level) host.put_file_contents(ipatests_dse_path, ldif) return ipatests_dse_path def allow_sync_ptr(host): kinit_admin(host) host.run_command(["ipa", "dnsconfig-mod", "--allow-sync-ptr=true"], raiseonerr=False) def backup_file(host, filename): if host.transport.file_exists(filename): backupname = os.path.join(host.config.test_dir, 'file_backup', filename.lstrip('/')) host.transport.mkdir_recursive(os.path.dirname(backupname)) host.run_command(['cp', '-af', filename, backupname]) return True else: rmname = os.path.join(host.config.test_dir, 'file_remove') host.run_command('echo %s >> %s' % ( ipautil.shell_quote(filename), ipautil.shell_quote(rmname))) host.transport.mkdir_recursive(os.path.dirname(rmname)) return False def fix_hostname(host): backup_file(host, paths.ETC_HOSTNAME) host.put_file_contents(paths.ETC_HOSTNAME, host.hostname + '\n') host.run_command(['hostname', host.hostname]) backupname = os.path.join(host.config.test_dir, 'backup_hostname') host.run_command('hostname > %s' % ipautil.shell_quote(backupname)) def host_service_active(host, service): res = host.run_command(['systemctl', 'is-active', '--quiet', service], raiseonerr=False) return res.returncode == 0 def fix_apache_semaphores(master): systemd_available = master.transport.file_exists(paths.SYSTEMCTL) if systemd_available: master.run_command(['systemctl', 'stop', 'httpd'], raiseonerr=False) else: master.run_command([paths.SBIN_SERVICE, 'httpd', 'stop'], raiseonerr=False) master.run_command( 'for line in `ipcs -s | grep apache ''| cut -d " " -f 2`; ' + 'do ipcrm -s $line; done', raiseonerr=False ) def unapply_fixes(host): restore_files(host) restore_hostname(host) # Clean ccache to prevent issues like 5741 host.run_command(['kdestroy', '-A'], raiseonerr=False) # Clean up the test directory host.run_command(['rm', '-rvf', host.config.test_dir]) def restore_files(host): backupname = os.path.join(host.config.test_dir, 'file_backup') rmname = os.path.join(host.config.test_dir, 'file_remove') # Prepare command for restoring context of the backed-up files sed_remove_backupdir = 's/%s//g' % backupname.replace('/', r'\/') restorecon_command = ( "find %s | " "sed '%s' | " "sed '/^$/d' | " "xargs -d '\n' " "/sbin/restorecon -v" % (backupname, sed_remove_backupdir)) # Prepare command for actual restoring of the backed up files copyfiles_command = 'if [ -d %(dir)s/ ]; then cp -arvf %(dir)s/* /; fi' % { 'dir': ipautil.shell_quote(backupname)} # Run both commands in one session. For more information, see: # https://fedorahosted.org/freeipa/ticket/4133 host.run_command('%s ; (%s ||:)' % (copyfiles_command, restorecon_command)) # Remove all the files that did not exist and were 'backed up' host.run_command(['xargs', '-d', r'\n', '-a', rmname, 'rm', '-vf'], raiseonerr=False) host.run_command(['rm', '-rvf', backupname, rmname], raiseonerr=False) def restore_hostname(host): backupname = os.path.join(host.config.test_dir, 'backup_hostname') try: hostname = host.get_file_contents(backupname, encoding='utf-8') except IOError: logger.debug('No hostname backed up on %s', host.hostname) else: host.run_command(['hostname', hostname.strip()]) host.run_command(['rm', backupname]) def enable_ds_audit_log(host, enabled='on'): """Enable 389-ds audit log and auditfail log :param host: the host on which audit log is configured :param enabled: a string (either 'on' or 'off') """ logger.info('Set LDAP audit log') logging_ldif = textwrap.dedent(""" dn: cn=config changetype: modify replace: nsslapd-auditlog-logging-enabled nsslapd-auditlog-logging-enabled: {enabled} - replace: nsslapd-auditfaillog-logging-enabled nsslapd-auditfaillog-logging-enabled: {enabled} """.format(enabled=enabled)) ldapmodify_dm(host, logging_ldif) def set_default_ttl_for_ipa_dns_zone(host, raiseonerr=True): args = [ 'ipa', 'dnszone-mod', host.domain.name, '--default-ttl', '1', '--ttl', '1' ] result = host.run_command(args, raiseonerr=raiseonerr, stdin_text=None) if result.returncode != 0: logger.info('Failed to set TTL and default TTL for DNS zone %s to 1', host.domain.name) def install_master(host, setup_dns=True, setup_kra=False, setup_adtrust=False, extra_args=(), domain_level=None, unattended=True, external_ca=False, stdin_text=None, raiseonerr=True, random_serial=False): if domain_level is None: domain_level = host.config.domain_level check_domain_level(domain_level) apply_common_fixes(host) if "--dirsrv-config-file" not in extra_args: ipatests_dse = prepare_dse_changes(host) else: ipatests_dse = None fix_apache_semaphores(host) fw = Firewall(host) fw_services = ["freeipa-ldap", "freeipa-ldaps"] args = [ 'ipa-server-install', '-n', host.domain.name, '-r', host.domain.realm, '-p', host.config.dirman_password, '-a', host.config.admin_password, "--domain-level=%i" % domain_level, ] if random_serial: args.append('--random-serial-numbers') if ipatests_dse: args.extend(["--dirsrv-config-file", ipatests_dse]) if unattended: args.append('-U') if setup_dns: args.extend([ '--setup-dns', '--forwarder', host.config.dns_forwarder, '--auto-reverse' ]) fw_services.append("dns") if setup_kra: args.append('--setup-kra') if setup_adtrust: args.append('--setup-adtrust') fw_services.append("freeipa-trust") if is_fips_enabled(host): enable_crypto_subpolicy(host, "AD-SUPPORT") if external_ca: args.append('--external-ca') args.extend(extra_args) result = host.run_command(args, raiseonerr=raiseonerr, stdin_text=stdin_text) if result.returncode == 0: fw.enable_services(fw_services) if result.returncode == 0 and not external_ca: # external CA step 1 doesn't have DS and KDC fully configured, yet enable_ds_audit_log(host, 'on') setup_sssd_conf(host) kinit_admin(host) if setup_dns: setup_named_debugging(host) # fixup DNS zone default TTL for IPA DNS zone # For tests we should not wait too long set_default_ttl_for_ipa_dns_zone(host, raiseonerr=raiseonerr) return result def check_domain_level(domain_level): if domain_level < MIN_DOMAIN_LEVEL: pytest.fail( "Domain level {} not supported, min level is {}.".format( domain_level, MIN_DOMAIN_LEVEL) ) if domain_level > MAX_DOMAIN_LEVEL: pytest.fail( "Domain level {} not supported, max level is {}.".format( domain_level, MAX_DOMAIN_LEVEL) ) def domainlevel(host): """ Dynamically determines the domainlevel on master. Needed for scenarios when domainlevel is changed during the test execution. Sometimes the master is even not installed. Please refer to ca-less tests, where we call tasks.uninstall_master after every test while a lot of them make sure that the server installation fails. Therefore we need to not raise on failures here. """ kinit_admin(host, raiseonerr=False) result = host.run_command(['ipa', 'domainlevel-get'], raiseonerr=False) level = MIN_DOMAIN_LEVEL domlevel_re = re.compile(r'.*(\d)') if result.returncode == 0: # "domainlevel-get" command doesn't exist on ipa versions prior to 4.3 level = int(domlevel_re.findall(result.stdout_text)[0]) check_domain_level(level) return level def master_authoritative_for_client_domain(master, client): zone = ".".join(client.hostname.split('.')[1:]) result = master.run_command(["ipa", "dnszone-show", zone], raiseonerr=False) return result.returncode == 0 def copy_nfast_data(src_host, dest_host): src_host.run_command( ['tar', '-cf', '/root/token_files.tar', '.'], cwd='/opt/nfast/kmdata/local/' ) tarball = src_host.get_file_contents('/root/token_files.tar') dest_host.put_file_contents('/root/token_files.tar', tarball) dest_host.run_command( ['tar', '-xf', '/root/token_files.tar', '-C', '/opt/nfast/kmdata/local'] ) def install_replica(master, replica, setup_ca=True, setup_dns=False, setup_kra=False, setup_adtrust=False, extra_args=(), domain_level=None, unattended=True, stdin_text=None, raiseonerr=True, promote=True, nameservers='master'): """ This task installs client and then promote it to the replica :param nameservers: nameservers to write in resolver config. Possible values: * "master" - use ip of `master` parameter * None - do not setup resolver * IP_ADDRESS or [IP_ADDRESS, ...] - use this address as resolver """ replica_args = list(extra_args) # needed for client's ntp options if domain_level is None: domain_level = domainlevel(master) check_domain_level(domain_level) apply_common_fixes(replica) if "--dirsrv-config-file" not in extra_args: ipatests_dse = prepare_dse_changes(replica) else: ipatests_dse = None allow_sync_ptr(master) fw = Firewall(replica) fw_services = ["freeipa-ldap", "freeipa-ldaps"] # Otherwise ipa-client-install would not create a PTR # and replica installation would fail args = ['ipa-replica-install', '--admin-password', replica.config.admin_password] if promote: # while promoting we use directory manager password args.extend(['--password', replica.config.dirman_password]) # install client on a replica machine and then promote it to replica # to configure ntp options we have to pass them to client installation # because promotion does not support NTP options ntp_args = [arg for arg in replica_args if "-ntp" in arg] for ntp_arg in ntp_args: replica_args.remove(ntp_arg) install_client(master, replica, extra_args=ntp_args, nameservers=nameservers) else: # for one step installation of replica we need authorized user # to enroll a replica and master server to contact args.extend(['--principal', replica.config.admin_name, '--server', master.hostname]) replica.resolver.backup() if nameservers is not None: if nameservers == 'master': nameservers = master.ip replica.resolver.setup_resolver(nameservers, master.domain.name) if unattended: args.append('-U') if setup_ca: args.append('--setup-ca') if setup_kra: assert setup_ca, "CA must be installed on replica with KRA" args.append('--setup-kra') if setup_dns: args.extend([ '--setup-dns', '--forwarder', replica.config.dns_forwarder ]) fw_services.append("dns") if setup_adtrust: args.append('--setup-adtrust') fw_services.append("freeipa-trust") if is_fips_enabled(replica): enable_crypto_subpolicy(replica, "AD-SUPPORT") if master_authoritative_for_client_domain(master, replica): args.extend(['--ip-address', replica.ip]) args.extend(replica_args) # append extra arguments to installation fix_apache_semaphores(replica) args.extend(['--realm', replica.domain.realm, '--domain', replica.domain.name]) if ipatests_dse: args.extend(["--dirsrv-config-file", ipatests_dse]) fw.enable_services(fw_services) result = replica.run_command(args, raiseonerr=raiseonerr, stdin_text=stdin_text) if result.returncode == 0: enable_ds_audit_log(replica, 'on') setup_sssd_conf(replica) kinit_admin(replica) if setup_dns: setup_named_debugging(replica) else: fw.disable_services(fw_services) return result def install_client(master, client, extra_args=[], user=None, password=None, pkinit_identity=None, unattended=True, stdin_text=None, nameservers='master'): """ :param nameservers: nameservers to write in resolver config. Possible values: * "master" - use ip of `master` parameter * None - do not setup resolver * IP_ADDRESS or [IP_ADDRESS, ...] - use this address as resolver """ apply_common_fixes(client) allow_sync_ptr(master) # Now, for the situations where a client resides in a different subnet from # master, we need to explicitly tell master to create a reverse zone for # the client and enable dynamic updates for this zone. zone, error = prepare_reverse_zone(master, client.ip) if not error: master.run_command(["ipa", "dnszone-mod", zone, "--dynamic-update=TRUE"]) if nameservers is not None: client.resolver.backup() if nameservers == 'master': nameservers = master.ip client.resolver.setup_resolver(nameservers, master.domain.name) args = [ 'ipa-client-install', '--domain', client.domain.name, '--realm', client.domain.realm, '--server', master.hostname ] if pkinit_identity: args.extend(["--pkinit-identity", pkinit_identity]) else: if user is None: user = client.config.admin_name if password is None: password = client.config.admin_password args.extend(['-p', user, '-w', password]) if unattended: args.append('-U') args.extend(extra_args) if is_fips_enabled(client) and getattr(master.config, 'ad_domains', False): enable_crypto_subpolicy(client, "AD-SUPPORT") result = client.run_command(args, stdin_text=stdin_text) setup_sssd_conf(client) kinit_admin(client) return result def install_adtrust(host): """ Runs ipa-adtrust-install on the client and generates SIDs for the entries. Configures the compat tree for the legacy clients. """ kinit_admin(host) if is_fips_enabled(host): enable_crypto_subpolicy(host, "AD-SUPPORT") host.run_command(['ipa-adtrust-install', '-U', '--enable-compat', '--netbios-name', host.netbios, '-a', host.config.admin_password, '--add-sids']) host.run_command(['net', 'conf', 'setparm', 'global', 'log level', '10']) Firewall(host).enable_service("freeipa-trust") # Restart named because it lost connection to dirsrv # (Directory server restarts during the ipa-adtrust-install) host.run_command(['systemctl', 'restart', knownservices.named.systemd_name]) # Check that named is running and has loaded the information from LDAP dig_command = ['dig', 'SRV', '+short', '@localhost', '_ldap._tcp.%s' % host.domain.name] dig_output = '0 100 389 %s.' % host.hostname def dig_test(x): return re.search(re.escape(dig_output), x) run_repeatedly(host, dig_command, test=dig_test) def disable_dnssec_validation(host): """ Edits ipa-options-ext.conf snippet in order to disable dnssec validation """ backup_file(host, paths.NAMED_CUSTOM_OPTIONS_CONF) named_conf = host.get_file_contents(paths.NAMED_CUSTOM_OPTIONS_CONF) named_conf = re.sub(br'dnssec-validation\s*yes;', b'dnssec-validation no;', named_conf) host.put_file_contents(paths.NAMED_CUSTOM_OPTIONS_CONF, named_conf) restart_named(host) def restore_dnssec_validation(host): restore_files(host) restart_named(host) def is_subdomain(subdomain, domain): subdomain_unpacked = subdomain.split('.') domain_unpacked = domain.split('.') subdomain_unpacked.reverse() domain_unpacked.reverse() subdomain = False if len(subdomain_unpacked) > len(domain_unpacked): subdomain = True for subdomain_segment, domain_segment in zip(subdomain_unpacked, domain_unpacked): subdomain = subdomain and subdomain_segment == domain_segment return subdomain def configure_dns_for_trust(master, *ad_hosts): """ This configures DNS on IPA master according to the relationship of the IPA's and AD's domains. """ kinit_admin(master) dnssec_disabled = False for ad in ad_hosts: if is_subdomain(ad.domain.name, master.domain.name): master.run_command(['ipa', 'dnsrecord-add', master.domain.name, '%s.%s' % (ad.shortname, ad.netbios), '--a-ip-address', ad.ip]) master.run_command(['ipa', 'dnsrecord-add', master.domain.name, ad.netbios, '--ns-hostname', '%s.%s' % (ad.shortname, ad.netbios)]) master.run_command(['ipa', 'dnszone-mod', master.domain.name, '--allow-transfer', ad.ip]) else: if not dnssec_disabled: disable_dnssec_validation(master) dnssec_disabled = True master.run_command(['ipa', 'dnsforwardzone-add', ad.domain.name, '--forwarder', ad.ip, '--forward-policy', 'only', ]) def unconfigure_dns_for_trust(master, *ad_hosts): """ This undoes changes made by configure_dns_for_trust """ kinit_admin(master) dnssec_needs_restore = False for ad in ad_hosts: if is_subdomain(ad.domain.name, master.domain.name): master.run_command(['ipa', 'dnsrecord-del', master.domain.name, '%s.%s' % (ad.shortname, ad.netbios), '--a-rec', ad.ip]) master.run_command(['ipa', 'dnsrecord-del', master.domain.name, ad.netbios, '--ns-rec', '%s.%s' % (ad.shortname, ad.netbios)]) else: master.run_command(['ipa', 'dnsforwardzone-del', ad.domain.name]) dnssec_needs_restore = True if dnssec_needs_restore: restore_dnssec_validation(master) def configure_windows_dns_for_trust(ad, master): ad.run_command(['dnscmd', '/zoneadd', master.domain.name, '/Forwarder', master.ip]) def unconfigure_windows_dns_for_trust(ad, master): ad.run_command(['dnscmd', '/zonedelete', master.domain.name, '/f']) def establish_trust_with_ad(master, ad_domain, ad_admin=None, extra_args=(), shared_secret=None): """ Establishes trust with Active Directory. Trust type is detected depending on the presence of SfU (Services for Unix) support on the AD. Use extra arguments to pass extra arguments to the trust-add command, such as --range-type="ipa-ad-trust" to enforce a particular range type. If ad_admin is not provided, name will be constructed as "Administrator@<ad_domain>". """ # Force KDC to reload MS-PAC info by trying to get TGT for HTTP extra_args = list(extra_args) master.run_command(['kinit', '-kt', paths.HTTP_KEYTAB, 'HTTP/%s' % master.hostname]) master.run_command(['systemctl', 'restart', 'krb5kdc.service']) master.run_command(['kdestroy', '-A']) kinit_admin(master) master.run_command(['klist']) master.run_command(['smbcontrol', 'all', 'debug', '100']) if shared_secret: extra_args += ['--trust-secret'] stdin_text = shared_secret else: if ad_admin is None: ad_admin = 'Administrator@{}'.format(ad_domain) extra_args += ['--admin', ad_admin, '--password'] stdin_text = master.config.ad_admin_password run_repeatedly( master, ['ipa', 'trust-add', '--type', 'ad', ad_domain] + extra_args, stdin_text=stdin_text) master.run_command(['smbcontrol', 'all', 'debug', '1']) clear_sssd_cache(master) master.run_command(['systemctl', 'restart', 'krb5kdc.service']) time.sleep(60) def remove_trust_with_ad(master, ad_domain, ad_hostname): """ Removes trust with Active Directory. Also removes the associated ID range. """ remove_trust_info_from_ad(master, ad_domain, ad_hostname) kinit_admin(master) # Remove the trust master.run_command(['ipa', 'trust-del', ad_domain]) # Remove the range range_name = ad_domain.upper() + '_id_range' master.run_command(['ipa', 'idrange-del', range_name]) def remove_trust_info_from_ad(master, ad_domain, ad_hostname): # Remove record about trust from AD kinit_as_user(master, 'Administrator@{}'.format(ad_domain.upper()), master.config.ad_admin_password) # Find cache for the user cache_args = [] cache = get_credential_cache(master) if cache: cache_args = ["--use-krb5-ccache", cache] # Detect whether rpcclient supports -k or --use-kerberos option res = master.run_command(['rpcclient', '-h'], raiseonerr=False) if "--use-kerberos" in res.stderr_text: rpcclient_krb5_knob = "--use-kerberos=desired" else: rpcclient_krb5_knob = "-k" cmd_args = ['rpcclient', rpcclient_krb5_knob, ad_hostname] cmd_args.extend(cache_args) cmd_args.extend(['-c', 'deletetrustdom {}'.format(master.domain.name)]) master.run_command(cmd_args, raiseonerr=False) def configure_auth_to_local_rule(master, ad): """ Configures auth_to_local rule in /etc/krb5.conf """ section_identifier = " %s = {" % master.domain.realm line1 = (" auth_to_local = RULE:[1:$1@$0](^.*@%s$)s/@%s/@%s/" % (ad.domain.realm, ad.domain.realm, ad.domain.name)) line2 = " auth_to_local = DEFAULT" krb5_conf_content = master.get_file_contents(paths.KRB5_CONF) krb5_lines = [line.rstrip() for line in krb5_conf_content.split('\n')] realm_section_index = krb5_lines.index(section_identifier) krb5_lines.insert(realm_section_index + 1, line1) krb5_lines.insert(realm_section_index + 2, line2) krb5_conf_new_content = '\n'.join(krb5_lines) master.put_file_contents(paths.KRB5_CONF, krb5_conf_new_content) master.run_command(['systemctl', 'restart', 'sssd']) def setup_sssd_conf(host): """ Configures sssd """ # sssd in not published on PyPI from SSSDConfig import NoOptionError with remote_sssd_config(host) as sssd_config: # sssd 2.5.0 https://github.com/SSSD/sssd/issues/5635 try: sssd_config.edit_domain(host.domain, "ldap_sudo_random_offset", 0) except NoOptionError: # sssd doesn't support ldap_sudo_random_offset pass for sssd_service_name in sssd_config.list_services(): sssd_config.edit_service(sssd_service_name, "debug_level", 7) for sssd_domain_name in sssd_config.list_domains(): sssd_config.edit_domain(sssd_domain_name, "debug_level", 7) # Clear the cache and restart SSSD clear_sssd_cache(host) def setup_named_debugging(host): """ Sets debug level to debug in each section of custom logging config """ host.run_command( [ "sed", "-i", "s/severity info;/severity debug;/", paths.NAMED_LOGGING_OPTIONS_CONF, ], ) host.run_command(["cat", paths.NAMED_LOGGING_OPTIONS_CONF]) result = host.run_command( [ "python3", "-c", ( "from ipaplatform.services import knownservices; " "print(knownservices.named.systemd_name)" ), ] ) service_name = result.stdout_text.strip() host.run_command(["systemctl", "restart", service_name]) @contextmanager def remote_sssd_config(host): """Context manager for editing sssd config file on a remote host. It provides SimpleSSSDConfig object which is automatically serialized and uploaded to remote host upon exit from the context. If exception is raised inside the context then the ini file is NOT updated on remote host. SimpleSSSDConfig is a SSSDConfig descendant with added helper methods for modifying options: edit_domain and edit_service. Example: with remote_sssd_config(master) as sssd_conf: # use helper methods # add/replace option sssd_conf.edit_domain(master.domain, 'filter_users', 'root') # add/replace provider option sssd_conf.edit_domain(master.domain, 'sudo_provider', 'ipa') # delete option sssd_conf.edit_service('pam', 'pam_verbosity', None) # use original methods of SSSDConfig domain = sssd_conf.get_domain(master.domain.name) domain.set_name('example.test') self.save_domain(domain) """ from SSSDConfig import SSSDConfig class SimpleSSSDConfig(SSSDConfig): def edit_domain(self, domain_or_name, option, value): """Add/replace/delete option in a domain section. :param domain_or_name: Domain object or domain name :param option: option name :param value: value to assign to option. If None, option will be deleted """ if hasattr(domain_or_name, 'name'): domain_name = domain_or_name.name else: domain_name = domain_or_name domain = self.get_domain(domain_name) if value is None: domain.remove_option(option) else: domain.set_option(option, value) self.save_domain(domain) def edit_service(self, service_name, option, value): """Add/replace/delete option in a service section. :param service_name: a string :param option: option name :param value: value to assign to option. If None, option will be deleted """ service = self.get_service(service_name) if value is None: service.remove_option(option) else: service.set_option(option, value) self.save_service(service) fd, temp_config_file = tempfile.mkstemp() os.close(fd) try: current_config = host.transport.get_file_contents(paths.SSSD_CONF) with open(temp_config_file, 'wb') as f: f.write(current_config) # In order to use SSSDConfig() locally we need to import the schema # Create a tar file with /usr/share/sssd.api.conf and # /usr/share/sssd/sssd.api.d tmpname = create_temp_file(host) host.run_command( ['tar', 'cJvf', tmpname, 'sssd.api.conf', 'sssd.api.d'], log_stdout=False, cwd="/usr/share/sssd") # fetch tar file tar_dir = tempfile.mkdtemp() tarname = os.path.join(tar_dir, "sssd_schema.tar.xz") with open(tarname, 'wb') as f: f.write(host.get_file_contents(tmpname)) # delete from remote host.run_command(['rm', '-f', tmpname]) # Unpack on the local side ipautil.run([paths.TAR, 'xJvf', tarname], cwd=tar_dir) os.unlink(tarname) # Use the imported schema sssd_config = SimpleSSSDConfig( schemafile=os.path.join(tar_dir, "sssd.api.conf"), schemaplugindir=os.path.join(tar_dir, "sssd.api.d")) sssd_config.import_config(temp_config_file) yield sssd_config new_config = sssd_config.dump(sssd_config.opts).encode('utf-8') host.transport.put_file_contents(paths.SSSD_CONF, new_config) finally: try: os.remove(temp_config_file) shutil.rmtree(tar_dir) except OSError: pass def clear_sssd_cache(host): """ Clears SSSD cache by removing the cache files. Restarts SSSD. """ systemd_available = host.transport.file_exists(paths.SYSTEMCTL) if systemd_available: host.run_command(['systemctl', 'stop', 'sssd']) else: host.run_command([paths.SBIN_SERVICE, 'sssd', 'stop']) host.run_command("find /var/lib/sss/db -name '*.ldb' | " "xargs rm -fv") host.run_command(['rm', '-fv', paths.SSSD_MC_GROUP]) host.run_command(['rm', '-fv', paths.SSSD_MC_PASSWD]) host.run_command(['rm', '-fv', paths.SSSD_MC_INITGROUPS]) if systemd_available: host.run_command(['systemctl', 'start', 'sssd']) else: host.run_command([paths.SBIN_SERVICE, 'sssd', 'start']) # To avoid false negatives due to SSSD not responding yet time.sleep(10) def sync_time(host, server): """ Syncs the time with the remote server. Please note that this function leaves chronyd stopped. """ host.run_command(['systemctl', 'stop', 'chronyd']) host.run_command(['chronyd', '-q', "server {srv} iburst maxdelay 1000".format( srv=server.hostname), 'pidfile /tmp/chronyd.pid', 'bindcmdaddress /', 'maxdistance 1000', 'maxjitter 1000']) def connect_replica(master, replica, domain_level=None, database=DOMAIN_SUFFIX_NAME): if domain_level is None: domain_level = master.config.domain_level check_domain_level(domain_level) if domain_level == DOMAIN_LEVEL_0: if database == DOMAIN_SUFFIX_NAME: cmd = 'ipa-replica-manage' else: cmd = 'ipa-csreplica-manage' replica.run_command([cmd, 'connect', master.hostname]) else: kinit_admin(master) master.run_command(["ipa", "topologysegment-add", database, "%s-to-%s" % (master.hostname, replica.hostname), "--leftnode=%s" % master.hostname, "--rightnode=%s" % replica.hostname ]) def disconnect_replica(master, replica, domain_level=None, database=DOMAIN_SUFFIX_NAME): if domain_level is None: domain_level = master.config.domain_level check_domain_level(domain_level) if domain_level == DOMAIN_LEVEL_0: if database == DOMAIN_SUFFIX_NAME: cmd = 'ipa-replica-manage' else: cmd = 'ipa-csreplica-manage' replica.run_command([cmd, 'disconnect', master.hostname]) else: kinit_admin(master) master.run_command(["ipa", "topologysegment-del", database, "%s-to-%s" % (master.hostname, replica.hostname), "--continue" ]) def kinit_user(host, user, password, raiseonerr=True): return host.run_command(['kinit', user], raiseonerr=raiseonerr, stdin_text=password) def kinit_admin(host, raiseonerr=True): return kinit_user(host, 'admin', host.config.admin_password, raiseonerr=raiseonerr) def get_credential_cache(host): # Return the credential cache currently in use on host or None result = host.run_command(["klist"]).stdout_text pattern = re.compile(r'Ticket cache: (?P<cache>.*)\n') res = pattern.search(result) if res: return res['cache'] return None def uninstall_master(host, ignore_topology_disconnect=True, ignore_last_of_role=True, clean=True, verbose=False): uninstall_cmd = ['ipa-server-install', '--uninstall', '-U'] host_domain_level = domainlevel(host) if ignore_topology_disconnect and host_domain_level != DOMAIN_LEVEL_0: uninstall_cmd.append('--ignore-topology-disconnect') if ignore_last_of_role and host_domain_level != DOMAIN_LEVEL_0: uninstall_cmd.append('--ignore-last-of-role') if verbose and host_domain_level != DOMAIN_LEVEL_0: uninstall_cmd.append('-v') result = host.run_command(uninstall_cmd) assert "Traceback" not in result.stdout_text # Check that IPA certs have been deleted after uninstall # Related: https://pagure.io/freeipa/issue/8614 assert host.run_command(['test', '-f', paths.IPA_CA_CRT], raiseonerr=False).returncode == 1 assert host.run_command(['test', '-f', paths.IPA_P11_KIT], raiseonerr=False).returncode == 1 assert "IPA CA" not in host.run_command( ["trust", "list"], log_stdout=False ).stdout_text if clean: Firewall(host).disable_services(["freeipa-ldap", "freeipa-ldaps", "freeipa-trust", "dns"]) host.run_command(['pkidestroy', '-s', 'CA', '-i', 'pki-tomcat'], raiseonerr=False) host.run_command(['rm', '-rf', paths.TOMCAT_TOPLEVEL_DIR, paths.SYSCONFIG_PKI_TOMCAT, paths.SYSCONFIG_PKI_TOMCAT_PKI_TOMCAT_DIR, paths.VAR_LIB_PKI_TOMCAT_DIR, paths.PKI_TOMCAT, paths.IPA_RENEWAL_LOCK, paths.REPLICA_INFO_GPG_TEMPLATE % host.hostname], raiseonerr=False) host.run_command("find %s -name '*.keytab' | " "xargs rm -fv" % paths.SSSD_KEYTABS_DIR, raiseonerr=False) host.run_command("find /run/ipa -name 'krb5*' | xargs rm -fv", raiseonerr=False) while host.resolver.has_backups(): host.resolver.restore() if clean: unapply_fixes(host) def uninstall_client(host): host.run_command(['ipa-client-install', '--uninstall', '-U'], raiseonerr=False) while host.resolver.has_backups(): host.resolver.restore() unapply_fixes(host) @check_arguments_are((0, 2), Host) def clean_replication_agreement(master, replica, cleanup=False, raiseonerr=True): """ Performs `ipa-replica-manage del replica_hostname --force`. """ args = ['ipa-replica-manage', 'del', replica.hostname, '--force'] if cleanup: args.append('--cleanup') master.run_command(args, raiseonerr=raiseonerr) @check_arguments_are((0, 3), Host) def create_segment(master, leftnode, rightnode, suffix=DOMAIN_SUFFIX_NAME): """ creates a topology segment. The first argument is a node to run the command :returns: a hash object containing segment's name, leftnode, rightnode information and an error string. """ kinit_admin(master) lefthost = leftnode.hostname righthost = rightnode.hostname segment_name = "%s-to-%s" % (lefthost, righthost) result = master.run_command( ["ipa", "topologysegment-add", suffix, segment_name, "--leftnode=%s" % lefthost, "--rightnode=%s" % righthost], raiseonerr=False ) if result.returncode == 0: return {'leftnode': lefthost, 'rightnode': righthost, 'name': segment_name}, "" else: return {}, result.stderr_text def destroy_segment(master, segment_name, suffix=DOMAIN_SUFFIX_NAME): """ Destroys topology segment. :param master: reference to master object of class Host :param segment_name: name of the segment to be created """ assert isinstance(master, Host), "master should be an instance of Host" kinit_admin(master) command = ["ipa", "topologysegment-del", suffix, segment_name] result = master.run_command(command, raiseonerr=False) return result.returncode, result.stderr_text def get_topo(name_or_func): """Get a topology function by name A topology function receives a master and list of replicas, and yields (parent, child) pairs, where "child" should be installed from "parent" (or just connected if already installed) If a callable is given instead of name, it is returned directly """ if callable(name_or_func): return name_or_func return topologies[name_or_func] def _topo(name): """Decorator that registers a function in topologies under a given name""" def add_topo(func): topologies[name] = func return func return add_topo topologies = collections.OrderedDict() @_topo('star') def star_topo(master, replicas): r"""All replicas are connected to the master Rn R1 R2 \ | / R7-- M -- R3 / | \ R6 R5 R4 """ for replica in replicas: yield master, replica @_topo('line') def line_topo(master, replicas): r"""Line topology M \ R1 \ R2 \ R3 \ ... """ for replica in replicas: yield master, replica master = replica @_topo('complete') def complete_topo(master, replicas): r"""Each host connected to each other host M--R1 |\/| |/\| R2-R3 """ for replica in replicas: yield master, replica for replica1, replica2 in itertools.combinations(replicas, 2): yield replica1, replica2 @_topo('tree') def tree_topo(master, replicas): r"""Binary tree topology M / \ / \ R1 R2 / \ / \ R3 R4 R5 R6 / R7 ... """ replicas = list(replicas) def _masters(): for host in [master] + replicas: yield host yield host for parent, child in zip(_masters(), replicas): yield parent, child @_topo('tree2') def tree2_topo(master, replicas): r"""First replica connected directly to master, the rest in a line M / \ R1 R2 \ R3 \ R4 \ ... """ if replicas: yield master, replicas[0] for replica in replicas[1:]: yield master, replica master = replica @_topo('2-connected') def two_connected_topo(master, replicas): r"""No replica has more than 4 agreements and at least two replicas must fail to disconnect the topology. . . . . . . . . . . . . ... R --- R R --- R ... \ / \ / \ / \ / \ / \ / ... R R R ... \ / \ / \ / \ / M0 -- R2 | | | | R1 -- R3 . \ / . . \ / . . R . . . . . . . """ grow = [] pool = [master] + replicas try: v0 = pool.pop(0) v1 = pool.pop(0) yield v0, v1 v2 = pool.pop(0) yield v0, v2 grow.append((v0, v2)) v3 = pool.pop(0) yield v2, v3 yield v1, v3 grow.append((v1, v3)) i = 0 while i < len(grow): r, s = grow[i] t = pool.pop(0) for (u, v) in [(r, t), (s, t)]: yield u, v w = pool.pop(0) yield u, w x = pool.pop(0) yield v, x yield w, x grow.append((w, x)) i += 1 except IndexError: return @_topo('double-circle') def double_circle_topo(master, replicas, site_size=6): r""" R--R |\/| |/\| R--R / \ M -- R /| |\ / | | \ R - R - R--|----|--R - R - R | X | | | | | | X | R - R - R -|----|--R - R - R \ | | / \| |/ R -- R \ / R--R |\/| |/\| R--R """ # to provide redundancy there must be at least two replicas per site assert site_size >= 2 # do not handle master other than the rest of the servers servers = [master] + replicas # split servers into sites it = [iter(servers)] * site_size sites = [(x[0], x[1], x[2:]) for x in zip(*it)] num_sites = len(sites) for i in range(num_sites): (a, b, _ignore) = sites[i] # create agreement inside the site yield a, b # create agreement to one server in two next sites for c, _d, _ignore in [sites[(i+n) % num_sites] for n in [1, 2]]: yield b, c if site_size > 2: # deploy servers inside the site for site in sites: site_servers = list(site[2]) yield site[0], site_servers[0] for edge in complete_topo(site_servers[0], site_servers[1:]): yield edge yield site[1], site_servers[-1] def install_topo(topo, master, replicas, clients, domain_level=None, skip_master=False, setup_replica_cas=True, setup_replica_kras=False, clients_extra_args=(), random_serial=False, extra_args=()): """Install IPA servers and clients in the given topology""" if setup_replica_kras and not setup_replica_cas: raise ValueError("Option 'setup_replica_kras' requires " "'setup_replica_cas' set to True") replicas = list(replicas) installed = {master} if not skip_master: install_master( master, domain_level=domain_level, setup_kra=setup_replica_kras, random_serial=random_serial, ) add_a_records_for_hosts_in_master_domain(master) for parent, child in get_topo(topo)(master, replicas): if child in installed: logger.info('Connecting replica %s to %s', parent, child) connect_replica(parent, child) else: logger.info('Installing replica %s from %s', child, parent) install_replica( parent, child, setup_ca=setup_replica_cas, setup_kra=setup_replica_kras, nameservers=master.ip, extra_args=extra_args, ) installed.add(child) install_clients([master] + replicas, clients, clients_extra_args) def install_clients(servers, clients, extra_args=(), nameservers='first'): """Install IPA clients, distributing them among the given servers :param nameservers: nameservers to write in resolver config on clients. Possible values: * "first" - use ip of the first item in `servers` parameter * "distribute" - use ip of master/replica which is used for client installation * None - do not setup resolver * IP_ADDRESS or [IP_ADDRESS, ...] - use this address as resolver """ izip = getattr(itertools, 'izip', zip) client_nameservers = nameservers for server, client in izip(itertools.cycle(servers), clients): logger.info('Installing client %s on %s', server, client) if nameservers == 'distribute': client_nameservers = server.ip if nameservers == 'first': client_nameservers = servers[0].ip install_client(server, client, extra_args, nameservers=client_nameservers) def _entries_to_ldif(entries): """Format LDAP entries as LDIF""" io = StringIO() writer = LDIFWriter(io) for entry in entries: writer.unparse(str(entry.dn), dict(entry.raw)) return io.getvalue() def wait_for_replication(ldap, timeout=30, target_status_re=r'^0 |^Error \(0\) ', raise_on_timeout=False): """Wait for all replication agreements to reach desired state With defaults waits until updates on all replication agreements are done (or failed) and exits without exception :param ldap: LDAP client autenticated with necessary rights to read the mapping tree :param timeout: Maximum time to wait, in seconds :param target_status_re: Regexp of status to wait for :param raise_on_timeout: if True, raises AssertionError if status not reached in specified time Note that this waits for updates originating on this host, not those coming from other hosts. """ logger.debug('Waiting for replication to finish') start = time.time() while True: status_attr = 'nsds5replicaLastUpdateStatus' progress_attr = 'nsds5replicaUpdateInProgress' entries = ldap.get_entries( DN(('cn', 'mapping tree'), ('cn', 'config')), filter='(objectclass=nsds5replicationagreement)', attrs_list=[status_attr, progress_attr]) logger.debug('Replication agreements: \n%s', _entries_to_ldif(entries)) statuses = [entry.single_value[status_attr] for entry in entries] wrong_statuses = [s for s in statuses if not re.match(target_status_re, s)] if any(e.single_value[progress_attr] for e in entries): msg = 'Replication not finished' logger.debug(msg) elif wrong_statuses: msg = 'Unexpected replication status: %s' % wrong_statuses[0] logger.debug(msg) else: logger.debug('Replication finished') return if time.time() - start > timeout: logger.error('Giving up wait for replication to finish') if raise_on_timeout: raise AssertionError(msg) break time.sleep(1) def wait_for_cleanallruv_tasks(ldap, timeout=30): """Wait until cleanallruv tasks are finished """ logger.debug('Waiting for cleanallruv tasks to finish') success_status = 'Successfully cleaned rid' for i in range(timeout): status_attr = 'nstaskstatus' try: entries = ldap.get_entries( DN(('cn', 'cleanallruv'), ('cn', 'tasks'), ('cn', 'config')), scope=ldap.SCOPE_ONELEVEL, attrs_list=[status_attr]) except errors.EmptyResult: logger.debug("No cleanallruv tasks") break # Check status if all( e.single_value[status_attr].startswith(success_status) for e in entries ): logger.debug("All cleanallruv tasks finished successfully") break logger.debug("cleanallruv task in progress, (waited %s/%ss)", i, timeout) time.sleep(1) else: logger.error('Giving up waiting for cleanallruv to finish') for e in entries: stat_str = e.single_value[status_attr] if not stat_str.startswith(success_status): logger.debug('%s status: %s', e.dn, stat_str) def add_a_records_for_hosts_in_master_domain(master): for host in master.domain.hosts: # We don't need to take care of the zone creation since it is master # domain add_a_record(master, host) def add_a_record(master, host): # Find out if the record is already there cmd = master.run_command(['ipa', 'dnsrecord-show', master.domain.name, host.hostname + "."], raiseonerr=False) # If not, add it if cmd.returncode != 0: master.run_command(['ipa', 'dnsrecord-add', master.domain.name, host.hostname + ".", '--a-rec', host.ip]) def resolve_record(nameserver, query, rtype="SOA", retry=True, timeout=100): """Resolve DNS record :retry: if resolution failed try again until timeout is reached :timeout: max period of time while method will try to resolve query (requires retry=True) """ res = DNSResolver() res.nameservers = [nameserver] res.lifetime = 10 # wait max 10 seconds for reply wait_until = time.time() + timeout while time.time() < wait_until: try: ans = res.resolve(query, rtype) return ans except dns.exception.DNSException: if not retry: raise time.sleep(1) raise errors.DNSResolverError(exception=ValueError("Record not found")) def ipa_backup(host, disable_role_check=False, data_only=False, raiseonerr=True): """Run backup on host and return the run_command result. """ cmd = ['ipa-backup', '-v'] if disable_role_check: cmd.append('--disable-role-check') if data_only: cmd.append('--data') result = host.run_command(cmd, raiseonerr=raiseonerr) # Test for ticket 7632: check that services are restarted # before the backup is compressed pattern = r'.*{}.*Starting IPA service.*'.format(paths.GZIP) if (re.match(pattern, result.stderr_text, re.DOTALL)): raise AssertionError('IPA Services are started after compression') return result def ipa_epn( host, dry_run=False, from_nbdays=None, to_nbdays=None, raiseonerr=True, mailtest=False, ): """Run EPN on host and return the run_command result. """ cmd = ["ipa-epn"] if dry_run: cmd.append("--dry-run") if mailtest: cmd.append("--mail-test") if from_nbdays is not None: cmd.extend(("--from-nbdays", str(from_nbdays))) if to_nbdays is not None: cmd.extend(("--to-nbdays", str(to_nbdays))) return host.run_command(cmd, raiseonerr=raiseonerr) def get_backup_dir(host, data_only=False, raiseonerr=True): """Wrapper around ipa_backup: returns the backup directory. """ result = ipa_backup(host, data_only=data_only, raiseonerr=raiseonerr) # Get the backup location from the command's output for line in result.stderr_text.splitlines(): prefix = 'ipaserver.install.ipa_backup: INFO: Backed up to ' if line.startswith(prefix): backup_path = line[len(prefix):].strip() logger.info('Backup path for %s is %s', host.hostname, backup_path) return backup_path else: if raiseonerr: raise AssertionError('Backup directory not found in output') else: return None def ipa_restore(master, backup_path, backend=None): cmd = ["ipa-restore", "-U", "-p", master.config.dirman_password, backup_path] if backend: cmd.extend(["--data", "--backend", backend]) master.run_command(cmd) def install_kra(host, domain_level=None, first_instance=False, raiseonerr=True, extra_args=(),): if domain_level is None: domain_level = domainlevel(host) check_domain_level(domain_level) command = ["ipa-kra-install", "-U", "-p", host.config.dirman_password] if not isinstance(extra_args, (tuple, list)): raise TypeError("extra_args must be tuple or list") command.extend(extra_args) result = host.run_command(command, raiseonerr=raiseonerr) return result def install_ca( host, domain_level=None, first_instance=False, external_ca=False, cert_files=None, raiseonerr=True, extra_args=(), random_serial=False, ): if domain_level is None: domain_level = domainlevel(host) check_domain_level(domain_level) command = ["ipa-ca-install", "-U", "-p", host.config.dirman_password, "-P", 'admin', "-w", host.config.admin_password] if random_serial: command.append('--random-serial-numbers') if not isinstance(extra_args, (tuple, list)): raise TypeError("extra_args must be tuple or list") command.extend(extra_args) # First step of ipa-ca-install --external-ca if external_ca: command.append('--external-ca') # Continue with ipa-ca-install --external-ca if cert_files: for fname in cert_files: command.extend(['--external-cert-file', fname]) result = host.run_command(command, raiseonerr=raiseonerr) return result def install_dns(host, raiseonerr=True, extra_args=()): args = [ "ipa-dns-install", "--forwarder", host.config.dns_forwarder, "-U", ] args.extend(extra_args) ret = host.run_command(args, raiseonerr=raiseonerr) Firewall(host).enable_service("dns") return ret def uninstall_replica(master, replica): master.run_command(["ipa-replica-manage", "del", "--force", "-p", master.config.dirman_password, replica.hostname], raiseonerr=False) uninstall_master(replica) def replicas_cleanup(func): """ replicas_cleanup decorator, applied to any test method in integration tests uninstalls all replicas in the topology leaving only master configured """ def wrapped(*args): func(*args) for host in args[0].replicas: uninstall_replica(args[0].master, host) uninstall_client(host) result = args[0].master.run_command( ["ipa", "host-del", "--updatedns", host.hostname], raiseonerr=False) # Workaround for 5627 if "host not found" in result.stderr_text: args[0].master.run_command(["ipa", "host-del", host.hostname], raiseonerr=False) return wrapped def run_server_del(host, server_to_delete, force=False, ignore_topology_disconnect=False, ignore_last_of_role=False): kinit_admin(host) args = ['ipa', 'server-del', server_to_delete] if force: args.append('--force') if ignore_topology_disconnect: args.append('--ignore-topology-disconnect') if ignore_last_of_role: args.append('--ignore-last-of-role') return host.run_command(args, raiseonerr=False) def run_certutil(host, args, reqdir, dbtype=None, stdin=None, raiseonerr=True): dbdir = reqdir if dbtype is None else '{}:{}'.format(dbtype, reqdir) new_args = [paths.CERTUTIL, '-d', dbdir] new_args.extend(args) return host.run_command(new_args, raiseonerr=raiseonerr, stdin_text=stdin) def certutil_certs_keys(host, reqdir, pwd_file, token_name=None): """Run certutils and get mappings of cert and key files """ base_args = ['-f', pwd_file] if token_name is not None: base_args.extend(['-h', token_name]) cert_args = base_args + ['-L'] key_args = base_args + ['-K'] result = run_certutil(host, cert_args, reqdir) certs = {} for line in result.stdout_text.splitlines(): mo = certdb.CERT_RE.match(line) if mo: certs[mo.group('nick')] = mo.group('flags') result = run_certutil(host, key_args, reqdir) assert 'orphan' not in result.stdout_text keys = {} for line in result.stdout_text.splitlines(): mo = certdb.KEY_RE.match(line) if mo: keys[mo.group('nick')] = mo.group('keyid') return certs, keys def certutil_fetch_cert(host, reqdir, pwd_file, nickname, token_name=None): """Run certutil and retrieve a cert as cryptography.x509 object """ args = ['-f', pwd_file, '-L', '-a', '-n'] if token_name is not None: args.extend([ '{}:{}'.format(token_name, nickname), '-h', token_name ]) else: args.append(nickname) result = run_certutil(host, args, reqdir) return x509.load_pem_x509_certificate( result.stdout_bytes, default_backend() ) def upload_temp_contents(host, contents, encoding='utf-8'): """Upload contents to a temporary file :param host: Remote host instance :param contents: file content (str, bytes) :param encoding: file encoding :return: Temporary file name """ result = host.run_command(['mktemp']) tmpname = result.stdout_text.strip() host.put_file_contents(tmpname, contents, encoding=encoding) return tmpname def assert_error(result, pattern, returncode=None): """ Assert that ``result`` command failed and its stderr contains ``pattern``. ``pattern`` may be a ``str`` or a ``re.Pattern`` (regular expression). """ if hasattr(pattern, "search"): # re pattern assert pattern.search(result.stderr_text), \ f"pattern {pattern} not found in stderr {result.stderr_text!r}" else: assert pattern in result.stderr_text, \ f"substring {pattern!r} not found in stderr {result.stderr_text!r}" if returncode is not None: assert result.returncode == returncode else: assert result.returncode > 0 def restart_named(*args): time.sleep(20) # give a time to DNSSEC daemons to provide keys for named for host in args: host.run_command(['systemctl', 'restart', knownservices.named.systemd_name]) time.sleep(20) # give a time to named to be ready (zone loading) def run_repeatedly(host, command, assert_zero_rc=True, test=None, timeout=30, **kwargs): """ Runs command on host repeatedly until it's finished successfully (returns 0 exit code and its stdout passes the test function). Returns True if the command was executed succesfully, False otherwise. This method accepts additional kwargs and passes these arguments to the actual run_command method. """ time_waited = 0 time_step = 2 # Check that the test is a function if test: assert callable(test) while(time_waited <= timeout): result = host.run_command(command, raiseonerr=False, **kwargs) return_code_ok = not assert_zero_rc or (result.returncode == 0) test_ok = not test or test(result.stdout_text) if return_code_ok and test_ok: # Command successful return True else: # Command not successful time.sleep(time_step) time_waited += time_step raise AssertionError("Command: {cmd} repeatedly failed {times} times, " "exceeding the timeout of {timeout} seconds." .format(cmd=' '.join(command), times=timeout // time_step, timeout=timeout)) def get_host_ip_with_hostmask(host): """Detects the IP of the host including the hostmask Returns None if the IP could not be detected. """ ip = host.ip result = host.run_command(['ip', 'addr']) full_ip_regex = r'(?P<full_ip>%s/\d{1,2}) ' % re.escape(ip) match = re.search(full_ip_regex, result.stdout_text) if match: return match.group('full_ip') else: return None def ldappasswd_user_change(user, oldpw, newpw, master, use_dirman=False, raiseonerr=True): container_user = dict(DEFAULT_CONFIG)['container_user'] basedn = master.domain.basedn userdn = "uid={},{},{}".format(user, container_user, basedn) master_ldap_uri = "ldap://{}".format(master.hostname) if use_dirman: args = [paths.LDAPPASSWD, '-D', str(master.config.dirman_dn), '-w', master.config.dirman_password, '-s', newpw, '-x', '-ZZ', '-H', master_ldap_uri, userdn] else: args = [paths.LDAPPASSWD, '-D', userdn, '-w', oldpw, '-a', oldpw, '-s', newpw, '-x', '-ZZ', '-H', master_ldap_uri] return master.run_command(args, raiseonerr=raiseonerr) def ldappasswd_sysaccount_change(user, oldpw, newpw, master, use_dirman=False): container_sysaccounts = dict(DEFAULT_CONFIG)['container_sysaccounts'] basedn = master.domain.basedn userdn = "uid={},{},{}".format(user, container_sysaccounts, basedn) master_ldap_uri = "ldap://{}".format(master.hostname) if use_dirman: args = [paths.LDAPPASSWD, '-D', str(master.config.dirman_dn), '-w', master.config.dirman_password, '-a', oldpw, '-s', newpw, '-x', '-ZZ', '-H', master_ldap_uri, userdn] else: args = [paths.LDAPPASSWD, '-D', userdn, '-w', oldpw, '-a', oldpw, '-s', newpw, '-x', '-ZZ', '-H', master_ldap_uri] master.run_command(args) def add_dns_zone(master, zone, skip_overlap_check=False, dynamic_update=False, add_a_record_hosts=None): """ Add DNS zone if it is not already added. """ result = master.run_command( ['ipa', 'dnszone-show', zone], raiseonerr=False) if result.returncode != 0: command = ['ipa', 'dnszone-add', zone] if skip_overlap_check: command.append('--skip-overlap-check') if dynamic_update: command.append('--dynamic-update=True') master.run_command(command) if add_a_record_hosts: for host in add_a_record_hosts: master.run_command(['ipa', 'dnsrecord-add', zone, host.hostname + ".", '--a-rec', host.ip]) else: logger.debug('Zone %s already added.', zone) def sign_ca_and_transport(host, csr_name, root_ca_name, ipa_ca_name, root_ca_path_length=None, ipa_ca_path_length=1, key_size=None, root_ca_extensions=()): """ Sign ipa csr and save signed CA together with root CA back to the host. Returns root CA and IPA CA paths on the host. """ test_dir = host.config.test_dir # Get IPA CSR as bytes ipa_csr = host.get_file_contents(csr_name) external_ca = ExternalCA(key_size=key_size) # Create root CA root_ca = external_ca.create_ca( path_length=root_ca_path_length, extensions=root_ca_extensions, ) # Sign CSR ipa_ca = external_ca.sign_csr(ipa_csr, path_length=ipa_ca_path_length) root_ca_fname = os.path.join(test_dir, root_ca_name) ipa_ca_fname = os.path.join(test_dir, ipa_ca_name) # Transport certificates (string > file) to master host.put_file_contents(root_ca_fname, root_ca) host.put_file_contents(ipa_ca_fname, ipa_ca) return root_ca_fname, ipa_ca_fname def generate_ssh_keypair(): """ Create SSH keypair for key authentication testing """ key = rsa.generate_private_key(backend=default_backend(), public_exponent=65537, key_size=2048) public_key = key.public_key().public_bytes( serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH) pem = key.private_bytes( encoding=serialization.Encoding.PEM, # paramiko does not support PKCS#8 format, yet. format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption() ) private_key_str = pem.decode('utf-8') public_key_str = public_key.decode('utf-8') return (private_key_str, public_key_str) def strip_cert_header(pem): """ Remove the header and footer from a certificate. """ regexp = ( r"^-----BEGIN CERTIFICATE-----(.*?)-----END CERTIFICATE-----" ) s = re.search(regexp, pem, re.MULTILINE | re.DOTALL) if s is not None: return s.group(1) else: return pem def user_add(host, login, first='test', last='user', extra_args=(), password=None): cmd = [ "ipa", "user-add", login, "--first", first, "--last", last ] if password is not None: cmd.append('--password') stdin_text = '{0}\n{0}\n'.format(password) else: stdin_text = None cmd.extend(extra_args) return host.run_command(cmd, stdin_text=stdin_text) def user_del(host, login): cmd = ["ipa", "user-del", login] return host.run_command(cmd) def group_add(host, groupname, extra_args=()): cmd = [ "ipa", "group-add", groupname, ] cmd.extend(extra_args) return host.run_command(cmd) def group_del(host, groupname): cmd = [ "ipa", "group-del", groupname, ] return host.run_command(cmd) def group_add_member(host, groupname, users=None, raiseonerr=True, extra_args=()): cmd = [ "ipa", "group-add-member", groupname ] if users: cmd.append("--users") cmd.append(users) cmd.extend(extra_args) return host.run_command(cmd, raiseonerr=raiseonerr) def ldapmodify_dm(host, ldif_text, **kwargs): """Run ldapmodify as Directory Manager :param host: host object :param ldif_text: ldif string :param kwargs: additional keyword arguments to run_command() :return: result object """ # no hard-coded hostname, let ldapmodify pick up the host from ldap.conf. args = [ 'ldapmodify', '-x', '-D', str(host.config.dirman_dn), '-w', host.config.dirman_password ] return host.run_command(args, stdin_text=ldif_text, **kwargs) def ldapsearch_dm(host, base, ldap_args, scope='sub', **kwargs): """Run ldapsearch as Directory Manager :param host: host object :param base: Base DN :param ldap_args: additional arguments to ldapsearch (filter, attributes) :param scope: search scope (base, sub, one) :param kwargs: additional keyword arguments to run_command() :return: result object """ args = [ 'ldapsearch', '-x', '-ZZ', '-H', "ldap://{}".format(host.hostname), '-D', str(host.config.dirman_dn), '-w', host.config.dirman_password, '-s', scope, '-b', base, '-o', 'ldif-wrap=no', '-LLL', ] args.extend(ldap_args) return host.run_command(args, **kwargs) def create_temp_file(host, directory=None, suffix=None, create_file=True): """Creates temporary file using mktemp. See `man 1 mktemp`.""" cmd = ['mktemp'] if create_file is False: cmd += ['--dry-run'] if directory is not None: cmd += ['-p', directory] if suffix is not None: cmd.extend(["--suffix", suffix]) return host.run_command(cmd).stdout_text.strip() def create_active_user(host, login, password, first='test', last='user', extra_args=(), krb5_trace=False): """Create user and do login to set password""" temp_password = 'Secret456789' kinit_admin(host) user_add(host, login, first=first, last=last, extra_args=extra_args, password=temp_password) if krb5_trace: # Retrieve kdcinfo.$REALM before changing the user's password. get_kdcinfo(host) # This tends to fail when the KDC the password is # reset on is not the same as the one we immediately # request a TGT from. This should not be the case as SSSD # tries to pin itself to an IPA server. # # Note raiseonerr=False: # the assert is located after kdcinfo retrieval. result = host.run_command( f"KRB5_TRACE=/dev/stdout SSSD_KRB5_LOCATOR_DEBUG=1 kinit {login}", stdin_text='{0}\n{1}\n{1}\n'.format( temp_password, password ), raiseonerr=False ) # Retrieve kdc.$REALM after the password change, just in case SSSD # domain status flipped to online during the password change. get_kdcinfo(host) assert result.returncode == 0 else: host.run_command( ['kinit', login], stdin_text='{0}\n{1}\n{1}\n'.format(temp_password, password) ) kdestroy_all(host) def set_user_password(host, username, password): temppass = "redhat\nredhat" sendpass = f"redhat\n{password}\n{password}" kdestroy_all(host) kinit_admin(host) host.run_command(["ipa", "passwd", username],stdin_text=temppass) host.run_command(["kinit", username], stdin_text=sendpass) kdestroy_all(host) kinit_admin(host) def kdestroy_all(host): return host.run_command(['kdestroy', '-A']) def run_command_as_user(host, user, command, *args, **kwargs): """Run command on remote host using 'su -l' Arguments are similar to Host.run_command """ if not isinstance(command, str): command = ' '.join(quote(s) for s in command) cwd = kwargs.pop('cwd', None) if cwd is not None: command = 'cd {}; {}'.format(quote(cwd), command) command = ['su', '-l', user, '-c', command] return host.run_command(command, *args, **kwargs) def kinit_as_user(host, user, password, krb5_trace=False, raiseonerr=True): """Launch kinit as user on host. If krb5_trace, then set KRB5_TRACE=/dev/stdout, SSSD_KRB5_LOCATOR_DEBUG=1 and collect /var/lib/sss/pubconf/kdcinfo.$REALM as this file contains the list of KRB5KDC IPs SSSD uses. https://pagure.io/freeipa/issue/8510 """ if krb5_trace: # Retrieve kdcinfo.$REALM before changing the user's password. get_kdcinfo(host) # This tends to fail when the KDC the password is # reset on is not the same as the one we immediately # request a TGT from. This should not be the case as SSSD # tries to pin itself to an IPA server. # # Note raiseonerr=False: # the assert is located after kdcinfo retrieval. result = host.run_command( f"KRB5_TRACE=/dev/stdout SSSD_KRB5_LOCATOR_DEBUG=1 kinit {user}", stdin_text='{0}\n'.format(password), raiseonerr=False ) # Retrieve kdc.$REALM after the password change, just in case SSSD # domain status flipped to online during the password change. get_kdcinfo(host) if raiseonerr: assert result.returncode == 0 return result else: return host.run_command( ['kinit', user], stdin_text='{0}\n'.format(password), raiseonerr=raiseonerr) def get_kdcinfo(host): """Retrieve /var/lib/sss/pubconf/kdcinfo.$REALM on host. That file contains the IP of the KDC SSSD should be pinned to. """ logger.info( 'Collecting kdcinfo log from: %s', host.hostname ) if check_if_sssd_is_online(host): logger.info("SSSD considers domain %s online.", host.domain.realm) else: logger.warning( "SSSD considers domain %s offline.", host.domain.realm ) kdcinfo = None try: kdcinfo = host.get_file_contents( "/var/lib/sss/pubconf/kdcinfo.{}".format(host.domain.realm) ) logger.info( 'kdcinfo %s contains:\n%s', host.hostname, kdcinfo ) if check_if_sssd_is_online(host) is False: logger.warning( "SSSD still considers domain %s offline.", host.domain.realm ) except (OSError, IOError) as e: logger.warning( "Exception collecting kdcinfo.%s: %s\n" "SSSD is able to function without this file but logon " "attempts immediately after a password change might break.", host.domain.realm, e ) return kdcinfo KeyEntry = collections.namedtuple('KeyEntry', ['kvno', 'principal', 'etype', 'key']) class KerberosKeyCopier: """Copy Kerberos keys from a keytab to a keytab on a target host Example: Copy host/master1.ipa.test principal as MASTER$ in a temporary keytab # host - master1.ipa.test copier = KerberosKeyCopier(host) realm = host.domain.realm principal = copier.host_princ_template.format( master=host.hostname, realm=realm) replacement = {principal: f'MASTER$@{realm}'} result = host.run_command(['mktemp']) tmpname = result.stdout_text.strip() copier.copy_keys('/etc/krb5.keytab', tmpname, replacement=replacement) """ host_princ_template = "host/{master}@{realm}" valid_etypes = ['aes256-cts-hmac-sha384-192', 'aes128-cts-hmac-sha256-128', 'aes256-cts-hmac-sha1-96', 'aes128-cts-hmac-sha1-96'] def __init__(self, host): self.host = host self.realm = host.domain.realm def extract_key_refs(self, keytab, princ=None): if princ is None: princ = self.host_princ_template.format(master=self.host.hostname, realm=self.realm) result = self.host.run_command( [paths.KLIST, "-eK", "-k", keytab], log_stdout=False) keys_to_sync = [] for line in result.stdout_text.splitlines(): if (princ in line and any(e in line for e in self.valid_etypes)): els = line.split() els[-2] = els[-2].strip('()') els[-1] = els[-1].strip('()') keys_to_sync.append(KeyEntry._make(els)) return keys_to_sync def copy_key(self, keytab, keyentry): def get_keytab_mtime(): """Get keytab file mtime. Returns mtime with sub-second precision as a string with format "2020-08-25 14:35:05.980503425 +0200" or None if file does not exist. """ if self.host.transport.file_exists(keytab): return self.host.run_command( ['stat', '-c', '%y', keytab]).stdout_text.strip() return None mtime_before = get_keytab_mtime() with self.host.spawn_expect(paths.KTUTIL, default_timeout=5, extra_ssh_options=['-t']) as e: e.expect_exact('ktutil:') e.sendline('rkt {}'.format(keytab)) e.expect_exact('ktutil:') e.sendline( 'addent -key -p {principal} -k {kvno} -e {etype}' .format(principal=keyentry.principal, kvno=keyentry.kvno, etype=keyentry.etype,)) e.expect('Key for.+:') # keyentry.key is a hex value of the actual key # prefixed with 0x, as produced by klist -K -k. # However, ktutil accepts hex value without 0x, so # we should strip first two characters. e.sendline(keyentry.key[2:]) e.expect_exact('ktutil:') e.sendline('wkt {}'.format(keytab)) e.expect_exact('ktutil:') e.sendline('q') if mtime_before == get_keytab_mtime(): raise Exception('{} did not update keytab file "{}"'.format( paths.KTUTIL, keytab)) def copy_keys(self, origin, destination, principal=None, replacement=None): def sync_keys(origkeys, destkeys): for origkey in origkeys: copied = False uptodate = False if origkey.principal in replacement: origkey = copy.deepcopy(origkey) origkey.principal = replacement.get(origkey.principal) for destkey in destkeys: if all([destkey.principal == origkey.principal, destkey.etype == origkey.etype]): if any([destkey.key != origkey.key, destkey.kvno != origkey.kvno]): self.copy_key(destination, origkey) copied = True break uptodate = True if not (copied or uptodate): self.copy_key(destination, origkey) if not self.host.transport.file_exists(origin): raise ValueError('File "{}" does not exist'.format(origin)) origkeys = self.extract_key_refs(origin, princ=principal) if self.host.transport.file_exists(destination): destkeys = self.extract_key_refs(destination) if any([origkeys is None, destkeys is None]): raise Exception( 'Either {} or {} are missing or unreadable'.format( origin, destination)) sync_keys(origkeys, destkeys) else: for origkey in origkeys: if origkey.principal in replacement: newkey = KeyEntry._make( [origkey.kvno, replacement.get(origkey.principal), origkey.etype, origkey.key]) origkey = newkey self.copy_key(destination, origkey) class FileBackup: """Create file backup and do restore on remote host Examples: config_backup = FileBackup(host, '/etc/some.conf') ... modify the file and do the test ... config_backup.restore() Use as a context manager: with FileBackup(host, '/etc/some.conf'): ... modify the file and do the test ... """ def __init__(self, host, filename): """Create file backup.""" self._host = host self._filename = filename self._backup = create_temp_file(host) host.run_command(['cp', '--preserve=all', filename, self._backup]) def restore(self): """Restore file. Can be called only once.""" self._host.run_command(['mv', self._backup, self._filename]) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.restore() @contextmanager def remote_ini_file(host, filename): """Context manager for editing an ini file on a remote host. It provides RawConfigParser object which is automatically serialized and uploaded to remote host upon exit from the context. If exception is raised inside the context then the ini file is NOT updated on remote host. Example: with remote_ini_file(master, '/etc/some.conf') as some_conf: some_conf.set('main', 'timeout', 10) """ data = host.get_file_contents(filename, encoding='utf-8') ini_file = configparser.RawConfigParser() ini_file.read_string(data) yield ini_file data = StringIO() ini_file.write(data) host.put_file_contents(filename, data.getvalue()) def is_selinux_enabled(host): res = host.run_command('selinuxenabled', ok_returncode=(0, 1)) return res.returncode == 0 def get_logsize(host, logfile): """ get current logsize""" logsize = len(host.get_file_contents(logfile)) return logsize def get_platform(host): result = host.run_command([ 'python3', '-c', 'from ipaplatform.osinfo import OSInfo; print(OSInfo().platform)' ], raiseonerr=False) assert result.returncode == 0 return result.stdout_text.strip() def get_platform_version(host): result = host.run_command([ 'python3', '-c', 'from ipaplatform.osinfo import OSInfo; print(OSInfo().version_number)' ], raiseonerr=False) assert result.returncode == 0 # stdout_text is a str in format "(X, Y)" and needs to be # converted back to a functional tuple. This approach works with # any number of version numbers filled, e.g. (34, ) or (8, 6) etc. return tuple(map(int, re.findall(r'[0-9]+', result.stdout_text.strip()))) def install_packages(host, pkgs): """Install packages on a remote host. :param host: the host where the installation takes place :param pkgs: packages to install, provided as a list of strings """ platform = get_platform(host) if platform in {'rhel', 'fedora'}: install_cmd = ['/usr/bin/dnf', 'install', '-y'] elif platform in {'debian', 'ubuntu'}: install_cmd = ['apt-get', 'install', '-y'] else: raise ValueError('install_packages: unknown platform %s' % platform) host.run_command(install_cmd + pkgs) def reinstall_packages(host, pkgs): """Install packages on a remote host. :param host: the host where the installation takes place :param pkgs: packages to install, provided as a list of strings """ platform = get_platform(host) if platform in {'rhel', 'fedora'}: install_cmd = ['/usr/bin/dnf', 'reinstall', '-y'] elif platform in {'debian', 'ubuntu'}: install_cmd = ['apt-get', '--reinstall', 'install', '-y'] else: raise ValueError('install_packages: unknown platform %s' % platform) host.run_command(install_cmd + pkgs) def download_packages(host, pkgs): """Download packages on a remote host. :param host: the host where the download takes place :param pkgs: packages to download, provided as a list of strings Returns the temporary directory where the packages are. The caller is responsible for cleanup. """ platform = get_platform(host) tmpdir = os.path.join('/tmp', str(uuid.uuid4())) # Only supports RHEL 8+ and Fedora for now if platform in ('rhel', 'fedora'): download_cmd = ['/usr/bin/dnf', 'download'] else: raise ValueError('download_packages: unknown platform %s' % platform) host.run_command(['mkdir', tmpdir]) host.run_command(download_cmd + pkgs, cwd=tmpdir) return tmpdir def uninstall_packages(host, pkgs, nodeps=False): """Uninstall packages on a remote host. :param host: the host where the uninstallation takes place. :param pkgs: packages to uninstall, provided as a list of strings. :param nodeps: ignore dependencies (dangerous!). """ platform = get_platform(host) if platform not in {"rhel", "fedora", "debian", "ubuntu"}: raise ValueError(f"uninstall_packages: unknown platform {platform}") if nodeps: if platform in {"rhel", "fedora"}: cmd = ["rpm", "-e", "--nodeps"] elif platform in {"debian", "ubuntu"}: cmd = ["dpkg", "-P", "--force-depends"] for package in pkgs: # keep raiseonerr=True here. --fcami host.run_command(cmd + [package]) else: if platform in {"rhel", "fedora"}: cmd = ["/usr/bin/dnf", "remove", "-y"] elif platform in {"debian", "ubuntu"}: cmd = ["apt-get", "remove", "-y"] host.run_command(cmd + pkgs, raiseonerr=False) def wait_for_request(host, request_id, timeout=120): for _i in range(0, timeout, 5): result = host.run_command( "getcert list -i %s | grep status: | awk '{ print $2 }'" % request_id ) state = result.stdout_text.strip() logger.info("certmonger request is in state %s", state) if state in ('CA_REJECTED', 'CA_UNREACHABLE', 'CA_UNCONFIGURED', 'NEED_GUIDANCE', 'NEED_CA', 'MONITORING'): break time.sleep(5) else: raise RuntimeError("request timed out") return state def wait_for_certmonger_status(host, status, request_id, timeout=120): """Aggressively wait for a specific certmonger status. This checks the status every second in order to attempt to catch transient states like SUBMITTED. There are no guarantees. :param host: the host where the uninstallation takes place :param status: tuple of statuses to look for :param request_id: request_id of request to check status on :param timeout: max time in seconds to wait for the status """ for _i in range(0, timeout, 1): result = host.run_command( "getcert list -i %s | grep status: | awk '{ print $2 }'" % request_id ) state = result.stdout_text.strip() logger.info("certmonger request is in state %s", state) if state in status: break time.sleep(1) else: raise RuntimeError("request timed out") return state def check_if_sssd_is_online(host): """Check whether SSSD considers the IPA domain online. Analyse sssctl domain-status <domain>'s output to see if SSSD considers the IPA domain of the host online. Could be extended for Trust domains as well. """ pattern = re.compile(r'Online status: (?P<state>.*)\n') result = host.run_command( [paths.SSSCTL, "domain-status", host.domain.name, "-o"] ) match = pattern.search(result.stdout_text) state = match.group('state') return state == 'Online' def wait_for_sssd_domain_status_online(host, timeout=120): """Wait up to timeout (in seconds) for sssd domain status to become Online The method is checking the Online Status of the domain as displayed by the command sssctl domain-status <domain> -o and returns successfully when the status is Online. This call is useful for instance when 389-ds has been stopped and restarted as SSSD may need a while before it reconnects and switches from Offline mode to Online. """ for _i in range(0, timeout, 5): if check_if_sssd_is_online(host): break time.sleep(5) else: raise RuntimeError("SSSD still offline") def get_sssd_version(host): """Get sssd version on remote host.""" version = host.run_command('sssd --version').stdout_text.strip() return parse_version(version) def get_pki_version(host): """Get pki version on remote host.""" data = host.get_file_contents("/usr/share/pki/VERSION", encoding="utf-8") groups = re.match(r'.*\nSpecification-Version: ([\d+\.]*)\n.*', data) if groups: version_string = groups.groups(0)[0] return parse_version(version_string) else: raise ValueError("get_pki_version: pki is not installed") def get_package_version(host, pkgname): """ Get package version on remote host """ platform = get_platform(host) if platform in ("rhel", "fedora"): cmd = host.run_command( ["rpm", "-qa", "--qf", "%{VERSION}", pkgname] ) get_package_version = cmd.stdout_text if not get_package_version: raise ValueError( "get_package_version: " "pkgname package is not installed" ) else: raise ValueError( "get_package_version: unknown platform %s" % platform ) return get_package_version def get_openldap_client_version(host): """Get openldap-clients version on remote host""" return get_package_version(host, 'openldap-clients') def get_healthcheck_version(host): return get_package_version(host, '*ipa-healthcheck') def wait_for_ipa_to_start(host, timeout=60): """Wait up to timeout seconds for ipa to start on a given host. If DS is restarted, and SSSD must be online, please consider using wait_for_sssd_domain_status_online(host) in the test after calling this method. """ interval = 1 end_time = datetime.now() + timedelta(seconds=timeout) for _i in range(0, timeout, interval): if datetime.now() > end_time: raise RuntimeError("Request timed out") time.sleep(interval) result = host.run_command( [paths.IPACTL, "status"], raiseonerr=False ) if result.returncode == 0: break def stop_ipa_server(host): """Stop the entire IdM server using the ipactl utility. """ host.run_command([paths.IPACTL, "stop"]) def start_ipa_server(host): """Start the entire IdM server using the ipactl utility """ host.run_command([paths.IPACTL, "start"]) def restart_ipa_server(host): """Restart the entire IdM server using the ipactl utility """ host.run_command([paths.IPACTL, "restart"]) def dns_update_system_records(host): """Runs "ipa dns-update-system-records" on "host". """ kinit_admin(host) host.run_command( ["ipa", "dns-update-system-records"] ) def run_ssh_cmd( from_host=None, to_host=None, username=None, cmd=None, auth_method=None, password=None, private_key_path=None, expect_auth_success=True, expect_auth_failure=None, verbose=True, connect_timeout=2, strict_host_key_checking=False ): """Runs an ssh connection from the controller to the host. - auth_method can be either "password" or "key". - In the first case, set password to the user's password ; in the second case, set private_key_path to the path of the private key. - If expect_auth_success or expect_auth_failure, analyze the ssh client's log and check whether the selected authentication method worked. expect_auth_failure takes precedence over expect_auth_success. - If verbose, display the ssh client verbose log. - Both expect_auth_success and verbose are True by default. Debugging ssh client failures is next to impossible without the associated debug log. Possible enhancements: - select which host to run from (currently: controller only) """ if from_host is not None: raise NotImplementedError( "from_host must be None ; running from anywhere but the " "controller is not implemented yet." ) if expect_auth_failure: expect_auth_success = False if to_host is None or username is None or auth_method is None: raise ValueError("host, username and auth_method are mandatory") if cmd is None: # cmd must run properly on all supported platforms. # true(1) ("do nothing, successfully") is the obvious candidate. cmd = "true" if auth_method == "password": if password is None: raise ValueError( "password is mandatory if auth_method == password" ) ssh_cmd = ( "ssh", "-v", "-o", "PubkeyAuthentication=no", "-o", "GSSAPIAuthentication=no", "-o", "ConnectTimeout={connect_timeout}".format( connect_timeout=connect_timeout ), ) elif auth_method == "key": if private_key_path is None: raise ValueError( "private_key_path is mandatory if auth_method == key" ) ssh_cmd = ( "ssh", "-v", "-o", "BatchMode=yes", "-o", "PubkeyAuthentication=yes", "-o", "GSSAPIAuthentication=no", "-o", "ConnectTimeout={connect_timeout}".format( connect_timeout=connect_timeout ), ) else: raise ValueError( "auth_method must either be password or key" ) ssh_cmd_1 = list(ssh_cmd) if strict_host_key_checking is True: ssh_cmd_1.extend(("-o", "StrictHostKeyChecking=yes")) else: ssh_cmd_1.extend(("-o", "StrictHostKeyChecking=no")) if auth_method == "password": ssh_cmd_1 = list(("sshpass", "-p", password)) + ssh_cmd_1 elif auth_method == "key": ssh_cmd_1.extend(("-i", private_key_path)) ssh_cmd_1.extend(("-l", username, to_host, cmd)) try: if verbose: output = "OpenSSH command: {sshcmd}".format(sshcmd=ssh_cmd_1) logger.info(output) remote_cmd = subprocess.Popen( ssh_cmd_1, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) while remote_cmd.poll() is None: time.sleep(0.1) return_code = remote_cmd.returncode stderr = os.linesep.join( str(line) for line in remote_cmd.stderr.readlines() ) stdout = os.linesep.join( str(line) for line in remote_cmd.stderr.readlines() ) if verbose: print_stdout = "Standard output: {stdout}".format(stdout=stdout) print_stderr = "Standard error: {stderr}".format(stderr=stderr) logger.info(print_stdout) logger.info(print_stderr) except Exception as e: pytest.fail("Unable to run ssh command.", e) if auth_method == "password": if expect_auth_success is True: patterns = [ r'Authenticated to .* using "keyboard-interactive"', r'Authentication succeeded \(keyboard-interactive\)' ] assert any(re.search(pattern, stderr) for pattern in patterns) # do not assert the return code: # it can be >0 if the command failed. elif expect_auth_failure is True: # sshpass return code: 5 for failed auth assert return_code == 5 assert "Authentication succeeded" not in stderr elif auth_method == "key": if expect_auth_success is True: patterns = [ r'Authenticated to .* using "publickey"', r'Authentication succeeded \(publickey\)' ] assert any(re.search(pattern, stderr) for pattern in patterns) # do not assert the return code: # it can be >0 if the command failed. elif expect_auth_failure is True: # ssh return code: 255 for failed auth assert return_code == 255 assert "Authentication succeeded" not in stderr assert "No more authentication methods to try." in stderr return (return_code, stdout, stderr) def is_package_installed(host, pkg): platform = get_platform(host) if platform in {'rhel', 'fedora'}: result = host.run_command( ['rpm', '-q', pkg], raiseonerr=False ) elif platform in {'debian', 'ubuntu'}: result = host.run_command( ['dpkg', '-s', pkg], raiseonerr=False ) else: raise ValueError( 'is_package_installed: unknown platform %s' % platform ) return result.returncode == 0 def move_date(host, chrony_cmd, date_str): """Helper method to move system date :param host: host on which date is to be manipulated :param chrony_cmd: systemctl command to apply to chrony service, for instance 'start', 'stop' :param date_str: date string to change the date i.e '3years2months1day1' """ host.run_command(['systemctl', chrony_cmd, 'chronyd']) host.run_command(['date', '-s', date_str]) def copy_files(source_host, dest_host, filelist): """Helper to copy a file from one host to another :param source_host: source host of the file to copy :param dest_host: destination host :param filelist: list of full path of files to copy """ for file in filelist: dest_host.transport.mkdir_recursive(os.path.dirname(file)) data = source_host.get_file_contents(file) dest_host.transport.put_file_contents(file, data)
101,756
Python
.py
2,478
32.20339
79
0.610659
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,321
host.py
freeipa_freeipa/ipatests/pytest_ipa/integration/host.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Host class for integration testing""" import re import subprocess import tempfile import ldap import pytest_multihost.host from ipaplatform.paths import paths from ipapython import ipaldap from .fips import ( is_fips_enabled, enable_userspace_fips, disable_userspace_fips ) from .transport import IPAOpenSSHTransport from .resolver import resolver FIPS_NOISE_RE = re.compile(br"FIPS mode initialized\r?\n?") class LDAPClientWithoutCertCheck(ipaldap.LDAPClient): """Adds an option to disable certificate check for TLS connection To disable certificate validity check create client with added option no_certificate_check: client = LDAPClientWithoutCertCheck(..., no_certificate_check=True) """ def __init__(self, *args, **kwargs): self._no_certificate_check = kwargs.pop( 'no_certificate_check', False) super(LDAPClientWithoutCertCheck, self).__init__(*args, **kwargs) def _connect(self): if (self._start_tls and self.protocol == 'ldap' and self._no_certificate_check): with self.error_handler(): conn = ipaldap.ldap_initialize( self.ldap_uri, cacertfile=self._cacert) conn.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) conn.set_option(ldap.OPT_X_TLS_NEWCTX, 0) conn.start_tls_s() return conn else: return super(LDAPClientWithoutCertCheck, self)._connect() class Host(pytest_multihost.host.Host): """Representation of a remote IPA host""" transport_class = IPAOpenSSHTransport def __init__(self, domain, hostname, role, ip=None, external_hostname=None, username=None, password=None, test_dir=None, host_type=None): super().__init__( domain, hostname, role, ip=ip, external_hostname=external_hostname, username=username, password=password, test_dir=test_dir, host_type=host_type ) self._fips_mode = None self._userspace_fips = False self.resolver = resolver(self) @property def is_fips_mode(self): """Check and cache if a system is in FIPS mode """ if self._fips_mode is None: self._fips_mode = is_fips_enabled(self) return self._fips_mode @property def is_userspace_fips(self): """Check if host uses fake userspace FIPS """ return self._userspace_fips def enable_userspace_fips(self): """Enable fake userspace FIPS mode The call has no effect if the system is already in FIPS mode. :return: True if system was modified, else None """ if not self.is_fips_mode: enable_userspace_fips(self) self._fips_mode = True self._userspace_fips = True return True else: return False def disable_userspace_fips(self): """Disable fake userspace FIPS mode The call has no effect if userspace FIPS mode is not enabled. :return: True if system was modified, else None """ if self.is_userspace_fips: disable_userspace_fips(self) self._userspace_fips = False self._fips_mode = False return True else: return False @staticmethod def _make_host(domain, hostname, role, ip, external_hostname): # We need to determine the type of the host, this depends on the domain # type, as we assume all Unix machines are in the Unix domain and # all Windows machine in a AD domain if domain.type == 'AD': cls = WinHost else: cls = Host return cls( domain, hostname, role, ip=ip, external_hostname=external_hostname ) def ldap_connect(self): """Return an LDAPClient authenticated to this host as directory manager """ self.log.info('Connecting to LDAP at %s', self.external_hostname) # get IPA CA cert to establish a secure connection cacert = self.get_file_contents(paths.IPA_CA_CRT) with tempfile.NamedTemporaryFile() as f: f.write(cacert) f.flush() hostnames_mismatch = self.hostname != self.external_hostname conn = LDAPClientWithoutCertCheck.from_hostname_secure( self.external_hostname, cacert=f.name, no_certificate_check=hostnames_mismatch) binddn = self.config.dirman_dn self.log.info('LDAP bind as %s', binddn) conn.simple_bind(binddn, self.config.dirman_password) # The CA cert file has been loaded into the SSL_CTX and is no # longer required. return conn @classmethod def from_env(cls, env, domain, hostname, role, index, domain_index): from ipatests.pytest_ipa.integration.env_config import host_from_env return host_from_env(env, domain, hostname, role, index, domain_index) def to_env(self, **kwargs): from ipatests.pytest_ipa.integration.env_config import host_to_env return host_to_env(self, **kwargs) def run_command(self, argv, set_env=True, stdin_text=None, log_stdout=True, raiseonerr=True, cwd=None, bg=False, encoding='utf-8', ok_returncode=0): """Wrapper around run_command to log stderr on raiseonerr=True :param ok_returncode: return code considered to be correct, you can pass an integer or sequence of integers """ result = super().run_command( argv, set_env=set_env, stdin_text=stdin_text, log_stdout=log_stdout, raiseonerr=False, cwd=cwd, bg=bg, encoding=encoding ) # in FIPS mode SSH may print noise to stderr, remove the string # "FIPS mode initialized" + optional newline. result.stderr_bytes = FIPS_NOISE_RE.sub(b'', result.stderr_bytes) try: result_ok = result.returncode in ok_returncode except TypeError: result_ok = result.returncode == ok_returncode if not result_ok and raiseonerr: result.log.error('stderr: %s', result.stderr_text) raise subprocess.CalledProcessError( result.returncode, argv, result.stdout_text, result.stderr_text ) else: return result def spawn_expect(self, argv, default_timeout=10, encoding='utf-8', extra_ssh_options=None): """Run command on remote host using IpaTestExpect""" return self.transport.spawn_expect(argv, default_timeout, encoding, extra_ssh_options) class WinHost(pytest_multihost.host.WinHost): """ Representation of a remote Windows host. This serves as a sketch class once we move from manual preparation of Active Directory to the automated setup. """ transport_class = IPAOpenSSHTransport
7,967
Python
.py
187
33.374332
79
0.637573
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,322
__init__.py
freeipa_freeipa/ipatests/pytest_ipa/integration/__init__.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2011 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Pytest plugin for IPA Integration tests""" from __future__ import print_function, absolute_import from pprint import pformat import logging import os import tempfile import shutil import re import functools import pytest from pytest_multihost import make_multihost_fixture from ipapython import ipautil from ipaplatform.paths import paths from ipaplatform.constants import constants from . import fips from .config import Config from .env_config import get_global_config from . import tasks logger = logging.getLogger(__name__) CLASS_LOGFILES = [ # BIND logs os.path.join(paths.NAMED_VAR_DIR, constants.NAMED_DATA_DIR), # dirsrv logs paths.VAR_LOG_DIRSRV, # IPA install logs paths.IPASERVER_INSTALL_LOG, paths.IPASERVER_ADTRUST_INSTALL_LOG, paths.IPASERVER_DNS_INSTALL_LOG, paths.IPASERVER_KRA_INSTALL_LOG, paths.IPACLIENT_INSTALL_LOG, paths.IPAREPLICA_INSTALL_LOG, paths.IPAREPLICA_CONNCHECK_LOG, paths.IPAREPLICA_CA_INSTALL_LOG, paths.IPA_CUSTODIA_AUDIT_LOG, paths.IPACLIENTSAMBA_INSTALL_LOG, paths.IPACLIENTSAMBA_UNINSTALL_LOG, paths.IPATRUSTENABLEAGENT_LOG, # IPA uninstall logs paths.IPASERVER_UNINSTALL_LOG, paths.IPACLIENT_UNINSTALL_LOG, # IPA upgrade logs paths.IPAUPGRADE_LOG, # IPA backup and restore logs paths.IPARESTORE_LOG, paths.IPABACKUP_LOG, # EPN log paths.IPAEPN_LOG, # kerberos related logs paths.KADMIND_LOG, paths.KRB5KDC_LOG, # httpd logs paths.VAR_LOG_HTTPD_DIR, # dogtag logs paths.VAR_LOG_PKI_DIR, # dogtag conf paths.PKI_TOMCAT_SERVER_XML, paths.PKI_TOMCAT + "/ca/CS.cfg", paths.PKI_TOMCAT + "/kra/CS.cfg", paths.PKI_TOMCAT_ALIAS_DIR, paths.PKI_TOMCAT_ALIAS_PWDFILE_TXT, # selinux logs paths.VAR_LOG_AUDIT, # sssd paths.VAR_LOG_SSSD_DIR, # system paths.RESOLV_CONF, paths.HOSTS, # IPA renewal lock paths.IPA_RENEWAL_LOCK, paths.LETS_ENCRYPT_LOG, # resolvers management paths.NETWORK_MANAGER_CONFIG, paths.NETWORK_MANAGER_CONFIG_DIR, paths.SYSTEMD_RESOLVED_CONF, paths.SYSTEMD_RESOLVED_CONF_DIR, '/var/log/samba', ] def make_class_logs(host): logs = list(CLASS_LOGFILES) env_filename = os.path.join(host.config.test_dir, 'env.sh') logs.append(env_filename) return logs def pytest_addoption(parser): group = parser.getgroup("IPA integration tests") group.addoption( '--logfile-dir', dest="logfile_dir", default=None, help="Directory to store integration test logs in.") def _get_logname_from_node(node): name = node.nodeid name = re.sub(r'\(\)/', '', name) # remove ()/ name = re.sub(r'[()]', '', name) # and standalone brackets name = re.sub(r'(/|::)', '-', name) return name def collect_test_logs(node, logs_dict, test_config, suffix=''): """Collect logs from a test Calls collect_logs and collect_systemd_journal :param node: The pytest collection node (request.node) :param logs_dict: Mapping of host to list of log filnames to collect :param test_config: Pytest configuration :param suffix: The custom suffix of the name of logfiles' directory """ name = '{node}{suffix}'.format( node=_get_logname_from_node(node), suffix=suffix, ) logfile_dir = test_config.getoption('logfile_dir') collect_logs( name=name, logs_dict=logs_dict, logfile_dir=logfile_dir, beakerlib_plugin=test_config.pluginmanager.getplugin('BeakerLibPlugin'), ) hosts = logs_dict.keys() # pylint: disable=dict-keys-not-iterating collect_systemd_journal(name, hosts, logfile_dir) def collect_systemd_journal(name, hosts, logfile_dir=None): """Collect systemd journal from remote hosts :param name: Name under which logs are collected, e.g. name of the test :param hosts: List of hosts from which to collect journal :param logfile_dir: Directory to log to """ if logfile_dir is None: return for host in hosts: logger.info("Collecting journal from: %s", host.hostname) topdirname = os.path.join(logfile_dir, name, host.hostname) if not os.path.exists(topdirname): os.makedirs(topdirname) # Get journal content cmd = host.run_command( ['journalctl', '--since', host.config.log_journal_since], log_stdout=False, raiseonerr=False) if cmd.returncode: logger.error('An error occurred while collecting journal') continue # Write journal to file with open(os.path.join(topdirname, "journal"), 'w') as f: f.write(cmd.stdout_text) def collect_logs(name, logs_dict, logfile_dir=None, beakerlib_plugin=None): """Collect logs from remote hosts Calls collect_logs :param name: Name under which logs arecollected, e.g. name of the test :param logs_dict: Mapping of host to list of log filnames to collect :param logfile_dir: Directory to log to :param beakerlib_plugin: BeakerLibProcess or BeakerLibPlugin used to collect tests for BeakerLib If neither logfile_dir nor beakerlib_plugin is given, no tests are collected. """ if logs_dict and (logfile_dir or beakerlib_plugin): if logfile_dir: remove_dir = False else: logfile_dir = tempfile.mkdtemp() remove_dir = True topdirname = os.path.join(logfile_dir, name) for host, logs in logs_dict.items(): logger.info('Collecting logs from: %s', host.hostname) # make list of unique log filenames logs = list(set(logs)) dirname = os.path.join(topdirname, host.hostname) if not os.path.isdir(dirname): os.makedirs(dirname) tarname = os.path.join(dirname, 'logs.tar.xz') # get temporary file name cmd = host.run_command(['mktemp']) tmpname = cmd.stdout_text.strip() # Tar up the logs on the remote server cmd = host.run_command( [ "tar", "cJvf", tmpname, "--ignore-failed-read", "--warning=no-failed-read", "--dereference", ] + logs, log_stdout=False, raiseonerr=False, ) if cmd.returncode: logger.warning('Could not collect all requested logs') # fetch tar file with open(tarname, 'wb') as f: f.write(host.get_file_contents(tmpname)) # delete from remote host.run_command(['rm', '-f', tmpname]) # Unpack on the local side ipautil.run([paths.TAR, 'xJvf', 'logs.tar.xz'], cwd=dirname, raiseonerr=False) os.unlink(tarname) if beakerlib_plugin: # Use BeakerLib's rlFileSubmit on the indifidual files # The resulting submitted filename will be # $HOSTNAME-$FILENAME (with '/' replaced by '-') beakerlib_plugin.run_beakerlib_command(['pushd', topdirname]) try: for dirpath, _dirnames, filenames in os.walk(topdirname): for filename in filenames: fullname = os.path.relpath( os.path.join(dirpath, filename), topdirname) logger.debug('Submitting file: %s', fullname) beakerlib_plugin.run_beakerlib_command( ['rlFileSubmit', fullname]) finally: beakerlib_plugin.run_beakerlib_command(['popd']) if remove_dir: if beakerlib_plugin: # The BeakerLib process runs asynchronously, let it clean up # after it's done with the directory beakerlib_plugin.run_beakerlib_command( ['rm', '-rvf', topdirname]) else: shutil.rmtree(topdirname) class IntegrationLogs: """Represent logfile collections Collection is a mapping of IPA hosts and a list of logfiles to be collected. There are two types of collections: class and method. The former contains a list of logfiles which will be collected on each test (within class) completion, while the latter contains a list of logfiles which will be collected on only certain test completion (once). """ def __init__(self): self._class_logs = {} self._method_logs = {} def set_logs(self, host, logs): self._class_logs[host] = list(logs) @property def method_logs(self): return self._method_logs @property def class_logs(self): return self._class_logs def init_method_logs(self): """Initilize method logs with the class ones""" self._method_logs = {} for host, logs in self._class_logs.items(): self._method_logs[host] = list(logs) def collect_class_log(self, host, filename): """Add class scope log The file with the given filename will be collected from the host on an each test completion(within a test class). """ logger.info('Adding %s:%s to list of class logs to collect', host.external_hostname, filename) self._class_logs.setdefault(host, []).append(filename) self._method_logs.setdefault(host, []).append(filename) def collect_method_log(self, host, filename): """Add method scope log The file with the given filename will be collected from the host on a test completion. """ logger.info('Adding %s:%s to list of method logs to collect', host.external_hostname, filename) self._method_logs.setdefault(host, []).append(filename) @pytest.fixture(scope='class') def class_integration_logs(request): """Internal fixture providing class-level logs_dict For adjusting collection of logs, please, use 'integration_logs' fixture. """ integration_logs = IntegrationLogs() yield integration_logs # since the main fixture of integration tests('mh') depends on # this one the class logs collecting happens *after* the teardown # of that fixture. The 'uninstall' is among the finalizers of 'mh'. # This means that the logs collected here are the IPA *uninstall* # logs. class_logs = integration_logs.class_logs collect_test_logs(request.node, class_logs, request.config, suffix='-uninstall') @pytest.fixture def integration_logs(class_integration_logs, request): """Provides access to test integration logs, and collects after each test To collect a logfile on a test completion one should add the dependency on this fixture and call its 'collect_method_log' method. For example, run TestFoo. ``` class TestFoo(IntegrationTest): def test_foo(self): pass def test_bar(self, integration_logs): integration_logs.collect_method_log(self.master, '/logfile') ``` '/logfile' will be collected only for 'test_bar' test. To collect a logfile on a test class completion one should add the dependency on this fixture and call its 'collect_class_log' method. For example, run TestFoo. ``` class TestFoo(IntegrationTest): def test_foo(self, integration_logs): integration_logs.collect_class_log(self.master, '/logfile') def test_bar(self): pass ``` '/logfile' will be collected 3 times: 1) on 'test_foo' completion 2) on 'test_bar' completion 3) on 'TestFoo' completion Note, the registration of a collection works at the runtime. This means that if the '/logfile' will be registered in 'test_bar' then it will not be collected on 'test_foo' completion: 1) on 'test_bar' completion 2) on 'TestFoo' completion """ class_integration_logs.init_method_logs() yield class_integration_logs method_logs = class_integration_logs.method_logs collect_test_logs(request.node, method_logs, request.config) @pytest.fixture(scope='class') def mh(request, class_integration_logs): """IPA's multihost fixture object """ cls = request.cls domain_description = { 'type': 'IPA', 'hosts': { 'master': 1, 'replica': cls.num_replicas, 'client': cls.num_clients, }, } domain_description['hosts'].update( {role: 1 for role in cls.required_extra_roles}) domain_descriptions = [domain_description] for _i in range(cls.num_ad_domains): domain_descriptions.append({ 'type': 'AD', 'hosts': {'ad': 1} }) for _i in range(cls.num_ad_subdomains): domain_descriptions.append({ 'type': 'AD_SUBDOMAIN', 'hosts': {'ad_subdomain': 1} }) for _i in range(cls.num_ad_treedomains): domain_descriptions.append({ 'type': 'AD_TREEDOMAIN', 'hosts': {'ad_treedomain': 1} }) mh = make_multihost_fixture( request, domain_descriptions, config_class=Config, _config=get_global_config(), ) mh.domain = mh.config.domains[0] [mh.master] = mh.domain.hosts_by_role('master') mh.replicas = mh.domain.hosts_by_role('replica') mh.clients = mh.domain.hosts_by_role('client') ad_domains = mh.config.ad_domains if ad_domains: mh.ads = [] for domain in ad_domains: mh.ads.extend(domain.hosts_by_role('ad')) mh.ad_subdomains = [] for domain in ad_domains: mh.ad_subdomains.extend(domain.hosts_by_role('ad_subdomain')) mh.ad_treedomains = [] for domain in ad_domains: mh.ad_treedomains.extend(domain.hosts_by_role('ad_treedomain')) cls.logs_to_collect = class_integration_logs.class_logs if logger.isEnabledFor(logging.INFO): logger.info(pformat(mh.config.to_dict())) for ipa_host in mh.config.get_all_ipa_hosts(): class_integration_logs.set_logs(ipa_host, make_class_logs(ipa_host)) for host in mh.config.get_all_hosts(): logger.info('Preparing host %s', host.hostname) tasks.prepare_host(host) add_compat_attrs(cls, mh) def fin(): del_compat_attrs(cls) mh._pytestmh_request.addfinalizer(fin) try: yield mh.install() finally: # the 'mh' fixture depends on 'class_integration_logs' one, # thus, the class logs collecting happens *after* the teardown # of 'mh' fixture. The 'uninstall' is among the finalizers of 'mh'. # This means that the logs collected here are the IPA *uninstall* # logs and the 'install' ones can be removed during the IPA # uninstall phase. To address this problem(e.g. installation error) # the install logs will be collected into '{nodeid}-install' directory # while the uninstall ones into '{nodeid}-uninstall'. class_logs = class_integration_logs.class_logs collect_test_logs(request.node, class_logs, request.config, suffix='-install') def add_compat_attrs(cls, mh): """Add convenience attributes to the test class This is deprecated in favor of the mh fixture. To be removed when no more tests using this. """ cls.domain = mh.domain cls.master = mh.master cls.replicas = mh.replicas cls.clients = mh.clients cls.ad_domains = mh.config.ad_domains if cls.ad_domains: cls.ads = mh.ads cls.ad_subdomains = mh.ad_subdomains cls.ad_treedomains = mh.ad_treedomains def del_compat_attrs(cls): """Remove convenience attributes from the test class This is deprecated in favor of the mh fixture. To be removed when no more tests using this. """ del cls.master del cls.replicas del cls.clients del cls.domain if cls.ad_domains: del cls.ads del cls.ad_subdomains del cls.ad_treedomains del cls.ad_domains def skip_if_fips(reason='Not supported in FIPS mode', host='master'): if callable(reason): raise TypeError('Invalid decorator usage, add "()"') def decorator(test_method): @functools.wraps(test_method) def wrapper(instance, *args, **kwargs): if fips.is_fips_enabled(getattr(instance, host)): pytest.skip(reason) else: test_method(instance, *args, **kwargs) return wrapper return decorator
17,526
Python
.py
445
31.707865
80
0.64736
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,323
firewall.py
freeipa_freeipa/ipatests/pytest_ipa/integration/firewall.py
# # Copyright (C) 2018 FreeIPA Contributors. See COPYING for license # """Firewall class for integration testing using firewalld""" import abc from ipapython import ipautil class FirewallBase(abc.ABC): def __init__(self, host): """Initialize with host where firewall changes should be applied""" @abc.abstractmethod def run(self): """Enable and start firewall service""" @abc.abstractmethod def enable_service(self, service): """Enable firewall rules for service""" @abc.abstractmethod def disable_service(self, service): """Disable firewall rules for service""" @abc.abstractmethod def enable_services(self, services): """Enable firewall rules for list of services""" @abc.abstractmethod def disable_services(self, services): """Disable firewall rules for list of services""" @abc.abstractmethod def passthrough_rule(self, rule, ipv=None): """Generic method to get direct passthrough rules to rule is an ip[6]tables rule without using the ip[6]tables command. The rule will per default be added to the IPv4 and IPv6 firewall. If there are IP version specific parts in the rule, please make sure that ipv is adapted properly. The rule is added to the direct sub chain of the chain that is used in the rule""" @abc.abstractmethod def add_passthrough_rules(self, rules, ipv=None): """Add passthough rules to the end of the chain rules is a list of ip[6]tables rules, where the first entry of each rule is the chain. No --append/-A, --delete/-D should be added before the chain name, beacuse these are added by the method. If there are IP version specific parts in the rule, please make sure that ipv is adapted properly. """ @abc.abstractmethod def prepend_passthrough_rules(self, rules, ipv=None): """Insert passthough rules starting at position 1 as a block rules is a list of ip[6]tables rules, where the first entry of each rule is the chain. No --append/-A, --delete/-D should be added before the chain name, beacuse these are added by the method. If there are IP version specific parts in the rule, please make sure that ipv is adapted properly. """ @abc.abstractmethod def remove_passthrough_rules(self, rules, ipv=None): """Remove passthrough rules rules is a list of ip[6]tables rules, where the first entry of each rule is the chain. No --append/-A, --delete/-D should be added before the chain name, beacuse these are added by the method. If there are IP version specific parts in the rule, please make sure that ipv is adapted properly. """ class NoOpFirewall(FirewallBase): """ no-op firewall is intended for platforms which haven't high level firewall backend. """ def run(self): pass def enable_service(self, service): pass def disable_service(self, service): pass def enable_services(self, services): pass def disable_services(self, services): pass def passthrough_rule(self, rule, ipv=None): pass def add_passthrough_rules(self, rules, ipv=None): pass def prepend_passthrough_rules(self, rules, ipv=None): pass def remove_passthrough_rules(self, rules, ipv=None): pass class FirewallD(FirewallBase): def __init__(self, host): """Initialize with host where firewall changes should be applied""" self.host = host def run(self): # Unmask firewalld service self.host.run_command(["systemctl", "unmask", "firewalld"]) # Enable firewalld service self.host.run_command(["systemctl", "enable", "firewalld"]) # Start firewalld service self.host.run_command(["systemctl", "start", "firewalld"]) def _rp_action(self, args): """Run-time and permanant firewall action""" cmd = ["firewall-cmd"] cmd.extend(args) # Run-time part result = self.host.run_command(cmd, raiseonerr=False) if result.returncode not in [0, 11, 12]: # Ignore firewalld error codes: # 11 is ALREADY_ENABLED # 12 is NOT_ENABLED raise ipautil.CalledProcessError(result.returncode, cmd, result.stdout_text, result.stderr_text) # Permanent part result = self.host.run_command(cmd + ["--permanent"], raiseonerr=False) if result.returncode not in [0, 11, 12]: # Ignore firewalld error codes: # 11 is ALREADY_ENABLED # 12 is NOT_ENABLED raise ipautil.CalledProcessError(result.returncode, cmd, result.stdout_text, result.stderr_text) def enable_service(self, service): """Enable firewall service in firewalld runtime and permanent environment""" self._rp_action(["--add-service", service]) def disable_service(self, service): """Disable firewall service in firewalld runtime and permanent environment""" self._rp_action(["--remove-service", service]) def enable_services(self, services): """Enable list of firewall services in firewalld runtime and permanent environment""" args = [] for service in services: args.extend(["--add-service", service]) self._rp_action(args) def disable_services(self, services): """Disable list of firewall services in firewalld runtime and permanent environment""" args = [] for service in services: args.extend(["--remove-service", service]) self._rp_action(args) def passthrough_rule(self, rule, ipv=None): """Generic method to get direct passthrough rules to firewalld rule is an ip[6]tables rule without using the ip[6]tables command. The rule will per default be added to the IPv4 and IPv6 firewall. If there are IP version specific parts in the rule, please make sure that ipv is adapted properly. The rule is added to the direct sub chain of the chain that is used in the rule""" if ipv is None: ipvs = ["ipv4", "ipv6"] else: ipvs = [ipv] for _ipv in ipvs: args = ["firewall-cmd", "--direct", "--passthrough", _ipv] + rule self.host.run_command(args) def add_passthrough_rules(self, rules, ipv=None): """Add passthough rules to the end of the chain rules is a list of ip[6]tables rules, where the first entry of each rule is the chain. No --append/-A, --delete/-D should be added before the chain name, beacuse these are added by the method. If there are IP version specific parts in the rule, please make sure that ipv is adapted properly. """ for rule in rules: self.passthrough_rule(["-A"] + rule, ipv) def prepend_passthrough_rules(self, rules, ipv=None): """Insert passthough rules starting at position 1 as a block rules is a list of ip[6]tables rules, where the first entry of each rule is the chain. No --append/-A, --delete/-D should be added before the chain name, beacuse these are added by the method. If there are IP version specific parts in the rule, please make sure that ipv is adapted properly. """ # first rule number in iptables is 1 for i, rule in enumerate(rules, start=1): self.passthrough_rule(["-I", rule[0], str(i)] + rule[1:], ipv) def remove_passthrough_rules(self, rules, ipv=None): """Remove passthrough rules rules is a list of ip[6]tables rules, where the first entry of each rule is the chain. No --append/-A, --delete/-D should be added before the chain name, beacuse these are added by the method. If there are IP version specific parts in the rule, please make sure that ipv is adapted properly. """ for rule in rules: self.passthrough_rule(["-D"] + rule, ipv) class Firewall(FirewallBase): """ Depending on the ipaplatform proxy firewall tasks to the actual backend. Current supported backends: firewalld and no-op firewall. """ def __init__(self, host): """Initialize with host where firewall changes should be applied""" # break circular dependency from .tasks import get_platform # pylint: disable=cyclic-import self.host = host platform = get_platform(host) firewalls = { 'rhel': FirewallD, 'fedora': FirewallD, 'debian': FirewallD, 'ubuntu': FirewallD, 'altlinux': NoOpFirewall, } if platform not in firewalls: raise ValueError( "Platform {} doesn't support Firewall".format(platform)) self.firewall = firewalls[platform](self.host) self.run() def run(self): self.firewall.run() def enable_service(self, service): self.firewall.enable_service(service) def disable_service(self, service): self.firewall.disable_service(service) def enable_services(self, services): self.firewall.enable_services(services) def disable_services(self, services): self.firewall.disable_services(services) def passthrough_rule(self, rule, ipv=None): self.firewall.passthrough_rule(rule, ipv) def add_passthrough_rules(self, rules, ipv=None): self.firewall.add_passthrough_rules(rules, ipv) def prepend_passthrough_rules(self, rules, ipv=None): self.firewall.prepend_passthrough_rules(rules, ipv) def remove_passthrough_rules(self, rules, ipv=None): self.firewall.remove_passthrough_rules(rules, ipv)
10,164
Python
.py
226
35.876106
78
0.639324
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,324
create_bridge.py
freeipa_freeipa/ipatests/pytest_ipa/integration/create_bridge.py
import re import textwrap from ipatests.pytest_ipa.integration import tasks def setup_scim_server(host, version="main"): dir = "/opt/ipa-tuura" password = host.config.admin_password tasks.install_packages(host, ["unzip", "java-11-openjdk-headless", "openssl", "maven", "wget", "git", "firefox", "xorg-x11-server-Xvfb", "python3-pip"]) # Download ipa-tuura project url = "https://github.com/freeipa/ipa-tuura" host.run_command(["git", "clone", "-b", f"{version}", f"{url}", f"{dir}"]) # Prepare SSSD config host.run_command(["python", "./prepare_sssd.py"], cwd=f"{dir}/src/install") # Get keytab for scim bridge service master = host.domain.hosts_by_role("master")[0].hostname princ = f"admin@{host.domain.realm}" ktfile = "/root/scim.keytab" sendpass = f"{password}\n{password}" tasks.kdestroy_all(host) tasks.kinit_admin(host) host.run_command(["ipa-getkeytab", "-s", master, "-p", princ, "-P", "-k", ktfile], stdin_text=sendpass) host.run_command(["kinit", "-k", "-t", ktfile, princ]) # Install django requirements django_reqs = f"{dir}/src/install/requirements.txt" host.run_command(["pip", "install", "-r", f"{django_reqs}"]) # Prepare models and database host.run_command(["python", "manage.py", "makemigrations", "scim"], cwd=f"{dir}/src/ipa-tuura") host.run_command(["python", "manage.py", "migrate"], cwd=f"{dir}/src/ipa-tuura") # Add necessary admin vars to bashrc env_vars = textwrap.dedent(f""" export DJANGO_SUPERUSER_PASSWORD={password} export DJANGO_SUPERUSER_USERNAME=scim export DJANGO_SUPERUSER_EMAIL=scim@{host.domain.name} """) tasks.backup_file(host, '/etc/bashrc') content = host.get_file_contents('/etc/bashrc', encoding='utf-8') new_content = content + f"\n{env_vars}" host.put_file_contents('/etc/bashrc', new_content) host.run_command(['bash']) # Create django admin host.run_command(["python", "manage.py", "createsuperuser", "--scim_username", "scim", "--noinput"], cwd=f"{dir}/src/ipa-tuura") # Open allowed hosts to any for testing regex = r"^(ALLOWED_HOSTS) .*$" replace = r"\1 = ['*']" settings_file = f"{dir}/src/ipa-tuura/root/settings.py" settings = host.get_file_contents(settings_file, encoding='utf-8') new_settings = re.sub(regex, replace, settings, flags=re.MULTILINE) host.put_file_contents(settings_file, new_settings) # Setup keycloak service and config files contents = textwrap.dedent(f""" DJANGO_SUPERUSER_USERNAME=scim DJANGO_SUPERUSER_PASSWORD={password} DJANGO_SUPERUSER_EMAIL=scim@{host.domain.name} """) host.put_file_contents("/etc/sysconfig/scim", contents) manage = f"{dir}/src/ipa-tuura/manage.py" contents = textwrap.dedent(f""" [Unit] Description=SCIMv2 Bridge Server After=network.target [Service] Type=idle WorkingDirectory={dir}/src/ipa-tuura/ EnvironmentFile=/etc/sysconfig/scim # Fix this later # User=scim # Group=scim ExecStart=/usr/bin/python {manage} runserver 0.0.0.0:8000 TimeoutStartSec=600 TimeoutStopSec=600 [Install] WantedBy=multi-user.target """) host.put_file_contents("/etc/systemd/system/scim.service", contents) host.run_command(["systemctl", "daemon-reload"]) host.run_command(["systemctl", "start", "scim"]) def setup_keycloak_scim_plugin(host, bridge_server): dir = "/opt/keycloak" password = host.config.admin_password # Install needed packages tasks.install_packages(host, ["unzip", "java-11-openjdk-headless", "openssl", "maven"]) # Add necessary admin vars to bashrc env_vars = textwrap.dedent(f""" export KEYCLOAK_PATH={dir} """) content = host.get_file_contents('/etc/bashrc', encoding='utf-8') new_content = content + f"\n{env_vars}" host.put_file_contents('/etc/bashrc', new_content) host.run_command(['bash']) # Download keycloak plugin zipfile = "scim-keycloak-user-storage-spi/archive/refs/tags/0.1.zip" url = f"https://github.com/justin-stephenson/{zipfile}" dest = "/tmp/keycloak-scim-plugin.zip" host.run_command(["wget", "-O", dest, url]) # Unzip keycloak plugin host.run_command(["unzip", dest, "-d", "/tmp"]) # Install plugin host.run_command(["./redeploy-plugin.sh"], cwd="/tmp/scim-keycloak-user-storage-spi-0.1") # Fix ownership of plugin files host.run_command(["chown", "-R", "keycloak:keycloak", dir]) # Restore SELinux contexts host.run_command(["restorecon", "-R", f"{dir}"]) # Rerun Keycloak build step and restart to pickup plugin # This relies on the KC_* vars set in /etc/bashrc from create_keycloak.py host.run_command(['su', '-', 'keycloak', '-c', '/opt/keycloak/bin/kc.sh build']) host.run_command(["systemctl", "restart", "keycloak"]) host.run_command(["/opt/keycloak/bin/kc.sh", "show-config"]) # Login to keycloak as admin kcadmin_sh = "/opt/keycloak/bin/kcadm.sh" kcadmin = [kcadmin_sh, "config", "credentials", "--server", f"https://{host.hostname}:8443/auth/", "--realm", "master", "--user", "admin", "--password", password] tasks.run_repeatedly(host, kcadmin, timeout=60) # Configure SCIM User Storage to point to Bridge server provider_type = "org.keycloak.storage.UserStorageProvider" host.run_command([kcadmin_sh, "create", "components", "-r", "master", "-s", "name=scimprov", "-s", "providerId=scim", "-s", f"providerType={provider_type}", "-s", "parentId=master", "-s", f'config.scimurl=["{bridge_server}:8000"]', "-s", 'config.loginusername=["scim"]', "-s", f'config.loginpassword=["{password}"]']) def uninstall_scim_server(host): host.run_command(["systemctl", "stop", "scim"], raiseonerr=False) host.run_command(["rm", "-rf", "/opt/ipa-tuura", "/etc/sysconfig/scim", "/etc/systemd/system/scim.service", "/tmp/scim-keycloak-user-storage-spi-0.1", "/tmp/keycloak-scim-plugin.zip", "/root/scim.keytab"]) host.run_command(["systemctl", "daemon-reload"]) tasks.restore_files(host) def uninstall_scim_plugin(host): host.run_command(["rm", "-rf", "/tmp/scim-keycloak-user-storage-spi-0.1", "/tmp/keycloak-scim-plugin.zip"])
6,912
Python
.py
150
37.3
78
0.607371
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,325
fips.py
freeipa_freeipa/ipatests/pytest_ipa/integration/fips.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # """FIPS testing helpers Based on userspace FIPS mode by Ondrej Moris. Userspace FIPS mode fakes a Kernel in FIPS enforcing mode. User space programs behave like the Kernel was booted in FIPS enforcing mode. Kernel space code still runs in standard mode. """ import os from ipaplatform.paths import paths FIPS_OVERLAY_DIR = "/var/tmp/userspace-fips" FIPS_OVERLAY = os.path.join(FIPS_OVERLAY_DIR, "fips_enabled") SYSTEM_FIPS = "/etc/system-fips" def is_fips_enabled(host): """Check if host has """ result = host.run_command( ["cat", paths.PROC_FIPS_ENABLED], raiseonerr=False ) if result.returncode == 1: # FIPS mode not available return None elif result.returncode == 0: return result.stdout_text.strip() == "1" else: raise RuntimeError(result.stderr_text) def enable_userspace_fips(host): # create /etc/system-fips host.put_file_contents(SYSTEM_FIPS, "# userspace fips\n") # fake Kernel FIPS mode with bind mount host.run_command(["mkdir", "-p", FIPS_OVERLAY_DIR]) host.put_file_contents(FIPS_OVERLAY, "1\n") host.run_command( ["chcon", "-t", "sysctl_crypto_t", "-u", "system_u", FIPS_OVERLAY] ) host.run_command( ["mount", "--bind", FIPS_OVERLAY, paths.PROC_FIPS_ENABLED] ) # set crypto policy to FIPS mode host.run_command(["update-crypto-policies", "--show"]) host.run_command(["update-crypto-policies", "--set", "FIPS"]) # sanity check assert is_fips_enabled(host) result = host.run_command( ["openssl", "md5", "/dev/null"], raiseonerr=False ) assert result.returncode == 1 assert "Error setting digest" in result.stderr_text def disable_userspace_fips(host): host.run_command(["rm", "-f", SYSTEM_FIPS]) host.run_command(["update-crypto-policies", "--set", "DEFAULT"]) result = host.run_command( ["umount", paths.PROC_FIPS_ENABLED], raiseonerr=False ) host.run_command(["rm", "-rf", FIPS_OVERLAY_DIR]) if result.returncode != 0: raise RuntimeError(result.stderr_text) # sanity check assert not is_fips_enabled(host) host.run_command(["openssl", "md5", "/dev/null"]) def enable_crypto_subpolicy(host, subpolicy): result = host.run_command(["update-crypto-policies", "--show"]) policy = result.stdout_text.strip() + ":" + subpolicy host.run_command(["update-crypto-policies", "--set", policy])
2,503
Python
.py
64
34.421875
74
0.676967
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,326
resolver.py
freeipa_freeipa/ipatests/pytest_ipa/integration/resolver.py
import os import abc import logging import re import textwrap import time from ipaplatform.paths import paths logger = logging.getLogger(__name__) class Resolver(abc.ABC): def __init__(self, host): self.host = host self.backups = [] self.current_state = self._get_state() logger.info('Obtained initial resolver state for host %s: %s', self.host, self.current_state) def setup_resolver(self, nameservers, searchdomains=None): """Configure DNS resolver :param nameservers: IP address of nameserver or a list of addresses :param searchdomains: searchdomain or list of searchdomains. None - do not configure Resolver.backup() must be called prior to using this method. Raises exception if configuration was changed externally since last call to any method of Resolver class. """ if len(self.backups) == 0: raise Exception( 'Changing resolver state without backup is forbidden') self.check_state_expected() if isinstance(nameservers, str): nameservers = [nameservers] if isinstance(searchdomains, str): searchdomains = [searchdomains] if searchdomains is None: searchdomains = [] logger.info( 'Setting up resolver for host %s: nameservers=%s, searchdomains=%s', self.host, nameservers, searchdomains ) state = self._make_state_from_args(nameservers, searchdomains) self._set_state(state) def backup(self): """Saves current configuration to stack Raises exception if configuration was changed externally since last call to any method of Resolver class. """ self.check_state_expected() self.backups.append(self._get_state()) logger.info( 'Saved resolver state for host %s, number of saved states: %s', self.host, len(self.backups) ) def restore(self): """Restore configuration from stack of backups. Raises exception if configuration was changed externally since last call to any method of Resolver class. """ if len(self.backups) == 0: raise Exception('No resolver backups found for host {}'.format( self.host)) self.check_state_expected() self._set_state(self.backups.pop()) logger.info( 'Restored resolver state for host %s, number of saved states: %s', self.host, len(self.backups) ) def has_backups(self): """Checks if stack of backups is not empty""" return bool(self.backups) def check_state_expected(self): """Checks if resolver configuration has not changed. Raises AssertionError if actual configuration has changed since last call to any method of Resolver """ assert self._get_state() == self.current_state, ( 'Resolver state changed unexpectedly at host {}'.format(self.host)) def __enter__(self): self.backup() return self def __exit__(self, exc_type, exc_val, exc_tb): self.restore() def _set_state(self, state): self._apply_state(state) logger.info('Applying resolver state for host %s: %s', self.host, state) self.current_state = state @classmethod @abc.abstractmethod def is_our_resolver(cls, host): """Checks if the class is appropriate for managing resolver on the host. """ @abc.abstractmethod def _make_state_from_args(self, nameservers, searchdomains): """ :param nameservers: list of ip addresses of nameservers :param searchdomains: list of searchdomain, can be an empty list :return: internal state object specific to subclass implementaion """ @abc.abstractmethod def _get_state(self): """Acquire actual host configuration. :return: internal state object specific to subclass implementaion """ @abc.abstractmethod def _apply_state(self, state): """Apply configuration to host. :param state: internal state object specific to subclass implementaion """ def uses_localhost_as_dns(self): """Return true if the localhost is set as DNS server. Default implementation checks the content of /etc/resolv.conf """ resolvconf = self.host.get_file_contents(paths.RESOLV_CONF, 'utf-8') patterns = [r"^\s*nameserver\s+127\.0\.0\.1\s*$", r"^\s*nameserver\s+::1\s*$"] return any(re.search(p, resolvconf, re.MULTILINE) for p in patterns) class ResolvedResolver(Resolver): RESOLVED_RESOLV_CONF = { "/run/systemd/resolve/stub-resolv.conf", "/run/systemd/resolve/resolv.conf", "/lib/systemd/resolv.conf", "/usr/lib/systemd/resolv.conf", } RESOLVED_CONF_FILE = ( '/etc/systemd/resolved.conf.d/zzzz-ipatests-nameservers.conf') RESOLVED_CONF = textwrap.dedent(''' # generated by IPA tests [Resolve] DNS={nameservers} Domains=~. {searchdomains} ''') @classmethod def is_our_resolver(cls, host): res = host.run_command( ['stat', '--format', '%F', paths.RESOLV_CONF]) filetype = res.stdout_text.strip() if filetype == 'symbolic link': res = host.run_command(['realpath', paths.RESOLV_CONF]) return (res.stdout_text.strip() in cls.RESOLVED_RESOLV_CONF) return False def _restart_resolved(self): # Restarting service at rapid pace (which is what happens in some test # scenarios) can exceed the threshold configured in systemd option # StartLimitIntervalSec. In that case restart fails, but we can simply # continue trying until it succeeds from . import tasks # pylint: disable=cyclic-import tasks.run_repeatedly( self.host, ['systemctl', 'restart', 'systemd-resolved.service'], timeout=15) def _make_state_from_args(self, nameservers, searchdomains): return { 'resolved_config': self.RESOLVED_CONF.format( nameservers=' '.join(nameservers), searchdomains=' '.join(searchdomains)) } def _get_state(self): exists = self.host.transport.file_exists(self.RESOLVED_CONF_FILE) return { 'resolved_config': self.host.get_file_contents(self.RESOLVED_CONF_FILE, 'utf-8') if exists else None } def _apply_state(self, state): if state['resolved_config'] is None: self.host.run_command(['rm', '-f', self.RESOLVED_CONF_FILE]) else: self.host.run_command( ['mkdir', '-p', os.path.dirname(self.RESOLVED_CONF_FILE)]) self.host.put_file_contents( self.RESOLVED_CONF_FILE, state['resolved_config']) self._restart_resolved() def uses_localhost_as_dns(self): """Return true if the localhost is set as DNS server. When systemd-resolved is in use, the DNS can be found using the command resolvectldns. """ dnsconf = self.host.run_command(['resolvectl', 'dns']).stdout_text patterns = [r"^Global:.*\s+127.0.0.1\s+.*$", r"^Global:.*\s+::1\s+.*$"] return any(re.search(p, dnsconf, re.MULTILINE) for p in patterns) class PlainFileResolver(Resolver): IPATESTS_RESOLVER_COMMENT = '# created by ipatests' @classmethod def is_our_resolver(cls, host): res = host.run_command( ['stat', '--format', '%F', paths.RESOLV_CONF]) filetype = res.stdout_text.strip() if filetype == 'regular file': # We want to be sure that /etc/resolv.conf is not generated # by NetworkManager or systemd-resolved. When it is then # the first line of the file is a comment of the form: # # Generated by NetworkManager # # or # # This file is managed by man:systemd-resolved(8). Do not edit. # # So we check that either first line of resolv.conf # is not a comment or the comment does not mention NM or # systemd-resolved resolv_conf = host.get_file_contents(paths.RESOLV_CONF, 'utf-8') line = resolv_conf.splitlines()[0].strip() return not line.startswith('#') or all([ 'resolved' not in line, 'NetworkManager' not in line ]) return False def _make_state_from_args(self, nameservers, searchdomains): contents_lines = [self.IPATESTS_RESOLVER_COMMENT] contents_lines.extend('nameserver {}'.format(r) for r in nameservers) if searchdomains: contents_lines.append('search {}'.format(' '.join(searchdomains))) contents = '\n'.join(contents_lines) return {'resolv_conf': contents} def _get_state(self): return { 'resolv_conf': self.host.get_file_contents( paths.RESOLV_CONF, 'utf-8') } def _apply_state(self, state): self.host.put_file_contents(paths.RESOLV_CONF, state['resolv_conf']) class NetworkManagerResolver(Resolver): NM_CONF_FILE = '/etc/NetworkManager/conf.d/zzzz-ipatests.conf' NM_CONF = textwrap.dedent(''' # generated by IPA tests [main] dns=default [global-dns] searches={searchdomains} [global-dns-domain-*] servers={nameservers} ''') @classmethod def is_our_resolver(cls, host): res = host.run_command( ['stat', '--format', '%F', paths.RESOLV_CONF]) filetype = res.stdout_text.strip() if filetype == 'regular file': resolv_conf = host.get_file_contents(paths.RESOLV_CONF, 'utf-8') return resolv_conf.startswith('# Generated by NetworkManager') return False def _restart_network_manager(self): # Restarting service at rapid pace (which is what happens in some test # scenarios) can exceed the threshold configured in systemd option # StartLimitIntervalSec. In that case restart fails, but we can simply # continue trying until it succeeds from . import tasks # pylint: disable=cyclic-import tasks.run_repeatedly( self.host, ['systemctl', 'restart', 'NetworkManager.service'], timeout=15) def _make_state_from_args(self, nameservers, searchdomains): return {'nm_config': self.NM_CONF.format( nameservers=','.join(nameservers), searchdomains=','.join(searchdomains))} def _get_state(self): exists = self.host.transport.file_exists(self.NM_CONF_FILE) return { 'nm_config': self.host.get_file_contents(self.NM_CONF_FILE, 'utf-8') if exists else None } def _apply_state(self, state): def get_resolv_conf_mtime(): """Get mtime of /etc/resolv.conf. Returns mtime with sub-second precision as a string with format "2020-08-25 14:35:05.980503425 +0200" """ return self.host.run_command( ['stat', '-c', '%y', paths.RESOLV_CONF]).stdout_text.strip() if state['nm_config'] is None: self.host.run_command(['rm', '-f', self.NM_CONF_FILE]) else: self.host.run_command( ['mkdir', '-p', os.path.dirname(self.NM_CONF_FILE)]) self.host.put_file_contents( self.NM_CONF_FILE, state['nm_config']) # NetworkManager writes /etc/resolv.conf few moments after # `systemctl restart` returns so we need to wait until the file is # updated mtime_before = get_resolv_conf_mtime() self._restart_network_manager() wait_until = time.time() + 10 while time.time() < wait_until: if get_resolv_conf_mtime() != mtime_before: break time.sleep(1) else: raise Exception('NetworkManager did not update /etc/resolv.conf ' 'in 10 seconds after restart') def resolver(host): for cls in [ResolvedResolver, NetworkManagerResolver, PlainFileResolver]: if cls.is_our_resolver(host): logger.info('Detected DNS resolver manager for host %s is %s', host.hostname, cls) return cls(host) raise Exception('Resolver manager could not be detected')
12,747
Python
.py
296
33.266892
80
0.612312
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,327
create_caless_pki.py
freeipa_freeipa/ipatests/pytest_ipa/integration/create_caless_pki.py
# Copyright (c) 2015-2017, Jan Cholasta <jcholast@redhat.com> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import collections import datetime import itertools import os import os.path import six from cryptography import __version__ as cryptography_version from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.x509.oid import NameOID from pkg_resources import parse_version from pyasn1.type import univ, char, namedtype, tag from pyasn1.codec.der import encoder as der_encoder from pyasn1.codec.native import decoder as native_decoder if six.PY3: unicode = str DAY = datetime.timedelta(days=1) YEAR = 365 * DAY # we get the variables from ca_less test domain = None realm = None server1 = None server2 = None client = None password = None cert_dir = None CertInfo = collections.namedtuple('CertInfo', 'nick key cert counter') class PrincipalName(univ.Sequence): '''See RFC 4120 for details''' componentType = namedtype.NamedTypes( namedtype.NamedType( 'name-type', univ.Integer().subtype( explicitTag=tag.Tag( tag.tagClassContext, tag.tagFormatSimple, 0, ), ), ), namedtype.NamedType( 'name-string', univ.SequenceOf(char.GeneralString()).subtype( explicitTag=tag.Tag( tag.tagClassContext, tag.tagFormatSimple, 1, ), ), ), ) class KRB5PrincipalName(univ.Sequence): '''See RFC 4556 for details''' componentType = namedtype.NamedTypes( namedtype.NamedType( 'realm', char.GeneralString().subtype( explicitTag=tag.Tag( tag.tagClassContext, tag.tagFormatSimple, 0, ), ), ), namedtype.NamedType( 'principalName', PrincipalName().subtype( explicitTag=tag.Tag( tag.tagClassContext, tag.tagFormatSimple, 1, ), ), ), ) def profile_ca(builder, ca_nick, ca): now = datetime.datetime.now(tz=datetime.timezone.utc) builder = builder.not_valid_before(now) builder = builder.not_valid_after(now + 10 * YEAR) crl_uri = u'file://{}.crl'.format(os.path.join(cert_dir, ca_nick)) builder = builder.add_extension( x509.KeyUsage( digital_signature=True, content_commitment=True, key_encipherment=False, data_encipherment=False, key_agreement=False, key_cert_sign=True, crl_sign=True, encipher_only=False, decipher_only=False, ), critical=True, ) builder = builder.add_extension( x509.BasicConstraints(ca=True, path_length=None), critical=True, ) builder = builder.add_extension( x509.CRLDistributionPoints([ x509.DistributionPoint( full_name=[x509.UniformResourceIdentifier(crl_uri)], relative_name=None, crl_issuer=None, reasons=None, ), ]), critical=False, ) public_key = builder._public_key builder = builder.add_extension( x509.SubjectKeyIdentifier.from_public_key(public_key), critical=False, ) # here we get "ca" only for "ca1/subca" CA if not ca: builder = builder.add_extension( x509.AuthorityKeyIdentifier.from_issuer_public_key(public_key), critical=False, ) else: ski_ext = ca.cert.extensions.get_extension_for_class( x509.SubjectKeyIdentifier ) auth_keyidentifier = (x509.AuthorityKeyIdentifier .from_issuer_subject_key_identifier) ''' cryptography < 2.7 accepts only Extension object. Remove this workaround when all supported platforms update python-cryptography. ''' if (parse_version(cryptography_version) >= parse_version('2.7')): extension = auth_keyidentifier(ski_ext.value) else: extension = auth_keyidentifier(ski_ext) builder = builder.add_extension(extension, critical=False) return builder def profile_server(builder, ca_nick, ca, warp=datetime.timedelta(days=0), dns_name=None, badusage=False, wildcard=False): now = datetime.datetime.now(tz=datetime.timezone.utc) + warp builder = builder.not_valid_before(now) builder = builder.not_valid_after(now + YEAR) crl_uri = u'file://{}.crl'.format(os.path.join(cert_dir, ca_nick)) builder = builder.add_extension( x509.CRLDistributionPoints([ x509.DistributionPoint( full_name=[x509.UniformResourceIdentifier(crl_uri)], relative_name=None, crl_issuer=None, reasons=None, ), ]), critical=False, ) if dns_name is not None: builder = builder.add_extension( x509.SubjectAlternativeName([x509.DNSName(dns_name)]), critical=False, ) if badusage: builder = builder.add_extension( x509.KeyUsage( digital_signature=False, content_commitment=False, key_encipherment=False, data_encipherment=True, key_agreement=True, key_cert_sign=False, crl_sign=False, encipher_only=False, decipher_only=False ), critical=False ) if wildcard: names = [x509.DNSName(u'*.' + domain)] server_split = server1.split('.', 1) if len(server_split) == 2 and domain != server_split[1]: names.append(x509.DNSName(u'*.' + server_split[1])) builder = builder.add_extension( x509.SubjectAlternativeName(names), critical=False, ) return builder def profile_kdc(builder, ca_nick, ca, warp=datetime.timedelta(days=0), dns_name=None, badusage=False): now = datetime.datetime.now(tz=datetime.timezone.utc) + warp builder = builder.not_valid_before(now) builder = builder.not_valid_after(now + YEAR) crl_uri = u'file://{}.crl'.format(os.path.join(cert_dir, ca_nick)) builder = builder.add_extension( x509.ExtendedKeyUsage([x509.ObjectIdentifier('1.3.6.1.5.2.3.5')]), critical=False, ) name = { 'realm': realm, 'principalName': { 'name-type': 2, 'name-string': ['krbtgt', realm], }, } name = native_decoder.decode(name, asn1Spec=KRB5PrincipalName()) name = der_encoder.encode(name) names = [x509.OtherName(x509.ObjectIdentifier('1.3.6.1.5.2.2'), name)] if dns_name is not None: names += [x509.DNSName(dns_name)] builder = builder.add_extension( x509.SubjectAlternativeName(names), critical=False, ) builder = builder.add_extension( x509.CRLDistributionPoints([ x509.DistributionPoint( full_name=[x509.UniformResourceIdentifier(crl_uri)], relative_name=None, crl_issuer=None, reasons=None, ), ]), critical=False, ) if badusage: builder = builder.add_extension( x509.KeyUsage( digital_signature=False, content_commitment=False, key_encipherment=False, data_encipherment=True, key_agreement=True, key_cert_sign=False, crl_sign=False, encipher_only=False, decipher_only=False ), critical=False ) return builder def gen_cert(profile, nick_base, subject, ca=None, **kwargs): key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) public_key = key.public_key() counter = itertools.count(1) if ca is not None: ca_nick, ca_key, ca_cert, ca_counter = ca nick = os.path.join(ca_nick, nick_base) issuer = ca_cert.subject else: nick = ca_nick = nick_base ca_key = key ca_counter = counter issuer = subject serial = next(ca_counter) builder = x509.CertificateBuilder() builder = builder.serial_number(serial) builder = builder.issuer_name(issuer) builder = builder.subject_name(subject) builder = builder.public_key(public_key) builder = profile(builder, ca_nick, ca, **kwargs) cert = builder.sign( private_key=ca_key, algorithm=hashes.SHA256(), backend=default_backend(), ) key_pem = key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.BestAvailableEncryption(password.encode()), ) cert_pem = cert.public_bytes(serialization.Encoding.PEM) try: os.makedirs(os.path.dirname(os.path.join(cert_dir, nick))) except OSError: pass with open(os.path.join(cert_dir, nick + '.key'), 'wb') as f: f.write(key_pem) with open(os.path.join(cert_dir, nick + '.crt'), 'wb') as f: f.write(cert_pem) return CertInfo(nick, key, cert, counter) def revoke_cert(ca, serial): now = datetime.datetime.now(tz=datetime.timezone.utc) crl_builder = x509.CertificateRevocationListBuilder() crl_builder = crl_builder.issuer_name(ca.cert.subject) crl_builder = crl_builder.last_update(now) crl_builder = crl_builder.next_update(now + DAY) crl_filename = os.path.join(cert_dir, ca.nick + '.crl') try: f = open(crl_filename, 'rb') except IOError: pass else: with f: crl_pem = f.read() crl = x509.load_pem_x509_crl(crl_pem, default_backend()) for revoked_cert in crl: crl_builder = crl_builder.add_revoked_certificate(revoked_cert) builder = x509.RevokedCertificateBuilder() builder = builder.serial_number(serial) builder = builder.revocation_date(now) revoked_cert = builder.build(default_backend()) crl_builder = crl_builder.add_revoked_certificate(revoked_cert) crl = crl_builder.sign( private_key=ca.key, algorithm=hashes.SHA256(), backend=default_backend(), ) crl_pem = crl.public_bytes(serialization.Encoding.PEM) with open(crl_filename, 'wb') as f: f.write(crl_pem) def gen_server_certs(nick_base, hostname, org, ca=None): gen_cert(profile_server, nick_base, x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.COMMON_NAME, hostname) ]), ca, dns_name=hostname ) gen_cert(profile_server, nick_base + u'-badname', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.COMMON_NAME, u'not-' + hostname) ]), ca, dns_name=u'not-' + hostname ) gen_cert(profile_server, nick_base + u'-altname', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.COMMON_NAME, u'alt-' + hostname) ]), ca, dns_name=hostname ) gen_cert(profile_server, nick_base + u'-expired', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'Expired'), x509.NameAttribute(NameOID.COMMON_NAME, hostname) ]), ca, dns_name=hostname, warp=-2 * YEAR ) gen_cert( profile_server, nick_base + u'-not-yet-valid', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'Future'), x509.NameAttribute(NameOID.COMMON_NAME, hostname), ]), ca, dns_name=hostname, warp=1 * DAY, ) gen_cert(profile_server, nick_base + u'-badusage', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'Bad Usage'), x509.NameAttribute(NameOID.COMMON_NAME, hostname) ]), ca, dns_name=hostname, badusage=True ) revoked = gen_cert(profile_server, nick_base + u'-revoked', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'Revoked'), x509.NameAttribute(NameOID.COMMON_NAME, hostname) ]), ca, dns_name=hostname ) revoke_cert(ca, revoked.cert.serial_number) def gen_kdc_certs(nick_base, hostname, org, ca=None): gen_cert(profile_kdc, nick_base + u'-kdc', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'KDC'), x509.NameAttribute(NameOID.COMMON_NAME, hostname) ]), ca ) gen_cert(profile_kdc, nick_base + u'-kdc-badname', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'KDC'), x509.NameAttribute(NameOID.COMMON_NAME, u'not-' + hostname) ]), ca ) gen_cert(profile_kdc, nick_base + u'-kdc-altname', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'KDC'), x509.NameAttribute(NameOID.COMMON_NAME, u'alt-' + hostname) ]), ca, dns_name=hostname ) gen_cert(profile_kdc, nick_base + u'-kdc-expired', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'Expired KDC'), x509.NameAttribute(NameOID.COMMON_NAME, hostname) ]), ca, warp=-2 * YEAR ) gen_cert(profile_kdc, nick_base + u'-kdc-badusage', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'Bad Usage KDC'), x509.NameAttribute(NameOID.COMMON_NAME, hostname) ]), ca, badusage=True ) revoked = gen_cert(profile_kdc, nick_base + u'-kdc-revoked', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'Revoked KDC'), x509.NameAttribute(NameOID.COMMON_NAME, hostname) ]), ca ) revoke_cert(ca, revoked.cert.serial_number) def gen_subtree(nick_base, org, ca=None): subca = gen_cert(profile_ca, nick_base, x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.COMMON_NAME, u'CA') ]), ca ) gen_cert(profile_server, u'wildcard', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.COMMON_NAME, u'*.' + domain) ]), subca, wildcard=True ) gen_server_certs(u'server', server1, org, subca) gen_server_certs(u'replica', server2, org, subca) gen_server_certs(u'client', client, org, subca) gen_cert(profile_kdc, u'kdcwildcard', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org), x509.NameAttribute(NameOID.COMMON_NAME, u'*.' + domain) ]), subca ) gen_kdc_certs(u'server', server1, org, subca) gen_kdc_certs(u'replica', server2, org, subca) gen_kdc_certs(u'client', client, org, subca) return subca def create_pki(): gen_cert(profile_server, u'server-selfsign', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Self-signed'), x509.NameAttribute(NameOID.COMMON_NAME, server1) ]) ) gen_cert(profile_server, u'replica-selfsign', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Self-signed'), x509.NameAttribute(NameOID.COMMON_NAME, server2) ]) ) gen_cert(profile_server, u'noca', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'No-CA'), x509.NameAttribute(NameOID.COMMON_NAME, server1) ]) ) gen_cert(profile_kdc, u'server-kdc-selfsign', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Self-signed'), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'KDC'), x509.NameAttribute(NameOID.COMMON_NAME, server1) ]) ) gen_cert(profile_kdc, u'replica-kdc-selfsign', x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Self-signed'), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'KDC'), x509.NameAttribute(NameOID.COMMON_NAME, server2) ]) ) ca1 = gen_subtree(u'ca1', u'Example Organization Espa\xf1a') gen_subtree(u'subca', u'Subsidiary Example Organization', ca1) gen_subtree(u'ca2', u'Other Example Organization') ca3 = gen_subtree(u'ca3', u'Unknown Organization') os.unlink(os.path.join(cert_dir, ca3.nick + '.key')) os.unlink(os.path.join(cert_dir, ca3.nick + '.crt'))
19,791
Python
.py
508
27.84252
79
0.581065
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,328
create_keycloak.py
freeipa_freeipa/ipatests/pytest_ipa/integration/create_keycloak.py
import os import textwrap import time from ipaplatform.paths import paths from ipatests.pytest_ipa.integration import tasks def setup_keycloakserver(host, version='17.0.0'): dir = "/opt/keycloak" password = host.config.admin_password tasks.install_packages(host, ["unzip", "java-11-openjdk-headless", "openssl", "maven", "wget", "firefox", "xorg-x11-server-Xvfb"]) # add keycloak system user/group and folder url = "https://github.com/keycloak/keycloak/releases/download/{0}/keycloak-{0}.zip".format(version) # noqa: E501 host.run_command(["wget", url, "-O", "{0}-{1}.zip".format(dir, version)]) host.run_command( ["unzip", "{0}-{1}.zip".format(dir, version), "-d", "/opt/"] ) host.run_command(["mv", "{0}-{1}".format(dir, version), dir]) host.run_command(["groupadd", "keycloak"]) host.run_command( ["useradd", "-r", "-g", "keycloak", "-d", dir, "keycloak"] ) host.run_command(["chown", "-R", "keycloak:", dir]) host.run_command(["chmod", "o+x", "{0}/bin/".format(dir)]) host.run_command(["restorecon", "-R", dir]) # setup TLS certificate using IPA CA host.run_command(["kinit", "-k"]) host.run_command(["ipa", "service-add", "HTTP/{0}".format(host.hostname)]) key = os.path.join(paths.OPENSSL_PRIVATE_DIR, "keycloak.key") crt = os.path.join(paths.OPENSSL_PRIVATE_DIR, "keycloak.crt") keystore = os.path.join(paths.OPENSSL_PRIVATE_DIR, "keycloak.store") host.run_command(["ipa-getcert", "request", "-K", "HTTP/{0}".format(host.hostname), "-D", host.hostname, "-o", "keycloak", "-O", "keycloak", "-m", "0600", "-M", "0644", "-k", key, "-f", crt, "-w"]) host.run_command(["keytool", "-import", "-keystore", keystore, "-file", "/etc/ipa/ca.crt", "-alias", "ipa_ca", "-trustcacerts", "-storepass", password, "-noprompt"]) host.run_command(["chown", "keycloak:keycloak", keystore]) # Setup keycloak service and config files contents = textwrap.dedent(""" KEYCLOAK_ADMIN=admin KEYCLOAK_ADMIN_PASSWORD={admin_pswd} KC_HOSTNAME={host}:8443 KC_HTTPS_CERTIFICATE_FILE={crt} KC_HTTPS_CERTIFICATE_KEY_FILE={key} KC_HTTPS_TRUST_STORE_FILE={store} KC_HTTPS_TRUST_STORE_PASSWORD={store_pswd} KC_HTTP_RELATIVE_PATH=/auth """).format(admin_pswd=password, host=host.hostname, crt=crt, key=key, store=keystore, store_pswd=password) host.put_file_contents("/etc/sysconfig/keycloak", contents) contents = textwrap.dedent(""" [Unit] Description=Keycloak Server After=network.target [Service] Type=idle EnvironmentFile=/etc/sysconfig/keycloak User=keycloak Group=keycloak ExecStart=/opt/keycloak/bin/kc.sh start TimeoutStartSec=600 TimeoutStopSec=600 [Install] WantedBy=multi-user.target """) host.put_file_contents("/etc/systemd/system/keycloak.service", contents) host.run_command(["systemctl", "daemon-reload"]) # Run build stage first env_vars = textwrap.dedent(""" export KEYCLOAK_ADMIN=admin export KC_HOSTNAME={hostname}:8443 export KC_HTTPS_CERTIFICATE_FILE=/etc/pki/tls/certs/keycloak.crt export KC_HTTPS_CERTIFICATE_KEY_FILE=/etc/pki/tls/private/keycloak.key export KC_HTTPS_TRUST_STORE_FILE=/etc/pki/tls/private/keycloak.store export KC_HTTPS_TRUST_STORE_PASSWORD={STORE_PASS} export KEYCLOAK_ADMIN_PASSWORD={ADMIN_PASS} export KC_HTTP_RELATIVE_PATH=/auth """).format(hostname=host.hostname, STORE_PASS=password, ADMIN_PASS=password) tasks.backup_file(host, '/etc/bashrc') content = host.get_file_contents('/etc/bashrc', encoding='utf-8') new_content = content + "\n{}".format(env_vars) host.put_file_contents('/etc/bashrc', new_content) host.run_command(['bash']) host.run_command( ['su', '-', 'keycloak', '-c', '/opt/keycloak/bin/kc.sh build']) host.run_command(["systemctl", "start", "keycloak"]) host.run_command(["/opt/keycloak/bin/kc.sh", "show-config"]) # Setup keycloak for use: kcadmin_sh = "/opt/keycloak/bin/kcadm.sh" host.run_command([kcadmin_sh, "config", "truststore", "--trustpass", password, keystore]) kcadmin = [kcadmin_sh, "config", "credentials", "--server", "https://{0}:8443/auth/".format(host.hostname), "--realm", "master", "--user", "admin", "--password", password ] tasks.run_repeatedly( host, kcadmin, timeout=60) host.run_command( [kcadmin_sh, "create", "users", "-r", "master", "-s", "username=testuser1", "-s", "enabled=true", "-s", "email=testuser1@ipa.test"] ) host.run_command( [kcadmin_sh, "set-password", "-r", "master", "--username", "testuser1", "--new-password", password] ) def setup_keycloak_client(host): password = host.config.admin_password host.run_command(["/opt/keycloak/bin/kcreg.sh", "config", "credentials", "--server", "https://{0}:8443/auth/".format(host.hostname), "--realm", "master", "--user", "admin", "--password", password] ) client_json = textwrap.dedent(""" {{ "enabled" : true, "clientAuthenticatorType" : "client-secret", "redirectUris" : [ "https://ipa-ca.{redirect}/ipa/idp/*" ], "webOrigins" : [ "https://ipa-ca.{web}" ], "protocol" : "openid-connect", "attributes" : {{ "oauth2.device.authorization.grant.enabled" : "true", "oauth2.device.polling.interval": "5" }} }} """).format(redirect=host.domain.name, web=host.domain.name) host.put_file_contents("/tmp/ipa_client.json", client_json) host.run_command(["/opt/keycloak/bin/kcreg.sh", "create", "-f", "/tmp/ipa_client.json", "-s", "clientId=ipa_oidc_client", "-s", "secret={0}".format(password)] ) time.sleep(60) def uninstall_keycloak(host): key = os.path.join(paths.OPENSSL_PRIVATE_DIR, "keycloak.key") crt = os.path.join(paths.OPENSSL_PRIVATE_DIR, "keycloak.crt") keystore = os.path.join(paths.OPENSSL_PRIVATE_DIR, "keycloak.store") host.run_command(["systemctl", "stop", "keycloak"], raiseonerr=False) host.run_command(["getcert", "stop-tracking", "-k", key, "-f", crt], raiseonerr=False) host.run_command(["rm", "-rf", "/opt/keycloak", "/etc/sysconfig/keycloak", "/etc/systemd/system/keycloak.service", key, crt, keystore]) host.run_command(["systemctl", "daemon-reload"]) host.run_command(["userdel", "keycloak"]) host.run_command(["groupdel", "keycloak"], raiseonerr=False) tasks.restore_files(host)
7,143
Python
.py
157
36.675159
117
0.596411
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,329
test_i18n_messages.py
freeipa_freeipa/ipatests/test_ipaserver/test_i18n_messages.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # import json import os import pytest from ipalib import api from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test from ipatests.test_ipaserver.httptest import Unauthorized_HTTP_test from ipatests.util import (assert_equal, assert_deepequal, raises, assert_not_equal) from ipapython.version import API_VERSION from ipaserver.plugins.internal import i18n_messages @pytest.mark.tier1 class test_i18n_messages(XMLRPC_test, Unauthorized_HTTP_test): """ Tests for i18n_messages end point """ app_uri = '/ipa/i18n_messages' content_type = 'application/json' def _prepare_data(self, method): """ Construct json data required for request """ return {"method": "{0}".format(method), "params": [[], {"version": "{0}".format(API_VERSION)}]} def _prepare_accept_lang(self): try: return os.environ['LANGUAGE'] except KeyError: pass try: return os.environ['LANG'].split('.')[0].replace('_', '-') except KeyError: return '' def _fetch_i18n_msgs(self): """ Build translations directly via command instance """ return i18n_messages({}).execute() def _fetch_i18n_msgs_http(self, accept_lang): """ Fetch translations via http request """ self.accept_language = accept_lang params = json.dumps(self._prepare_data('i18n_messages')) response = self.send_request(params=params) assert_equal(response.status, 200) response_data = response.read() jsondata = json.loads(response_data) assert_equal(jsondata['error'], None) assert jsondata['result'] assert jsondata['result']['texts'] return jsondata['result'] def test_only_i18n_serves(self): """ Test if end point doesn't fulfill other RPC commands """ assert api.Command.get('user_find') params = json.dumps(self._prepare_data('user_find/1')) response = self.send_request(params=params) assert_equal(response.status, 403) assert_equal(response.reason, 'Forbidden') response_data = response.read() assert_equal(response_data, b'Invalid RPC command') raises(ValueError, json.loads, response_data) def test_only_post_serves(self): """ Test if end point fulfills only POST method """ params = json.dumps(self._prepare_data('i18n_messages')) response = self.send_request(method='GET', params=params) assert_equal(response.status, 405) assert_equal(response.reason, 'Method Not Allowed') assert response.msg assert_equal(response.msg['allow'], 'POST') response_data = response.read() raises(ValueError, json.loads, response_data) def test_i18n_receive(self): """ Test if translations request is successful """ expected_msgs = self._fetch_i18n_msgs() actual_msgs = self._fetch_i18n_msgs_http(self._prepare_accept_lang()) assert_deepequal(expected_msgs, actual_msgs) def test_i18n_consequence_receive(self): """ Test if consequence translations requests for different languages are successful. Every request's result have to contain messages in it's locale. """ prev_i18n_msgs = self._fetch_i18n_msgs_http('en-us') cur_i18n_msgs = self._fetch_i18n_msgs_http('fr-fr') try: assert_equal(prev_i18n_msgs['texts']['true'], u'True') assert_equal(cur_i18n_msgs['texts']['true'], u'Vrai') except KeyError: assert_not_equal(prev_i18n_msgs, cur_i18n_msgs)
3,833
Python
.py
98
31
77
0.635335
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,330
test_rpcserver.py
freeipa_freeipa/ipatests/test_ipaserver/test_rpcserver.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipaserver.rpc` module. """ import json import pytest import six from ipatests.util import assert_equal, raises, PluginTester from ipalib import errors from ipaserver import rpcserver if six.PY3: unicode = str pytestmark = pytest.mark.tier0 class StartResponse: def __init__(self): self.reset() def reset(self): self.status = None self.headers = None def __call__(self, status, headers): assert self.status is None assert self.headers is None assert isinstance(status, str) assert isinstance(headers, list) self.status = status self.headers = headers def test_not_found(): api = 'the api instance' f = rpcserver.HTTP_Status(api) t = rpcserver._not_found_template s = StartResponse() # Test with an innocent URL: url = '/ipa/foo/stuff' assert_equal( f.not_found(None, s, url, None), [(t % dict(url='/ipa/foo/stuff')).encode('utf-8')] ) assert s.status == '404 Not Found' assert s.headers == [('Content-Type', 'text/html; charset=utf-8')] # Test when URL contains any of '<>&' s.reset() url ='&nbsp;' + '<script>do_bad_stuff();</script>' assert_equal( f.not_found(None, s, url, None), [(t % dict( url='&amp;nbsp;&lt;script&gt;do_bad_stuff();&lt;/script&gt;') ).encode('utf-8')] ) assert s.status == '404 Not Found' assert s.headers == [('Content-Type', 'text/html; charset=utf-8')] def test_bad_request(): api = 'the api instance' f = rpcserver.HTTP_Status(api) t = rpcserver._bad_request_template s = StartResponse() assert_equal( f.bad_request(None, s, 'illegal request'), [(t % dict(message='illegal request')).encode('utf-8')] ) assert s.status == '400 Bad Request' assert s.headers == [('Content-Type', 'text/html; charset=utf-8')] def test_internal_error(): api = 'the api instance' f = rpcserver.HTTP_Status(api) t = rpcserver._internal_error_template s = StartResponse() assert_equal( f.internal_error(None, s, 'request failed'), [(t % dict(message='request failed')).encode('utf-8')] ) assert s.status == '500 Internal Server Error' assert s.headers == [('Content-Type', 'text/html; charset=utf-8')] def test_unauthorized_error(): api = 'the api instance' f = rpcserver.HTTP_Status(api) t = rpcserver._unauthorized_template s = StartResponse() assert_equal( f.unauthorized(None, s, 'unauthorized', 'password-expired'), [(t % dict(message='unauthorized')).encode('utf-8')] ) assert s.status == '401 Unauthorized' assert s.headers == [('Content-Type', 'text/html; charset=utf-8'), ('X-IPA-Rejection-Reason', 'password-expired')] def test_params_2_args_options(): """ Test the `ipaserver.rpcserver.params_2_args_options` function. """ f = rpcserver.params_2_args_options args = ('Hello', u'world!') options = dict(one=1, two=u'Two', three='Three') assert f(tuple()) == (tuple(), dict()) assert f([args]) == (args, dict()) assert f([args, options]) == (args, options) class test_session: klass = rpcserver.wsgi_dispatch def test_route(self): def app1(environ, start_response): return ( 'from 1', [environ[k] for k in ('SCRIPT_NAME', 'PATH_INFO')] ) def app2(environ, start_response): return ( 'from 2', [environ[k] for k in ('SCRIPT_NAME', 'PATH_INFO')] ) api = 'the api instance' inst = self.klass(api) inst.mount(app1, '/foo/stuff') inst.mount(app2, '/bar') d = dict(SCRIPT_NAME='/ipa', PATH_INFO='/foo/stuff') assert inst.route(d, None) == ('from 1', ['/ipa', '/foo/stuff']) d = dict(SCRIPT_NAME='/ipa', PATH_INFO='/bar') assert inst.route(d, None) == ('from 2', ['/ipa', '/bar']) def test_mount(self): def app1(environ, start_response): pass def app2(environ, start_response): pass # Test that mount works: api = 'the api instance' inst = self.klass(api) inst.mount(app1, 'foo') assert inst['foo'] is app1 assert list(inst) == ['foo'] # Test that Exception is raise if trying override a mount: e = raises(Exception, inst.mount, app2, 'foo') assert str(e) == '%s.mount(): cannot replace %r with %r at %r' % ( 'wsgi_dispatch', app1, app2, 'foo' ) # Test mounting a second app: inst.mount(app2, 'bar') assert inst['bar'] is app2 assert list(inst) == ['bar', 'foo'] class test_xmlserver(PluginTester): """ Test the `ipaserver.rpcserver.xmlserver` plugin. """ _plugin = rpcserver.xmlserver def test_marshaled_dispatch(self): # FIXME self.instance('Backend', in_server=True) class test_jsonserver(PluginTester): """ Test the `ipaserver.rpcserver.jsonserver` plugin. """ _plugin = rpcserver.jsonserver def test_unmarshal(self): """ Test the `ipaserver.rpcserver.jsonserver.unmarshal` method. """ o, _api, _home = self.instance('Backend', in_server=True) # Test with invalid JSON-data: e = raises(errors.JSONError, o.unmarshal, 'this wont work') if six.PY2: assert unicode(e.error) == 'No JSON object could be decoded' else: assert str(e.error).startswith('Expecting value: ') # Test with non-dict type: e = raises(errors.JSONError, o.unmarshal, json.dumps([1, 2, 3])) assert unicode(e.error) == 'Request must be a dict' params = [[1, 2], dict(three=3, four=4)] # Test with missing method: d = dict(params=params, id=18) e = raises(errors.JSONError, o.unmarshal, json.dumps(d)) assert unicode(e.error) == 'Request is missing "method"' # Test with missing params: d = dict(method='echo', id=18) e = raises(errors.JSONError, o.unmarshal, json.dumps(d)) assert unicode(e.error) == 'Request is missing "params"' # Test with non-list params: for p in ('hello', dict(args=tuple(), options=dict())): d = dict(method='echo', id=18, params=p) e = raises(errors.JSONError, o.unmarshal, json.dumps(d)) assert unicode(e.error) == 'params must be a list' # Test with other than 2 params: for p in ([], [tuple()], [None, dict(), tuple()]): d = dict(method='echo', id=18, params=p) e = raises(errors.JSONError, o.unmarshal, json.dumps(d)) assert unicode(e.error) == 'params must contain [args, options]' # Test when args is not a list: d = dict(method='echo', id=18, params=['args', dict()]) e = raises(errors.JSONError, o.unmarshal, json.dumps(d)) assert unicode(e.error) == 'params[0] (aka args) must be a list' # Test when options is not a dict: d = dict(method='echo', id=18, params=[('hello', 'world'), 'options']) e = raises(errors.JSONError, o.unmarshal, json.dumps(d)) assert unicode(e.error) == 'params[1] (aka options) must be a dict' # Test with valid values: args = [u'jdoe'] options = dict(givenname=u'John', sn='Doe') d = dict(method=u'user_add', params=(args, options), id=18) assert o.unmarshal(json.dumps(d)) == (u'user_add', args, options, 18)
8,412
Python
.py
210
32.985714
78
0.611807
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,331
test_referer.py
freeipa_freeipa/ipatests/test_ipaserver/test_referer.py
# Copyright (C) 2023 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import pytest import uuid from ipatests.test_ipaserver.httptest import Unauthorized_HTTP_test from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test from ipatests.util import assert_equal from ipalib import api, errors from ipapython.ipautil import run testuser = u'tuser' password = u'password' @pytest.mark.tier1 class test_referer(XMLRPC_test, Unauthorized_HTTP_test): @pytest.fixture(autouse=True) def login_setup(self, request): ccache = os.path.join('/tmp', str(uuid.uuid4())) tokenid = None try: api.Command['user_add'](uid=testuser, givenname=u'Test', sn=u'User') api.Command['passwd'](testuser, password=password) run(['kinit', testuser], stdin='{0}\n{0}\n{0}\n'.format(password), env={"KRB5CCNAME": ccache}) result = api.Command["otptoken_add"]( type='HOTP', description='testotp', ipatokenotpalgorithm='sha512', ipatokenowner=testuser, ipatokenotpdigits='6') tokenid = result['result']['ipatokenuniqueid'][0] except errors.ExecutionError as e: pytest.skip( 'Cannot set up test user: %s' % e ) def fin(): try: api.Command['user_del']([testuser]) api.Command['otptoken_del']([tokenid]) except errors.NotFound: pass os.unlink(ccache) request.addfinalizer(fin) def _request(self, params={}, host=None): # implicit is that self.app_uri is set to the appropriate value return self.send_request(params=params, host=host) def test_login_password_valid(self): """Valid authentication of a user""" self.app_uri = "/ipa/session/login_password" response = self._request( params={'user': 'tuser', 'password': password}) assert_equal(response.status, 200, self.app_uri) def test_change_password_valid(self): """This actually changes the user password""" self.app_uri = "/ipa/session/change_password" response = self._request( params={'user': 'tuser', 'old_password': password, 'new_password': 'new_password'} ) assert_equal(response.status, 200, self.app_uri) def test_sync_token_valid(self): """We aren't testing that sync works, just that we can get there""" self.app_uri = "/ipa/session/sync_token" response = self._request( params={'user': 'tuser', 'first_code': '1234', 'second_code': '5678', 'password': 'password'}) assert_equal(response.status, 200, self.app_uri) def test_i18n_messages_valid(self): # i18n_messages requires a valid JSON request and we send # nothing. If we get a 500 error then it got past the # referer check. self.app_uri = "/ipa/i18n_messages" response = self._request() assert_equal(response.status, 500, self.app_uri) # /ipa/session/login_x509 is not tested yet as it requires # significant additional setup. # This can be manually verified by adding # Satisfy Any and Require all granted to the configuration # section and comment out all Auth directives. The request # will fail and log that there is no KRB5CCNAME which comes # after the referer check. def test_endpoints_auth_required(self): """Test endpoints that require pre-authorization which will fail before we even get to the Referer check """ self.endpoints = { "/ipa/xml", "/ipa/session/login_kerberos", "/ipa/session/json", "/ipa/session/xml" } for self.app_uri in self.endpoints: response = self._request(host="attacker.test") # referer is checked after auth assert_equal(response.status, 401, self.app_uri) def notest_endpoints_invalid(self): """Pass in a bad Referer, expect a 400 Bad Request""" self.endpoints = { "/ipa/session/login_password", "/ipa/session/change_password", "/ipa/session/sync_token", } for self.app_uri in self.endpoints: response = self._request(host="attacker.test") assert_equal(response.status, 400, self.app_uri)
5,175
Python
.py
118
35.152542
80
0.634253
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,332
test_topology_plugin.py
freeipa_freeipa/ipatests/test_ipaserver/test_topology_plugin.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # import io import os from ipaserver.plugins.ldap2 import ldap2 from ipalib import api from ipapython.dn import DN import pytest REPL_PLUGIN_NAME_TEMPLATE = 'Multi%s Replication Plugin' @pytest.mark.tier1 class TestTopologyPlugin: """ Test Topology plugin from the DS point of view Testcase: http://www.freeipa.org/page/V4/Manage_replication_topology/ Test_plan#Test_case: _Replication_Topology_is_listed_among_directory_server_plugins """ pwfile = os.path.join(api.env.dot_ipa, ".dmpw") @pytest.fixture(autouse=True) def topologyplugin_setup(self, request): """ setup for test """ self.conn = None def fin(): if self.conn and self.conn.isconnected(): self.conn.disconnect() request.addfinalizer(fin) @pytest.mark.skipif(os.path.isfile(pwfile) is False, reason="You did not provide a .dmpw file with the DM password") def test_topologyplugin(self): supplier = REPL_PLUGIN_NAME_TEMPLATE % 'supplier' pluginattrs = { u'nsslapd-pluginPath': [u'libtopology'], u'nsslapd-pluginVendor': [u'freeipa'], u'cn': [u'IPA Topology Configuration'], u'nsslapd-plugin-depends-on-named': [supplier, u'ldbm database'], u'nsslapd-topo-plugin-shared-replica-root': [u'dc=example,dc=com'], u'nsslapd-pluginVersion': [u'1.0'], u'nsslapd-topo-plugin-shared-config-base': [u'cn=ipa,cn=etc,dc=example,dc=com'], u'nsslapd-pluginDescription': [u'ipa-topology-plugin'], u'nsslapd-pluginEnabled': [u'on'], u'nsslapd-pluginId': [u'ipa-topology-plugin'], u'objectClass': [u'top', u'nsSlapdPlugin', u'extensibleObject'], u'nsslapd-topo-plugin-startup-delay': [u'20'], u'nsslapd-topo-plugin-shared-binddngroup': [u'cn=replication managers,cn=sysaccounts,cn=etc,dc=example,dc=com'], u'nsslapd-pluginType': [u'object'], u'nsslapd-pluginInitfunc': [u'ipa_topo_init'] } variable_attrs = {u'nsslapd-topo-plugin-shared-replica-root', u'nsslapd-topo-plugin-shared-config-base', u'nsslapd-topo-plugin-shared-binddngroup'} # Now eliminate keys that have domain-dependent values. checkvalues = set(pluginattrs.keys()) - variable_attrs topoplugindn = DN(('cn', 'IPA Topology Configuration'), ('cn', 'plugins'), ('cn', 'config')) pwfile = os.path.join(api.env.dot_ipa, ".dmpw") with io.open(pwfile, "r") as f: dm_password = f.read().rstrip() self.conn = ldap2(api) self.conn.connect(bind_dn=DN(('cn', 'directory manager')), bind_pw=dm_password) entry = self.conn.get_entry(topoplugindn) assert(set(entry.keys()) == set(pluginattrs.keys())) # Handle different names for replication plugin key = 'nsslapd-plugin-depends-on-named' plugin_dependencies = entry[key] if supplier not in plugin_dependencies: mm = REPL_PLUGIN_NAME_TEMPLATE % 'master' pluginattrs[key] = [mm, 'ldbm database'] for i in checkvalues: assert(set(pluginattrs[i]) == set(entry[i]))
3,479
Python
.py
77
35.038961
87
0.609375
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,333
test_secure_ajp_connector.py
freeipa_freeipa/ipatests/test_ipaserver/test_secure_ajp_connector.py
# Copyright (C) 2021 FreeIPA Project Contributors - see LICENSE file from collections import namedtuple from io import BytesIO from lxml.etree import parse as myparse import pytest import textwrap from unittest.mock import mock_open, patch from ipaplatform.constants import constants from ipaserver.install import dogtaginstance class MyDogtagInstance(dogtaginstance.DogtagInstance): """Purpose is to avoid reading configuration files. The real DogtagInstance will open up the system store and try to determine the actual version of tomcat installed. Fake it instead. """ def __init__(self, is_newer): self.service_user = constants.PKI_USER self.ajp_secret = None self.is_newer = is_newer def _is_newer_tomcat_version(self, default=None): return self.is_newer def mock_etree_parse(data): """Convert a string into a file-like object to pass in the XML""" f = BytesIO(data.strip().encode('utf-8')) return myparse(f) def mock_pkiuser_entity(): """Return struct_passwd for mocked pkiuser""" StructPasswd = namedtuple( "StructPasswd", [ "pw_name", "pw_passwd", "pw_uid", "pw_gid", "pw_gecos", "pw_dir", "pw_shell", ] ) pkiuser_entity = StructPasswd( constants.PKI_USER, pw_passwd="x", pw_uid=-1, pw_gid=-1, pw_gecos="", pw_dir="/dev/null", pw_shell="/sbin/nologin", ) return pkiuser_entity # Format of test_data is: # ( # is_newer_tomcat (boolean), # XML input, # expected secret attribute(s), # expected password(s), # rewrite of XML file expected (boolean), # ) test_data = ( ( # Case 1: Upgrade requiredSecret to secret True, textwrap.dedent(""" <?xml version="1.0" encoding="UTF-8"?> <Server port="1234" shutdown="SHUTDOWN"> <Service name="Catalina"> <Connector port="9000" protocol="AJP/1.3" redirectPort="443" address="localhost" requiredSecret="testing_ajp_secret" /> </Service> </Server> """), ('secret',), ('testing_ajp_secret',), ('requiredSecret',), True, ), ( # Case 2: One connector with secret, no update is needed True, textwrap.dedent(""" <?xml version="1.0" encoding="UTF-8"?> <Server port="1234" shutdown="SHUTDOWN"> <Service name="Catalina"> <Connector port="9000" protocol="AJP/1.3" redirectPort="443" address="localhost" secret="testing_ajp_secret" /> </Service> </Server> """), ('secret',), ('testing_ajp_secret',), ('requiredSecret',), False, ), ( # Case 3: Two connectors, old secret attribute, different secrets True, textwrap.dedent(""" <?xml version="1.0" encoding="UTF-8"?> <Server port="1234" shutdown="SHUTDOWN"> <Service name="Catalina"> <Connector port="9000" protocol="AJP/1.3" redirectPort="443" address="localhost4" requiredSecret="testing_ajp_secret" /> <Connector port="9000" protocol="AJP/1.3" redirectPort="443" address="localhost6" requiredSecret="other_secret" /> </Service> </Server> """), ('secret', 'secret'), ('testing_ajp_secret', 'testing_ajp_secret'), ('requiredSecret', 'requiredSecret'), True, ), ( # Case 4: Two connectors, new secret attribute, same secrets True, textwrap.dedent(""" <?xml version="1.0" encoding="UTF-8"?> <Server port="1234" shutdown="SHUTDOWN"> <Service name="Catalina"> <Connector port="9000" protocol="AJP/1.3" redirectPort="443" address="localhost4" secret="testing_ajp_secret" /> <Connector port="9000" protocol="AJP/1.3" redirectPort="443" address="localhost6" secret="testing_ajp_secret" /> </Service> </Server> """), ('secret', 'secret'), ('testing_ajp_secret', 'testing_ajp_secret'), ('requiredSecret', 'requiredSecret'), False, ), ( # Case 5: Two connectors, no secrets True, textwrap.dedent(""" <?xml version="1.0" encoding="UTF-8"?> <Server port="1234" shutdown="SHUTDOWN"> <Service name="Catalina"> <Connector port="9000" protocol="AJP/1.3" redirectPort="443" address="localhost4" /> <Connector port="9000" protocol="AJP/1.3" redirectPort="443" address="localhost6" /> </Service> </Server> """), ('secret', 'secret'), ('RANDOM', 'RANDOM'), ('requiredSecret', 'requiredSecret'), True, ), ( # Case 6: Older tomcat, no update needed for requiredSecret False, textwrap.dedent(""" <?xml version="1.0" encoding="UTF-8"?> <Server port="1234" shutdown="SHUTDOWN"> <Service name="Catalina"> <Connector port="9000" protocol="AJP/1.3" redirectPort="443" address="localhost" requiredSecret="testing_ajp_secret" /> </Service> </Server> """), ('requiredSecret',), ('testing_ajp_secret',), ('secret',), False, ), ( # Case 7: Older tomcat, both secrets are present, one s/b removed False, textwrap.dedent(""" <?xml version="1.0" encoding="UTF-8"?> <Server port="1234" shutdown="SHUTDOWN"> <Service name="Catalina"> <Connector port="9000" protocol="AJP/1.3" redirectPort="443" address="localhost" requiredSecret="testing_ajp_secret" secret="other_secret" /> </Service> </Server> """), ('requiredSecret',), ('testing_ajp_secret',), ('secret',), True, ), ) class TestAJPSecretUpgrade: @patch("ipaplatform.base.constants.pwd.getpwnam") @patch("ipaplatform.base.constants.os.chown") @patch("ipaserver.install.dogtaginstance.lxml.etree.parse") @pytest.mark.parametrize("test_data", test_data) def test_connecter(self, mock_parse, mock_chown, mock_getpwnam, test_data): is_newer, data, secret, expect, ex_secret, rewrite = test_data mock_chown.return_value = None mock_parse.return_value = mock_etree_parse(data) mock_getpwnam.return_value = mock_pkiuser_entity() dogtag = MyDogtagInstance(is_newer) with patch('ipaserver.install.dogtaginstance.open', mock_open()) \ as mocked_file: dogtag.secure_ajp_connector() if rewrite: newdata = mocked_file().write.call_args f = BytesIO(newdata[0][0]) server_xml = myparse(f) doc = server_xml.getroot() connectors = doc.xpath('//Connector[@protocol="AJP/1.3"]') assert len(connectors) == len(secret) i = 0 for connector in connectors: if expect[i] == 'RANDOM': assert connector.attrib[secret[i]] else: assert connector.attrib[secret[i]] == expect[i] assert connector.attrib.get(ex_secret[i]) is None i += 1 else: assert mocked_file().write.call_args is None
7,879
Python
.py
216
26.324074
79
0.549176
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,334
test_login_password.py
freeipa_freeipa/ipatests/test_ipaserver/test_login_password.py
# Copyright (C) 2023 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import pytest import uuid from ipatests.test_ipaserver.httptest import Unauthorized_HTTP_test from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test from ipatests.util import assert_equal from ipalib import api, errors from ipapython.ipautil import run testuser = u'tuser' password = u'password' @pytest.mark.tier1 class test_login_password(XMLRPC_test, Unauthorized_HTTP_test): app_uri = '/ipa/session/login_password' @pytest.fixture(autouse=True) def login_setup(self, request): ccache = os.path.join('/tmp', str(uuid.uuid4())) try: api.Command['user_add'](uid=testuser, givenname=u'Test', sn=u'User') api.Command['passwd'](testuser, password=password) run(['kinit', testuser], stdin='{0}\n{0}\n{0}\n'.format(password), env={"KRB5CCNAME": ccache}) except errors.ExecutionError as e: pytest.skip( 'Cannot set up test user: %s' % e ) def fin(): try: api.Command['user_del']([testuser]) except errors.NotFound: pass os.unlink(ccache) request.addfinalizer(fin) def _login(self, user, password, host=None): return self.send_request(params={'user': str(user), 'password' : str(password)}, host=host) def test_bad_options(self): for params in ( None, # no params {"user": "foo"}, # missing options {"user": "foo", "password": ""}, # empty option ): response = self.send_request(params=params) assert_equal(response.status, 400) assert_equal(response.reason, 'Bad Request') def test_invalid_auth(self): response = self._login(testuser, 'wrongpassword') assert_equal(response.status, 401) assert_equal(response.getheader('X-IPA-Rejection-Reason'), 'invalid-password') def test_invalid_referer(self): response = self._login(testuser, password, 'attacker.test') assert_equal(response.status, 400) def test_success(self): response = self._login(testuser, password) assert_equal(response.status, 200) assert response.getheader('X-IPA-Rejection-Reason') is None
3,123
Python
.py
72
35.5
80
0.640857
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,335
test_kadmin.py
freeipa_freeipa/ipatests/test_ipaserver/test_kadmin.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # """ Test suite for creating principals via kadmin.local and modifying their keys """ import os import pytest import tempfile from ipalib import api from ipaserver.install import installutils @pytest.fixture def keytab(): fd, keytab_path = tempfile.mkstemp(suffix='.keytab') os.close(fd) try: yield keytab_path finally: try: os.remove(keytab_path) except OSError: pass @pytest.fixture() def service_in_kerberos_subtree(request): princ = u'svc1/{0.host}@{0.realm}'.format(api.env) installutils.kadmin_addprinc(princ) def fin(): try: installutils.kadmin( 'delprinc -force {}'.format(princ)) except Exception: pass request.addfinalizer(fin) return princ @pytest.fixture() def service_in_service_subtree(request): princ = u'svc2/{0.host}@{0.realm}'.format(api.env) rpcclient = api.Backend.rpcclient was_connected = rpcclient.isconnected() if not was_connected: rpcclient.connect() api.Command.service_add(princ) def fin(): try: api.Command.service_del(princ) except Exception: pass try: if not was_connected: rpcclient.disconnect() except Exception: pass request.addfinalizer(fin) return princ @pytest.fixture(params=["service_in_kerberos_subtree", "service_in_service_subtree"]) def service(request): return request.getfixturevalue(request.param) @pytest.mark.skipif( os.getuid() != 0, reason="kadmin.local is accesible only to root") class TestKadmin: def assert_success(self, command, *args): """ Since kadmin.local returns 0 also when internal errors occur, we have to catch the command's stderr and check that it is empty """ result = command(*args) assert not result.error_output def test_create_keytab(self, service, keytab): """ tests that ktadd command works for both types of services """ self.assert_success( installutils.create_keytab, keytab, service) def test_change_key(self, service, keytab): """ tests that both types of service can have passwords changed using kadmin """ self.assert_success( installutils.create_keytab, keytab, service) self.assert_success( installutils.kadmin, 'change_password -randkey {}'.format(service)) def test_append_key(self, service, keytab): """ Tests that we can create a new keytab for both service types and then append new keys to it """ self.assert_success( installutils.create_keytab, keytab, service) self.assert_success( installutils.create_keytab, keytab, service) def test_getprincs(self): """ tests that kadmin.local getprincs command returns a list of principals """ self.assert_success(installutils.kadmin, 'getprincs')
3,274
Python
.py
106
23.009434
78
0.625835
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,336
test_otptoken_import.py
freeipa_freeipa/ipatests/test_ipaserver/test_otptoken_import.py
# Authors: # Nathaniel McCallum <npmccallum@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import codecs import os import pytest from ipaserver.install.ipa_otptoken_import import PSKCDocument, ValidationError from ipaserver.install.ipa_otptoken_import import convertHashName basename = os.path.join(os.path.dirname(__file__), "data") @pytest.mark.tier1 class test_otptoken_import: def test_figure3(self): doc = PSKCDocument(os.path.join(basename, "pskc-figure3.xml")) assert doc.keyname is None assert [(t.id, t.options) for t in doc.getKeyPackages()] == \ [(u'12345678', { 'ipatokenotpkey': u'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', 'ipatokenvendor': u'Manufacturer', 'ipatokenserial': u'987654321', 'ipatokenhotpcounter': 0, 'ipatokenotpdigits': 8, 'type': u'hotp', })] def test_figure4(self): doc = PSKCDocument(os.path.join(basename, "pskc-figure4.xml")) assert doc.keyname is None try: [(t.id, t.options) for t in doc.getKeyPackages()] except ValidationError: # Referenced keys are not supported. pass else: assert False def test_figure5(self): doc = PSKCDocument(os.path.join(basename, "pskc-figure5.xml")) assert doc.keyname is None try: [(t.id, t.options) for t in doc.getKeyPackages()] except ValidationError: # PIN Policy is not supported. pass else: assert False def test_figure6(self): doc = PSKCDocument(os.path.join(basename, "pskc-figure6.xml")) assert doc.keyname == 'Pre-shared-key' doc.setKey(codecs.decode('12345678901234567890123456789012', 'hex')) assert [(t.id, t.options) for t in doc.getKeyPackages()] == \ [(u'12345678', { 'ipatokenotpkey': u'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', 'ipatokenvendor': u'Manufacturer', 'ipatokenserial': u'987654321', 'ipatokenhotpcounter': 0, 'ipatokenotpdigits': 8, 'type': u'hotp'})] def test_figure7(self): doc = PSKCDocument(os.path.join(basename, "pskc-figure7.xml")) assert doc.keyname == 'My Password 1' doc.setKey(b'qwerty') assert [(t.id, t.options) for t in doc.getKeyPackages()] == \ [(u'123456', { 'ipatokenotpkey': u'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', 'ipatokenvendor': u'TokenVendorAcme', 'ipatokenserial': u'987654321', 'ipatokenotpdigits': 8, 'type': u'hotp'})] def test_figure8(self): try: PSKCDocument(os.path.join(basename, "pskc-figure8.xml")) except NotImplementedError: # X.509 is not supported. pass else: assert False def test_invalid(self): try: PSKCDocument(os.path.join(basename, "pskc-invalid.xml")) except ValueError: # File is invalid. pass else: assert False def test_mini(self): try: doc = PSKCDocument(os.path.join(basename, "pskc-mini.xml")) for t in doc.getKeyPackages(): t._PSKCKeyPackage__process() except ValidationError: # Unsupported token type. pass else: assert False def test_full(self): doc = PSKCDocument(os.path.join(basename, "full.xml")) assert [(t.id, t.options) for t in doc.getKeyPackages()] == \ [(u'KID1', { 'ipatokenotpkey': u'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', 'ipatokennotafter': u'20060531000000Z', 'ipatokennotbefore': u'20060501000000Z', 'ipatokenserial': u'SerialNo-IssueNo', 'ipatokentotpclockoffset': 60000, 'ipatokenotpalgorithm': u'sha1', 'ipatokenvendor': u'iana.dummy', 'description': u'FriendlyName', 'ipatokentotptimestep': 200, 'ipatokenhotpcounter': 0, 'ipatokenmodel': u'Model', 'ipatokenotpdigits': 8, 'type': u'hotp', })] def test_valid_tokens(self): assert convertHashName('sha1') == u'sha1' assert convertHashName('hmac-sha1') == u'sha1' assert convertHashName('sha224') == u'sha224' assert convertHashName('hmac-sha224') == u'sha224' assert convertHashName('sha256') == u'sha256' assert convertHashName('hmac-sha256') == u'sha256' assert convertHashName('sha384') == u'sha384' assert convertHashName('hmac-sha384') == u'sha384' assert convertHashName('sha512') == u'sha512' assert convertHashName('hmac-sha512') == u'sha512' def test_invalid_tokens(self): """The conversion defaults to sha1 on unknown hashing""" assert convertHashName('something-sha256') == u'sha1' assert convertHashName('') == u'sha1' assert convertHashName(None) == u'sha1'
5,848
Python
.py
136
33.25
79
0.612847
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,337
test_migratepw.py
freeipa_freeipa/ipatests/test_ipaserver/test_migratepw.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # import pytest from ipatests.test_ipaserver.httptest import Unauthorized_HTTP_test from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test from ipatests.util import assert_equal from ipalib import api, errors testuser = u'tuser' password = u'password' @pytest.mark.tier1 class test_migratepw(XMLRPC_test, Unauthorized_HTTP_test): """ Test password migrate end point """ app_uri = '/ipa/migration/migration.py' @pytest.fixture(autouse=True) def migratepw_setup(self, request): """ Prepare for tests """ api.Command['user_add'](uid=testuser, givenname=u'Test', sn=u'User') api.Command['passwd'](testuser, password=password) def fin(): try: api.Command['user_del']([testuser]) except errors.NotFound: pass request.addfinalizer(fin) def _migratepw(self, user, password, method='POST'): """ Make password migrate request to server """ return self.send_request(method, params={'username': str(user), 'password': str(password)}, ) def test_bad_params(self): """ Test against bad (missing, empty) params """ for params in (None, # no params {'username': 'foo'}, # missing password {'password': 'bar'}, # missing username {'username': '', 'password': ''}, # empty options {'username': '', 'password': 'bar'}, # empty username {'username': 'foo', 'password': ''}, # empty password ): response = self.send_request(params=params) assert_equal(response.status, 400) assert_equal(response.reason, 'Bad Request') def test_not_post_method(self): """ Test redirection of non POST request """ response = self._migratepw(testuser, password, method='GET') assert_equal(response.status, 302) assert response.msg assert_equal(response.msg['Location'], 'index.html') def test_invalid_password(self): """ Test invalid password """ response = self._migratepw(testuser, 'wrongpassword') assert_equal(response.status, 200) assert_equal(response.getheader('X-IPA-Migrate-Result'), 'invalid-password') def test_migration_success(self): """ Test successful migration scenario """ response = self._migratepw(testuser, password) assert_equal(response.status, 200) assert_equal(response.getheader('X-IPA-Migrate-Result'), 'ok')
2,956
Python
.py
76
28.197368
76
0.559358
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,338
__init__.py
freeipa_freeipa/ipatests/test_ipaserver/__init__.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Sub-package containing unit tests for `ipaserver` package. """ import ipatests.util ipatests.util.check_ipaclient_unittests()
911
Python
.py
23
38.478261
71
0.778531
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,339
test_version_comparison.py
freeipa_freeipa/ipatests/test_ipaserver/test_version_comparison.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # """ tests for correct RPM version comparison """ from __future__ import absolute_import from ipaplatform.tasks import tasks import pytest version_strings = [ ("3.0.0-1.el6", "3.0.0-2.el6", "older"), ("3.0.0-1.el6_8", "3.0.0-1.el6_8.1", "older"), ("3.0.0-42.el6", "3.0.0-1.el6", "newer"), ("3.0.0-1.el6", "3.0.0-42.el6", "older"), ("3.0.0-42.el6", "3.3.3-1.fc20", "older"), ("4.2.0-15.el7", "4.2.0-15.el7_2.3", "older"), ("4.2.0-15.el7_2", "4.2.0-15.el7_2.3", "older"), ("4.2.0-15.el7_2.3", "4.2.0-15.el7_2.3", "equal"), ("4.2.0-15.el7_2.3", "4.2.0-15.el7_2.2", "newer"), ("4.2.0-1.fc23", "4.2.1-1.fc23", "older"), ("4.2.3-alpha1.fc23", "4.2.3-2.fc23", "older"), # numeric version elements # have precedence over # non-numeric ones ("4.3.90.201601080923GIT55aeea7-0.fc23", "4.3.0-1.fc23", "newer") ] @pytest.fixture(params=version_strings) def versions(request): return request.param class TestVersionComparsion: def test_versions(self, versions): version_string1, version_string2, expected_comparison = versions ver1 = tasks.parse_ipa_version(version_string1) ver2 = tasks.parse_ipa_version(version_string2) if expected_comparison == "newer": assert ver1 > ver2 elif expected_comparison == "older": assert ver1 < ver2 elif expected_comparison == "equal": assert ver1 == ver2 else: raise TypeError( "Unexpected comparison string: {}".format(expected_comparison) )
1,740
Python
.py
43
32.372093
79
0.569395
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,340
test_dnssec.py
freeipa_freeipa/ipatests/test_ipaserver/test_dnssec.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # """ Test the `ipaserver/dnssec` package. """ import dns.name from ipaserver.dnssec.odsmgr import ODSZoneListReader ZONELIST_XML = """<?xml version="1.0" encoding="UTF-8"?> <ZoneList> <Zone name="ipa.example"> <Policy>default</Policy> <Adapters> <Input> <Adapter type="File">/var/lib/ipa/dns/zone/entryUUID/12345</Adapter> </Input> <Output> <Adapter type="File">/var/lib/ipa/dns/zone/entryUUID/12345</Adapter> </Output> </Adapters> </Zone> </ZoneList> """ def test_ods_zonelist_reader(): uuid = '12345' name = dns.name.from_text('ipa.example.') reader = ODSZoneListReader("<ZoneList/>") assert reader.mapping == {} assert reader.names == set() assert reader.uuids == set() reader = ODSZoneListReader(ZONELIST_XML) assert reader.mapping == {uuid: name} assert reader.names == {name} assert reader.uuids == {uuid}
985
Python
.py
34
24.941176
76
0.669492
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,341
httptest.py
freeipa_freeipa/ipatests/test_ipaserver/httptest.py
# Authors: # Martin Kosek <mkosek@redhat.com> # # Copyright (C) 2012 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Base class for HTTP request tests """ import urllib from ipalib import api, util class Unauthorized_HTTP_test: """ Base class for simple HTTP request tests executed against URI with no required authorization """ app_uri = '' host = api.env.host cacert = api.env.tls_ca_cert content_type = 'application/x-www-form-urlencoded' accept_language = 'en-us' def send_request(self, method='POST', params=None, host=None): """ Send a request to HTTP server :param key When not None, overrides default app_uri """ if params is not None: if self.content_type == 'application/x-www-form-urlencoded': params = urllib.parse.urlencode(params, True) if host: url = 'https://' + host + self.app_uri else: url = 'https://' + self.host + self.app_uri headers = {'Content-Type': self.content_type, 'Accept-Language': self.accept_language, 'Referer': url} conn = util.create_https_connection( self.host, cafile=self.cacert) conn.request(method, self.app_uri, params, headers) return conn.getresponse()
1,997
Python
.py
52
32.75
72
0.673206
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,342
test_changepw.py
freeipa_freeipa/ipatests/test_ipaserver/test_changepw.py
# Authors: # Martin Kosek <mkosek@redhat.com> # # Copyright (C) 2012 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import pytest from ipatests.test_ipaserver.httptest import Unauthorized_HTTP_test from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test from ipatests.util import assert_equal from ipalib import api, errors from ipapython.dn import DN from ipapython.ipaldap import ldap_initialize testuser = u'tuser' old_password = u'old_password' new_password = u'new_password' @pytest.mark.tier1 class test_changepw(XMLRPC_test, Unauthorized_HTTP_test): app_uri = '/ipa/session/change_password' @pytest.fixture(autouse=True) def changepw_setup(self, request): try: api.Command['user_add'](uid=testuser, givenname=u'Test', sn=u'User') api.Command['passwd'](testuser, password=u'old_password') except errors.ExecutionError as e: pytest.skip( 'Cannot set up test user: %s' % e ) def fin(): try: api.Command['user_del']([testuser]) except errors.NotFound: pass request.addfinalizer(fin) def _changepw(self, user, old_password, new_password, host=None): return self.send_request(params={'user': str(user), 'old_password' : str(old_password), 'new_password' : str(new_password)}, host=host ) def _checkpw(self, user, password): dn = str(DN(('uid', user), api.env.container_user, api.env.basedn)) conn = ldap_initialize(api.env.ldap_uri) try: conn.simple_bind_s(dn, password) finally: conn.unbind_s() def test_bad_options(self): for params in (None, # no params {'user': 'foo'}, # missing options {'user': 'foo', 'old_password' : 'old'}, # missing option {'user': 'foo', 'old_password' : 'old', 'new_password' : ''}, # empty option ): response = self.send_request(params=params) assert_equal(response.status, 400) assert_equal(response.reason, 'Bad Request') def test_invalid_auth(self): response = self._changepw(testuser, 'wrongpassword', 'new_password') assert_equal(response.status, 200) assert_equal(response.getheader('X-IPA-Pwchange-Result'), 'invalid-password') # make sure that password is NOT changed self._checkpw(testuser, old_password) def test_invalid_referer(self): response = self._changepw(testuser, old_password, new_password, 'attacker.test') assert_equal(response.status, 400) # make sure that password is NOT changed self._checkpw(testuser, old_password) def test_pwpolicy_error(self): response = self._changepw(testuser, old_password, '1') assert_equal(response.status, 200) assert_equal(response.getheader('X-IPA-Pwchange-Result'), 'policy-error') assert_equal(response.getheader('X-IPA-Pwchange-Policy-Error'), 'Constraint violation: Password is too short') # make sure that password is NOT changed self._checkpw(testuser, old_password) def test_pwpolicy_success(self): response = self._changepw(testuser, old_password, new_password) assert_equal(response.status, 200) assert_equal(response.getheader('X-IPA-Pwchange-Result'), 'ok') # make sure that password IS changed self._checkpw(testuser, new_password)
4,443
Python
.py
97
36.257732
85
0.625723
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,343
test_ipap11helper.py
freeipa_freeipa/ipatests/test_ipaserver/test_ipap11helper.py
# -*- coding: utf-8 -*- # # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # """ Test the `ipapython/ipap11helper/p11helper.c` module. """ from __future__ import absolute_import from binascii import hexlify import os import os.path import logging import subprocess import tempfile import pytest from ipaplatform.paths import paths from ipaserver import p11helper as _ipap11helper pytestmark = pytest.mark.tier0 CONFIG_DATA = """ # SoftHSM v2 configuration file directories.tokendir = %s/tokens objectstore.backend = file """ LIBSOFTHSM = paths.LIBSOFTHSM2_SO SOFTHSM2_UTIL = paths.SOFTHSM2_UTIL logging.basicConfig(level=logging.INFO) log = logging.getLogger('t') master_key_label = u"master-ž" # random non-ascii character to test unicode master_key_id = "m" replica1_key_label = u"replica1" replica1_key_id = "id1" replica1_import_label = u"replica1-import" replica1_import_id = "id1-import" replica1_new_label = u"replica1-new-label-ž" replica2_key_label = u"replica2" replica2_key_id = "id2" replica_non_existent_label = u"replica-nonexistent" @pytest.fixture(scope="module") def token_path(): token_path = tempfile.mkdtemp(prefix='pytest_', suffix='_pkcs11') os.mkdir(os.path.join(token_path, 'tokens')) return token_path @pytest.fixture(scope="module") def p11(request, token_path): with open(os.path.join(token_path, 'softhsm2.conf'), 'w') as cfg: cfg.write(CONFIG_DATA % token_path) args = [ SOFTHSM2_UTIL, '--init-token', '--free', '--label', 'test', '--pin', '1234', '--so-pin', '1234' ] os.environ['SOFTHSM2_CONF'] = os.path.join(token_path, 'softhsm2.conf') subprocess.check_call(args, cwd=token_path) try: p11 = _ipap11helper.P11_Helper('test', "1234", LIBSOFTHSM) except _ipap11helper.Error: pytest.fail('Failed to initialize the helper object.', pytrace=False) def fin(): try: p11.finalize() except _ipap11helper.Error: pytest.fail('Failed to finalize the helper object.', pytrace=False) finally: subprocess.call( [SOFTHSM2_UTIL, '--delete-token', '--label', 'test'], cwd=token_path ) os.environ.pop('SOFTHSM2_CONF', None) request.addfinalizer(fin) return p11 class test_p11helper: def test_generate_master_key(self, p11): assert p11.generate_master_key(master_key_label, master_key_id, key_length=16, cka_wrap=True, cka_unwrap=True) def test_search_for_master_key(self, p11): master_key = p11.find_keys(_ipap11helper.KEY_CLASS_SECRET_KEY, label=master_key_label, id=master_key_id) assert len(master_key) == 1, "The master key should exist." def test_generate_replica_key_pair(self, p11): assert p11.generate_replica_key_pair(replica1_key_label, replica1_key_id, pub_cka_wrap=True, priv_cka_unwrap=True) def test_find_key(self, p11): rep1_pub = p11.find_keys(_ipap11helper.KEY_CLASS_PUBLIC_KEY, label=replica1_key_label, cka_wrap=True) assert len(rep1_pub) == 1, ("replica key pair has to contain " "1 pub key instead of %s" % len(rep1_pub)) rep1_priv = p11.find_keys(_ipap11helper.KEY_CLASS_PRIVATE_KEY, label=replica1_key_label, cka_unwrap=True) assert len(rep1_priv) == 1, ("replica key pair has to contain 1 " "private key instead of %s" % len(rep1_priv)) def test_find_key_by_uri(self, p11): rep1_pub = p11.find_keys(uri="pkcs11:object=replica1;objecttype=public") assert len(rep1_pub) == 1, ("replica key pair has to contain 1 pub " "key instead of %s" % len(rep1_pub)) def test_get_attribute_from_object(self, p11): rep1_pub = p11.find_keys(_ipap11helper.KEY_CLASS_PUBLIC_KEY, label=replica1_key_label, cka_wrap=True)[0] iswrap = p11.get_attribute(rep1_pub, _ipap11helper.CKA_WRAP) assert iswrap is True, "replica public key has to have CKA_WRAP = TRUE" def test_generate_replica_keypair_with_extractable_private_key(self, p11): assert p11.generate_replica_key_pair(replica2_key_label, replica2_key_id, pub_cka_wrap=True, priv_cka_unwrap=True, priv_cka_extractable=True) def test_find_key_on_nonexistent_key_pair(self, p11): test_list = p11.find_keys(_ipap11helper.KEY_CLASS_PUBLIC_KEY, label=replica_non_existent_label) assert len(test_list) == 0, ("list should be empty because label " "'%s' should not exist" % replica_non_existent_label) def test_export_import_of_public_key(self, p11, token_path): rep1_pub = p11.find_keys(_ipap11helper.KEY_CLASS_PUBLIC_KEY, label=replica1_key_label, cka_wrap=True)[0] pub = p11.export_public_key(rep1_pub) log.debug("Exported public key %s", hexlify(pub)) pubfile = os.path.join(token_path, "public_key.asn1.der") with open(pubfile, "wb") as f: f.write(pub) rep1_pub_import = p11.import_public_key(replica1_import_label, replica1_import_id, pub, cka_wrap=True) log.debug('imported replica 1 public key: %s', rep1_pub_import) # test public key import rep1_modulus_orig = p11.get_attribute(rep1_pub, _ipap11helper.CKA_MODULUS) rep1_modulus_import = p11.get_attribute(rep1_pub_import, _ipap11helper.CKA_MODULUS) log.debug('rep1_modulus_orig = 0x%s', hexlify(rep1_modulus_orig)) log.debug('rep1_modulus_import = 0x%s', hexlify(rep1_modulus_import)) assert rep1_modulus_import == rep1_modulus_orig rep1_pub_exp_orig = p11.get_attribute( rep1_pub, _ipap11helper.CKA_PUBLIC_EXPONENT) rep1_pub_exp_import = p11.get_attribute( rep1_pub_import, _ipap11helper.CKA_PUBLIC_EXPONENT) log.debug('rep1_pub_exp_orig = 0x%s', hexlify(rep1_pub_exp_orig)) log.debug('rep1_pub_exp_import = 0x%s', hexlify(rep1_pub_exp_import)) assert rep1_pub_exp_import == rep1_pub_exp_orig def test_wrap_unwrap_key_by_master_key_with_AES(self, p11, token_path): master_key = p11.find_keys(_ipap11helper.KEY_CLASS_SECRET_KEY, label=master_key_label, id=master_key_id)[0] rep2_priv = p11.find_keys(_ipap11helper.KEY_CLASS_PRIVATE_KEY, label=replica2_key_label, cka_unwrap=True)[0] log.debug("wrapping dnssec priv key by master key") wrapped_priv = p11.export_wrapped_key( rep2_priv, master_key, _ipap11helper.MECH_AES_KEY_WRAP_PAD ) assert wrapped_priv log.debug("wrapped_dnssec priv key: %s", hexlify(wrapped_priv)) privfile = os.path.join(token_path, "wrapped_priv.der") with open(privfile, "wb") as f: f.write(wrapped_priv) assert p11.import_wrapped_private_key( u'test_import_wrapped_priv', '1', wrapped_priv, master_key, _ipap11helper.MECH_AES_KEY_WRAP_PAD, _ipap11helper.KEY_TYPE_RSA ) def test_wrap_unwrap_key_by_master_key_with_RSA_PKCS(self, p11): master_key = p11.find_keys(_ipap11helper.KEY_CLASS_SECRET_KEY, label=master_key_label, id=master_key_id)[0] rep2_pub = p11.find_keys(_ipap11helper.KEY_CLASS_PUBLIC_KEY, label=replica2_key_label, cka_wrap=True)[0] rep2_priv = p11.find_keys(_ipap11helper.KEY_CLASS_PRIVATE_KEY, label=replica2_key_label, cka_unwrap=True)[0] wrapped = p11.export_wrapped_key(master_key, rep2_pub, _ipap11helper.MECH_RSA_PKCS) assert wrapped log.debug("wrapped key MECH_RSA_PKCS (secret master wrapped by pub " "key): %s", hexlify(wrapped)) assert p11.import_wrapped_secret_key(u'test_import_wrapped', '2', wrapped, rep2_priv, _ipap11helper.MECH_RSA_PKCS, _ipap11helper.KEY_TYPE_AES) def test_wrap_unwrap_by_master_key_with_RSA_PKCS_OAEP(self, p11): master_key = p11.find_keys(_ipap11helper.KEY_CLASS_SECRET_KEY, label=master_key_label, id=master_key_id)[0] rep2_pub = p11.find_keys(_ipap11helper.KEY_CLASS_PUBLIC_KEY, label=replica2_key_label, cka_wrap=True)[0] rep2_priv = p11.find_keys(_ipap11helper.KEY_CLASS_PRIVATE_KEY, label=replica2_key_label, cka_unwrap=True)[0] wrapped = p11.export_wrapped_key(master_key, rep2_pub, _ipap11helper.MECH_RSA_PKCS_OAEP) assert wrapped log.debug("wrapped key MECH_RSA_PKCS_OAEP (secret master wrapped by " "pub key): %s", hexlify(wrapped)) assert p11.import_wrapped_secret_key(u'test_import_wrapped', '3', wrapped, rep2_priv, _ipap11helper.MECH_RSA_PKCS_OAEP, _ipap11helper.KEY_TYPE_AES) def test_set_attribute_on_object(self, p11): rep1_pub = p11.find_keys(_ipap11helper.KEY_CLASS_PUBLIC_KEY, label=replica1_key_label, cka_wrap=True)[0] test_label = replica1_new_label p11.set_attribute(rep1_pub, _ipap11helper.CKA_LABEL, test_label) assert p11.get_attribute(rep1_pub, _ipap11helper.CKA_LABEL) \ == test_label, "The labels do not match." def test_do_not_generate_identical_master_keys(self, p11): with pytest.raises(_ipap11helper.DuplicationError): p11.generate_master_key(master_key_label, master_key_id, key_length=16) master_key = p11.find_keys(_ipap11helper.KEY_CLASS_SECRET_KEY, label=master_key_label) assert len(master_key) == 1, ("There shouldn't be multiple keys " "with the same label.") def test_delete_key(self, p11): master_key = p11.find_keys(_ipap11helper.KEY_CLASS_SECRET_KEY, label=master_key_label, id=master_key_id)[0] rep1_pub = p11.find_keys(_ipap11helper.KEY_CLASS_PUBLIC_KEY, label=replica1_new_label, cka_wrap=True)[0] rep2_priv = p11.find_keys(_ipap11helper.KEY_CLASS_PRIVATE_KEY, label=replica2_key_label, cka_unwrap=True)[0] for key in (rep1_pub, rep2_priv, master_key): p11.delete_key(key) master_key = p11.find_keys(_ipap11helper.KEY_CLASS_SECRET_KEY, label=master_key_label, id=master_key_id) assert len(master_key) == 0, "The master key should be deleted." rep1_pub = p11.find_keys(_ipap11helper.KEY_CLASS_PUBLIC_KEY, label=replica1_new_label, cka_wrap=True) assert len(rep1_pub) == 0, ("The public key of replica1 pair should " "be deleted.") rep2_priv = p11.find_keys(_ipap11helper.KEY_CLASS_PRIVATE_KEY, label=replica2_key_label, cka_unwrap=True) assert len(rep2_priv) == 0, ("The private key of replica2 pair should" " be deleted.")
12,803
Python
.py
239
37.878661
80
0.557563
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,344
test_jsplugins.py
freeipa_freeipa/ipatests/test_ipaserver/test_jsplugins.py
# Copyright (C) 2020 FreeIPA Contributors see COPYING for license import os import pytest from ipalib import facts from ipatests.test_ipaserver.httptest import Unauthorized_HTTP_test from ipatests.util import assert_equal, assert_not_equal from ipaplatform.paths import paths @pytest.mark.tier1 @pytest.mark.skipif( not facts.is_ipa_configured(), reason="Requires configured IPA server", ) class test_jsplugins(Unauthorized_HTTP_test): app_uri = '/ipa/ui/js/freeipa/plugins.js' jsplugins = (('foo', 'foo.js'), ('bar', '')) content_type = 'application/javascript' def test_jsplugins(self): empty_response = "define([],function(){return[];});" # Step 1: make sure default response has no additional plugins response = self.send_request(method='GET') assert_equal(response.status, 200) response_data = response.read().decode(encoding='utf-8') assert_equal(response_data, empty_response) # Step 2: add fake plugins try: for (d, f) in self.jsplugins: dir = os.path.join(paths.IPA_JS_PLUGINS_DIR, d) if not os.path.exists(dir): os.mkdir(dir, 0o755) if f: with open(os.path.join(dir, f), 'w') as js: js.write("/* test js plugin */") except OSError as e: pytest.skip( 'Cannot set up test JS plugin: %s' % e ) # Step 3: query plugins to see if our plugins exist response = self.send_request(method='GET') assert_equal(response.status, 200) response_data = response.read().decode(encoding='utf-8') assert_not_equal(response_data, empty_response) for (d, f) in self.jsplugins: if f: assert "'" + d + "'" in response_data else: assert "'" + d + "'" not in response_data # Step 4: remove fake plugins try: for (d, f) in self.jsplugins: dir = os.path.join(paths.IPA_JS_PLUGINS_DIR, d) file = os.path.join(dir, f) if f and os.path.exists(file): os.unlink(file) if os.path.exists(dir): os.rmdir(dir) except OSError: pass # Step 5: make sure default response has no additional plugins response = self.send_request(method='GET') assert_equal(response.status, 200) response_data = response.read().decode(encoding='utf-8') assert_equal(response_data, empty_response)
2,615
Python
.py
62
32.032258
70
0.59166
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,345
test_secrets.py
freeipa_freeipa/ipatests/test_ipaserver/test_secrets.py
# Copyright (C) 2015 FreeIPA Project Contributors - see LICENSE file from __future__ import print_function from ipaserver.secrets.store import iSecStore, NAME_DB_MAP, NSSCertDB import os import shutil import subprocess import tempfile import pytest def _test_password_callback(): with open('test-ipa-sec-store/pwfile') as f: password = f.read() return password class TestiSecStore: certdb = None cert2db = None @pytest.fixture(autouse=True, scope="class") def isec_store_setup(self, request): cls = request.cls cls.testdir = tempfile.mkdtemp(suffix='ipa-sec-store') pwfile = os.path.join(cls.testdir, 'pwfile') with open(pwfile, 'w') as f: f.write('testpw') cls.certdb = os.path.join(cls.testdir, 'certdb') os.mkdir(cls.certdb) cls.cert2db = os.path.join(cls.testdir, 'cert2db') os.mkdir(cls.cert2db) seedfile = os.path.join(cls.testdir, 'seedfile') with open(seedfile, 'wb') as f: seed = os.urandom(1024) f.write(seed) subprocess.call( ['certutil', '-d', cls.certdb, '-N', '-f', pwfile], cwd=cls.testdir ) subprocess.call( ['certutil', '-d', cls.cert2db, '-N', '-f', pwfile], cwd=cls.testdir ) subprocess.call( ['certutil', '-d', cls.certdb, '-S', '-f', pwfile, '-s', 'CN=testCA', '-n', 'testCACert', '-x', '-t', 'CT,C,C', '-m', '1', '-z', seedfile], cwd=cls.testdir ) def fin(): shutil.rmtree(cls.testdir) request.addfinalizer(fin) def test_iSecStore(self): iss = iSecStore({}) NAME_DB_MAP['test'] = { 'type': 'NSSDB', 'path': self.certdb, 'handler': NSSCertDB, 'pwcallback': _test_password_callback, } value = iss.get('keys/test/testCACert') NAME_DB_MAP['test']['path'] = self.cert2db iss.set('keys/test/testCACert', value)
2,061
Python
.py
58
27.068966
69
0.571787
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,346
test_adtrust_mockup.py
freeipa_freeipa/ipatests/test_ipaserver/test_adtrust_mockup.py
# Copyright (C) 2018 FreeIPA Project Contributors - see LICENSE file from __future__ import print_function import ipaserver.install.adtrust as adtr from ipaserver.install.adtrust import set_and_check_netbios_name from collections import namedtuple from unittest import mock from io import StringIO import pytest class ApiMockup: Backend = namedtuple('Backend', 'ldap2') Calls = namedtuple('Callbacks', 'retrieve_netbios_name') env = namedtuple('Environment', 'domain') class TestNetbiosName: api = None @pytest.fixture(autouse=True, scope="class") def netbiosname_setup(self, request): cls = request.cls api = ApiMockup() ldap2 = namedtuple('LDAP', 'isconnected') ldap2.isconnected = mock.MagicMock(return_value=True) api.Backend.ldap2 = ldap2 api.Calls.retrieve_netbios_name = adtr.retrieve_netbios_name adtr.retrieve_netbios_name = mock.MagicMock(return_value=None) cls.api = api def fin(): adtr.retrieve_netbios_name = cls.api.Calls.retrieve_netbios_name request.addfinalizer(fin) def test_NetbiosName(self): """ Test set_and_check_netbios_name() using permutation of two inputs: - predefined and not defined NetBIOS name - unattended and interactive run As result, the function has to return expected NetBIOS name in all cases. For interactive run we override input to force what we expect. """ self.api.env.domain = 'example.com' expected_nname = 'EXAMPLE' # NetBIOS name, unattended, should set the name? tests = ((expected_nname, True, False), (None, True, True), (None, False, True), (expected_nname, False, False)) with mock.patch('sys.stdin', new_callable=StringIO) as stdin: stdin.write(expected_nname + '\r') for test in tests: nname, setname = set_and_check_netbios_name( test[0], test[1], self.api) assert expected_nname == nname assert setname == test[2]
2,147
Python
.py
50
34.42
76
0.649904
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,347
test_ldap.py
freeipa_freeipa/ipatests/test_ipaserver/test_ldap.py
# Authors: # Rob Crittenden <rcritten@redhat.com> # # Copyright (C) 2010 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Test some simple LDAP requests using the ldap2 backend # This fetches a certificate from a host principal so we can ensure that the # schema is working properly. We know this because the schema will tell the # encoder not to utf-8 encode binary attributes. # The DM password needs to be set in ~/.ipa/.dmpw from __future__ import absolute_import from datetime import datetime, timedelta import os import sys import pytest import six from ipaplatform.paths import paths from ipaserver.plugins.ldap2 import ldap2, AUTOBIND_DISABLED from ipalib import api, create_api, errors from ipapython.dn import DN if six.PY3: unicode = str @pytest.mark.tier0 @pytest.mark.needs_ipaapi class test_ldap: """ Test various LDAP client bind methods. """ @pytest.fixture(autouse=True) def ldap_setup(self, request): self.conn = None self.ldapuri = api.env.ldap_uri self.dn = DN(('krbprincipalname','ldap/%s@%s' % (api.env.host, api.env.realm)), ('cn','services'),('cn','accounts'),api.env.basedn) def fin(): if self.conn and self.conn.isconnected(): self.conn.disconnect() request.addfinalizer(fin) def test_anonymous(self): """ Test an anonymous LDAP bind using ldap2 """ self.conn = ldap2(api) self.conn.connect(autobind=AUTOBIND_DISABLED) dn = api.env.basedn entry_attrs = self.conn.get_entry(dn, ['associateddomain']) domain = entry_attrs.single_value['associateddomain'] assert domain == api.env.domain def test_GSSAPI(self): """ Test a GSSAPI LDAP bind using ldap2 """ self.conn = ldap2(api) self.conn.connect(autobind=AUTOBIND_DISABLED) entry_attrs = self.conn.get_entry(self.dn, ['usercertificate']) cert = entry_attrs.get('usercertificate')[0] assert cert.serial_number is not None def test_simple(self): """ Test a simple LDAP bind using ldap2 """ pwfile = api.env.dot_ipa + os.sep + ".dmpw" if os.path.isfile(pwfile): with open(pwfile, "r") as fp: dm_password = fp.read().rstrip() else: pytest.skip( "No directory manager password in %s" % pwfile ) self.conn = ldap2(api) self.conn.connect(bind_dn=DN(('cn', 'directory manager')), bind_pw=dm_password) entry_attrs = self.conn.get_entry(self.dn, ['usercertificate']) cert = entry_attrs.get('usercertificate')[0] assert cert.serial_number is not None def test_Backend(self): """ Test using the ldap2 Backend directly (ala ipa-server-install) """ # Create our own api because the one generated for the tests is # a client-only api. Then we register in the commands and objects # we need for the test. myapi = create_api(mode=None) myapi.bootstrap(context='cli', in_server=True, confdir=paths.ETC_IPA) myapi.finalize() pwfile = api.env.dot_ipa + os.sep + ".dmpw" if os.path.isfile(pwfile): with open(pwfile, "r") as fp: dm_password = fp.read().rstrip() else: pytest.skip( "No directory manager password in %s" % pwfile ) myapi.Backend.ldap2.connect(bind_dn=DN(('cn', 'Directory Manager')), bind_pw=dm_password) result = myapi.Command['service_show']('ldap/%s@%s' % (api.env.host, api.env.realm,)) entry_attrs = result['result'] cert = entry_attrs.get('usercertificate')[0] assert cert.serial_number is not None def test_autobind(self): """ Test an autobind LDAP bind using ldap2 """ self.conn = ldap2(api) try: self.conn.connect(autobind=True) except errors.ACIError: pytest.skip("Only executed as root") entry_attrs = self.conn.get_entry(self.dn, ['usercertificate']) cert = entry_attrs.get('usercertificate')[0] assert cert.serial_number is not None def test_generalized_time(self): """ Test that LDAP generalized time is converted to/from datetime """ self.conn = ldap2(api) try: self.conn.connect(autobind=True) except errors.ACIError: pytest.skip("Only executed as root") if not api.Backend.rpcclient.isconnected(): api.Backend.rpcclient.connect() newdate = datetime.now() + timedelta(days=365) lastdate = api.Backend.ldap2.encode(newdate).decode('utf-8') api.Command["user_mod"]( "admin", **dict(setattr=("krbprincipalexpiration=%s" % lastdate)) ) result = api.Command["user_find"]( **dict(krbprincipalexpiration=lastdate) ) assert result['count'] == 1 @pytest.mark.tier0 @pytest.mark.needs_ipaapi class test_LDAPEntry: """ Test the LDAPEntry class """ cn1 = [u'test1'] cn2 = [u'test2'] dn1 = DN(('cn', cn1[0])) dn2 = DN(('cn', cn2[0])) @pytest.fixture(autouse=True) def ldapentry_setup(self, request): self.ldapuri = api.env.ldap_uri self.conn = ldap2(api) self.conn.connect(autobind=AUTOBIND_DISABLED) self.entry = self.conn.make_entry(self.dn1, cn=self.cn1) def fin(): if self.conn and self.conn.isconnected(): self.conn.disconnect() request.addfinalizer(fin) def test_entry(self): e = self.entry assert e.dn is self.dn1 assert u'cn' in e assert u'cn' in e.keys() assert 'CN' in e if six.PY2: assert 'CN' not in e.keys() else: assert 'CN' in e.keys() assert 'commonName' in e if six.PY2: assert 'commonName' not in e.keys() else: assert 'commonName' in e.keys() assert e['CN'] is self.cn1 assert e['CN'] is e[u'cn'] e.dn = self.dn2 assert e.dn is self.dn2 def test_set_attr(self): e = self.entry e['commonName'] = self.cn2 assert u'cn' in e assert u'cn' in e.keys() assert 'CN' in e if six.PY2: assert 'CN' not in e.keys() else: assert 'CN' in e.keys() assert 'commonName' in e if six.PY2: assert 'commonName' not in e.keys() else: assert 'commonName' in e.keys() assert e['CN'] is self.cn2 assert e['CN'] is e[u'cn'] def test_del_attr(self): e = self.entry del e['CN'] assert 'CN' not in e assert 'CN' not in e.keys() assert u'cn' not in e assert u'cn' not in e.keys() assert 'commonName' not in e assert 'commonName' not in e.keys() def test_popitem(self): e = self.entry assert e.popitem() == ('cn', self.cn1) assert list(e) == [] def test_setdefault(self): e = self.entry assert e.setdefault('cn', self.cn2) == self.cn1 assert e['cn'] == self.cn1 assert e.setdefault('xyz', self.cn2) == self.cn2 assert e['xyz'] == self.cn2 def test_update(self): e = self.entry e.update({'cn': self.cn2}, xyz=self.cn2) assert e['cn'] == self.cn2 assert e['xyz'] == self.cn2 def test_pop(self): e = self.entry assert e.pop('cn') == self.cn1 assert 'cn' not in e assert e.pop('cn', 'default') == 'default' with pytest.raises(KeyError): e.pop('cn') def test_clear(self): e = self.entry e.clear() assert not e assert 'cn' not in e @pytest.mark.skipif(sys.version_info >= (3, 0), reason="Python 2 only") def test_has_key(self): e = self.entry assert not e.has_key('xyz') # noqa assert e.has_key('cn') # noqa assert e.has_key('COMMONNAME') # noqa def test_in(self): e = self.entry assert 'xyz' not in e assert 'cn' in e assert 'COMMONNAME' in e def test_get(self): e = self.entry assert e.get('cn') == self.cn1 assert e.get('commonname') == self.cn1 assert e.get('COMMONNAME', 'default') == self.cn1 assert e.get('bad key', 'default') == 'default' def test_single_value(self): e = self.entry assert e.single_value['cn'] == self.cn1[0] assert e.single_value['commonname'] == self.cn1[0] assert e.single_value.get('COMMONNAME', 'default') == self.cn1[0] assert e.single_value.get('bad key', 'default') == 'default' def test_sync(self): e = self.entry nice = e['test'] = [1, 2, 3] assert e['test'] is nice raw = e.raw['test'] assert raw == [b'1', b'2', b'3'] nice.remove(1) assert e.raw['test'] is raw assert raw == [b'2', b'3'] raw.append(b'4') assert e['test'] is nice assert nice == [2, 3, u'4'] nice.remove(2) raw.append(b'5') assert nice == [3, u'4'] assert raw == [b'2', b'3', b'4', b'5'] assert e['test'] is nice assert e.raw['test'] is raw assert nice == [3, u'4', u'5'] assert raw == [b'3', b'4', b'5'] nice.insert(0, 2) raw.remove(b'4') assert nice == [2, 3, u'4', u'5'] assert raw == [b'3', b'5'] assert e.raw['test'] is raw assert e['test'] is nice assert nice == [2, 3, u'5'] assert raw == [b'3', b'5', b'2'] raw = [b'a', b'b'] e.raw['test'] = raw assert e['test'] is not nice assert e['test'] == [u'a', u'b'] nice = 'not list' e['test'] = nice assert e['test'] is nice assert e.raw['test'] == [b'not list'] e.raw['test'].append(b'second') assert e['test'] == ['not list', u'second'] def test_modlist_with_varying_encodings(self): """ Test modlist is correct when only encoding of new value differs See: https://bugzilla.redhat.com/show_bug.cgi?id=1658302 """ dn_ipa_encoded = b'O=Red Hat\\, Inc.' dn_389ds_encoded = b'O=Red Hat\\2C Inc.' entry = self.entry entry.raw['distinguishedName'] = [dn_389ds_encoded] # This is to make entry believe that that value was part of the # original data we received from LDAP entry.reset_modlist() entry['distinguishedName'] = [entry['distinguishedName'][0]] assert entry.generate_modlist() == [ (1, 'distinguishedName', [dn_389ds_encoded]), (0, 'distinguishedName', [dn_ipa_encoded])]
11,593
Python
.py
312
28.939103
97
0.585931
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,348
test_serverroles.py
freeipa_freeipa/ipatests/test_ipaserver/test_serverroles.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # """ Tests for the serverroles backend """ from __future__ import absolute_import from collections import namedtuple import ldap import pytest from ipaplatform.paths import paths from ipalib import api, create_api, errors from ipapython.dn import DN from ipaserver.masters import ENABLED_SERVICE pytestmark = pytest.mark.needs_ipaapi def _make_service_entry(ldap_backend, dn, enabled=True, other_config=None): mods = { 'objectClass': ['top', 'nsContainer', 'ipaConfigObject'], } if enabled: mods.update({'ipaConfigString': [ENABLED_SERVICE]}) if other_config is not None: mods.setdefault('ipaConfigString', []) mods['ipaConfigString'].extend(other_config) return ldap_backend.make_entry(dn, **mods) def _make_master_entry(ldap_backend, dn, ca=False): mods = { 'objectClass': [ 'top', 'nsContainer', 'ipaReplTopoManagedServer', 'ipaSupportedDomainLevelConfig', 'ipaConfigObject', ], 'ipaMaxDomainLevel': ['1'], 'ipaMinDomainLevel': ['0'], 'ipaReplTopoManagedsuffix': [str(api.env.basedn)] } if ca: mods['ipaReplTopoManagedsuffix'].append('o=ipaca') return ldap_backend.make_entry(dn, **mods) _adtrust_agents = DN( ('cn', 'adtrust agents'), api.env.container_sysaccounts, api.env.basedn ) master_data = { 'ca-dns-dnssec-keymaster-pkinit-server': { 'services': { 'CA': { 'enabled': True, }, 'DNS': { 'enabled': True, }, 'DNSKeySync': { 'enabled': True, }, 'DNSSEC': { 'enabled': True, 'config': ['DNSSecKeyMaster'] }, 'KDC': { 'enabled': True, 'config': ['pkinitEnabled'] } }, 'expected_roles': { 'enabled': ['IPA master', 'CA server', 'DNS server'] }, 'expected_attributes': {'DNS server': 'dnssec_key_master_server', 'IPA master': 'pkinit_server_server'} }, 'ca-kra-renewal-master-pkinit-server': { 'services': { 'CA': { 'enabled': True, 'config': ['caRenewalMaster'] }, 'KRA': { 'enabled': True, }, 'KDC': { 'enabled': True, 'config': ['pkinitEnabled'] }, }, 'expected_roles': { 'enabled': ['IPA master', 'CA server', 'KRA server'] }, 'expected_attributes': {'CA server': 'ca_renewal_master_server', 'IPA master': 'pkinit_server_server'} }, 'dns-trust-agent': { 'services': { 'DNS': { 'enabled': True, }, 'DNSKeySync': { 'enabled': True, } }, 'attributes': { _adtrust_agents: { 'member': ['host'] } }, 'expected_roles': { 'enabled': ['IPA master', 'DNS server', 'AD trust agent'] } }, 'trust-agent': { 'attributes': { _adtrust_agents: { 'member': ['host'] } }, 'expected_roles': { 'enabled': ['IPA master', 'AD trust agent'] } }, 'trust-controller-dns': { 'services': { 'ADTRUST': { 'enabled': True, }, 'DNS': { 'enabled': True, }, 'DNSKeySync': { 'enabled': True, } }, 'attributes': { _adtrust_agents: { 'member': ['host', 'cifs'] } }, 'expected_roles': { 'enabled': ['IPA master', 'AD trust agent', 'AD trust controller', 'DNS server'] } }, 'trust-controller-ca': { 'services': { 'ADTRUST': { 'enabled': True, }, 'CA': { 'enabled': True, }, }, 'attributes': { _adtrust_agents: { 'member': ['host', 'cifs'] } }, 'expected_roles': { 'enabled': ['IPA master', 'AD trust agent', 'AD trust controller', 'CA server'] } }, 'configured-ca': { 'services': { 'CA': { 'enabled': False, }, }, 'expected_roles': { 'enabled': ['IPA master'], 'configured': ['CA server'] } }, 'configured-dns': { 'services': { 'DNS': { 'enabled': False, }, 'DNSKeySync': { 'enabled': False, } }, 'expected_roles': { 'enabled': ['IPA master'], 'configured': ['DNS server'] } }, 'mixed-state-dns': { 'services': { 'DNS': { 'enabled': False }, 'DNSKeySync': { 'enabled': True } }, 'expected_roles': { 'enabled': ['IPA master'], 'configured': ['DNS server'] } }, } class MockMasterTopology: """ object that will set up and tear down entries in LDAP backend to mimic a presence of real IPA masters with services running on them. """ ipamaster_services = [u'KDC', u'HTTP', u'KPASSWD'] def __init__(self, api_instance, domain_data): self.api = api_instance self.domain = self.api.env.domain self.domain_data = domain_data self.masters_base = DN( self.api.env.container_masters, self.api.env.basedn) self.test_master_dn = DN( ('cn', self.api.env.host), self.api.env.container_masters, self.api.env.basedn) self.ldap = self.api.Backend.ldap2 self.existing_masters = { m['cn'][0] for m in self.api.Command.server_find( u'', sizelimit=0, pkey_only=True, no_members=True, raw=True)['result']} self.original_dns_configs = self._remove_test_host_attrs() def iter_domain_data(self): MasterData = namedtuple('MasterData', ['dn', 'fqdn', 'services', 'attrs']) for name in self.domain_data: fqdn = self.get_fqdn(name) master_dn = self.get_master_dn(name) master_services = self.domain_data[name].get('services', {}) master_attributes = self.domain_data[name].get('attributes', {}) yield MasterData( dn=master_dn, fqdn=fqdn, services=master_services, attrs=master_attributes ) def get_fqdn(self, name): return '.'.join([name, self.domain]) def get_master_dn(self, name): return DN(('cn', self.get_fqdn(name)), self.masters_base) def get_service_dn(self, name, master_dn): return DN(('cn', name), master_dn) def _add_host_entry(self, fqdn): self.api.Command.host_add(fqdn, force=True) self.api.Command.hostgroup_add_member(u'ipaservers', host=fqdn) def _del_host_entry(self, fqdn): try: self.api.Command.host_del(fqdn) except errors.NotFound: pass def _add_service_entry(self, service, fqdn): return self.api.Command.service_add( '/'.join([service, fqdn]), force=True ) def _del_service_entry(self, service, fqdn): try: self.api.Command.service_del( '/'.join([service, fqdn]), ) except errors.NotFound: pass def _add_svc_entries(self, master_dn, svc_desc): for name in svc_desc: svc_dn = self.get_service_dn(name, master_dn) svc_mods = svc_desc[name] self.ldap.add_entry( _make_service_entry( self.ldap, svc_dn, enabled=svc_mods['enabled'], other_config=svc_mods.get('config', None))) self._add_ipamaster_services(master_dn) def _remove_svc_master_entries(self, master_dn): try: entries = self.ldap.get_entries( master_dn, ldap.SCOPE_SUBTREE ) except errors.NotFound: return if entries: entries.sort(key=lambda x: len(x.dn), reverse=True) for entry in entries: self.ldap.delete_entry(entry) def _add_ipamaster_services(self, master_dn): """ add all the service entries which are part of the IPA Master role """ for svc_name in self.ipamaster_services: svc_dn = self.get_service_dn(svc_name, master_dn) try: self.ldap.get_entry(svc_dn) except errors.NotFound: self.ldap.add_entry(_make_service_entry(self.ldap, svc_dn)) def _add_members(self, dn, fqdn, member_attrs): entry_attrs = self.ldap.get_entry(dn) value = entry_attrs.get('member', []) for a in member_attrs: if a == 'host': value.append( str(self.api.Object.host.get_dn(fqdn))) else: result = self._add_service_entry(a, fqdn)['result'] value.append(str(result['dn'])) entry_attrs['member'] = value self.ldap.update_entry(entry_attrs) def _remove_members(self, dn, fqdn, member_attrs): entry_attrs = self.ldap.get_entry(dn) value = set(entry_attrs.get('member', [])) if not value: return for a in member_attrs: if a == 'host': try: value.remove( str(self.api.Object.host.get_dn(fqdn))) except KeyError: pass else: try: value.remove( str(self.api.Object.service.get_dn( '/'.join([a, fqdn])))) except KeyError: pass self._del_service_entry(a, fqdn) entry_attrs['member'] = list(value) try: self.ldap.update_entry(entry_attrs) except (errors.NotFound, errors.EmptyModlist): pass def _remove_test_host_attrs(self): original_dns_configs = [] for attr_name in ( 'caRenewalMaster', 'dnssecKeyMaster', 'pkinitEnabled'): try: svc_entry = self.ldap.find_entry_by_attr( 'ipaConfigString', attr_name, 'ipaConfigObject', base_dn=self.test_master_dn) except errors.NotFound: continue else: original_dns_configs.append( (svc_entry.dn, list(svc_entry.get('ipaConfigString', []))) ) svc_entry[u'ipaConfigString'].remove(attr_name) self.ldap.update_entry(svc_entry) return original_dns_configs def _restore_test_host_attrs(self): for dn, config in self.original_dns_configs: try: svc_entry = self.api.Backend.ldap2.get_entry(dn) svc_entry['ipaConfigString'] = config self.ldap.update_entry(svc_entry) except (errors.NotFound, errors.EmptyModlist): continue def setup_data(self): for master_data in self.iter_domain_data(): # create host self._add_host_entry(master_data.fqdn) # create master self.ldap.add_entry( _make_master_entry( self.ldap, master_data.dn, ca='CA' in master_data.services)) # now add service entries self._add_svc_entries(master_data.dn, master_data.services) # optionally add some attributes required e.g. by AD trust roles for entry_dn, attrs in master_data.attrs.items(): if 'member' in attrs: self._add_members( entry_dn, master_data.fqdn, attrs['member'] ) def teardown_data(self): for master_data in self.iter_domain_data(): # first remove the master entries and service containers self._remove_svc_master_entries(master_data.dn) # optionally clean up leftover attributes for entry_dn, attrs in master_data.attrs.items(): if 'member' in attrs: self._remove_members( entry_dn, master_data.fqdn, attrs['member'], ) # finally remove host entry self._del_host_entry(master_data.fqdn) self._restore_test_host_attrs() @pytest.fixture(scope='module') def mock_api(request): test_api = create_api(mode=None) test_api.bootstrap(in_server=True, ldap_uri=api.env.ldap_uri, confdir=paths.ETC_IPA) test_api.finalize() if not test_api.Backend.ldap2.isconnected(): test_api.Backend.ldap2.connect() def finalize(): test_api.Backend.ldap2.disconnect() request.addfinalizer(finalize) return test_api @pytest.fixture(scope='module') def mock_masters(request, mock_api): """ Populate the LDAP backend with test data """ if not api.Backend.rpcclient.isconnected(): api.Backend.rpcclient.connect() master_topo = MockMasterTopology(mock_api, master_data) def finalize(): master_topo.teardown_data() if api.Backend.rpcclient.isconnected(): api.Backend.rpcclient.disconnect() request.addfinalizer(finalize) master_topo.setup_data() return master_topo def enabled_role_iter(master_data): for m, data in master_data.items(): for role in data['expected_roles']['enabled']: yield m, role def provided_role_iter(master_data): for m, data in master_data.items(): yield m, data['expected_roles']['enabled'] def configured_role_iter(master_data): for m, data in master_data.items(): if 'configured' in data['expected_roles']: for role in data['expected_roles']['configured']: yield m, role def role_provider_iter(master_data): result = {} for m, data in master_data.items(): for role in data['expected_roles']['enabled']: if role not in result: result[role] = [] result[role].append(m) for role_name, masters in result.items(): yield role_name, masters def attribute_masters_iter(master_data): for m, data in master_data.items(): if 'expected_attributes' in data: for assoc_role, attr in data['expected_attributes'].items(): yield m, assoc_role, attr def dns_servers_iter(master_data): for m, data in master_data.items(): if "DNS server" in data['expected_roles']['enabled']: yield m @pytest.fixture(params=list(enabled_role_iter(master_data)), ids=['role: {}, master: {}, enabled'.format(role, m) for m, role in enabled_role_iter(master_data)]) def enabled_role(request): return request.param @pytest.fixture(params=list(provided_role_iter(master_data)), ids=["{}: {}".format(m, ', '.join(roles)) for m, roles in provided_role_iter(master_data)]) def provided_roles(request): return request.param @pytest.fixture(params=list(configured_role_iter(master_data)), ids=['role: {}, master: {}, configured'.format(role, m) for m, role in configured_role_iter(master_data)]) def configured_role(request): return request.param @pytest.fixture(params=list(role_provider_iter(master_data)), ids=['{} providers'.format(role_name) for role_name, _m in role_provider_iter(master_data)]) def role_providers(request): return request.param @pytest.fixture(params=list(attribute_masters_iter(master_data)), ids=['{} of {}: {}'.format(attr, role, m) for m, role, attr in attribute_masters_iter(master_data)]) def attribute_providers(request): return request.param @pytest.fixture(params=list(dns_servers_iter(master_data)), ids=list(dns_servers_iter(master_data))) def dns_server(request): return request.param class TestServerRoleStatusRetrieval: def retrieve_role(self, master, role, mock_api, mock_masters): fqdn = mock_masters.get_fqdn(master) return mock_api.Backend.serverroles.server_role_retrieve( server_server=fqdn, role_servrole=role) def find_role(self, role_name, mock_api, mock_masters, master=None): if master is not None: hostname = mock_masters.get_fqdn(master) else: hostname = None result = mock_api.Backend.serverroles.server_role_search( server_server=hostname, role_servrole=role_name) return [ r for r in result if r[u'server_server'] not in mock_masters.existing_masters] def get_enabled_roles_on_master(self, master, mock_api, mock_masters): fqdn = mock_masters.get_fqdn(master) result = mock_api.Backend.serverroles.server_role_search( server_server=fqdn, role_servrole=None, status=u'enabled' ) return sorted(set(r[u'role_servrole'] for r in result)) def get_masters_with_enabled_role(self, role_name, mock_api, mock_masters): result = mock_api.Backend.serverroles.server_role_search( server_server=None, role_servrole=role_name) return sorted( r[u'server_server'] for r in result if r[u'status'] == u'enabled' and r[u'server_server'] not in mock_masters.existing_masters) def test_listing_of_enabled_role( self, mock_api, mock_masters, enabled_role): master, role_name = enabled_role result = self.retrieve_role(master, role_name, mock_api, mock_masters) assert result[0][u'status'] == u'enabled' def test_listing_of_configured_role( self, mock_api, mock_masters, configured_role): master, role_name = configured_role result = self.retrieve_role(master, role_name, mock_api, mock_masters) assert result[0][u'status'] == u'configured' def test_role_providers( self, mock_api, mock_masters, role_providers): role_name, providers = role_providers expected_masters = sorted(mock_masters.get_fqdn(m) for m in providers) actual_masters = self.get_masters_with_enabled_role( role_name, mock_api, mock_masters) assert expected_masters == actual_masters def test_provided_roles_on_master( self, mock_api, mock_masters, provided_roles): master, expected_roles = provided_roles expected_roles.sort() actual_roles = self.get_enabled_roles_on_master( master, mock_api, mock_masters) assert expected_roles == actual_roles def test_unknown_role_status_raises_notfound(self, mock_api, mock_masters): unknown_role = 'IAP maestr' fqdn = mock_masters.get_fqdn('ca-dns-dnssec-keymaster-pkinit-server') with pytest.raises(errors.NotFound): mock_api.Backend.serverroles.server_role_retrieve( fqdn, unknown_role) def test_no_servrole_queries_all_roles_on_server(self, mock_api, mock_masters): master_name = 'ca-dns-dnssec-keymaster-pkinit-server' enabled_roles = master_data[master_name]['expected_roles']['enabled'] result = self.find_role(None, mock_api, mock_masters, master=master_name) for r in result: if r[u'role_servrole'] in enabled_roles: assert r[u'status'] == u'enabled' else: assert r[u'status'] == u'absent' def test_invalid_substring_search_returns_nothing(self, mock_api, mock_masters): invalid_substr = 'fwfgbb' assert (not self.find_role(invalid_substr, mock_api, mock_masters, 'ca-dns-dnssec-keymaster-pkinit-server')) class TestServerAttributes: def config_retrieve(self, assoc_role_name, mock_api): return mock_api.Backend.serverroles.config_retrieve( assoc_role_name) def config_update(self, mock_api, **attrs_values): return mock_api.Backend.serverroles.config_update(**attrs_values) def test_attribute_master(self, mock_api, mock_masters, attribute_providers): master, assoc_role, attr_name = attribute_providers fqdn = mock_masters.get_fqdn(master) actual_attr_masters = self.config_retrieve( assoc_role, mock_api)[attr_name] assert fqdn in actual_attr_masters def test_set_attribute_on_the_same_provider_raises_emptymodlist( self, mock_api, mock_masters): attr_name = "ca_renewal_master_server" role_name = "CA server" existing_renewal_master = self.config_retrieve( role_name, mock_api)[attr_name] with pytest.raises(errors.EmptyModlist): self.config_update( mock_api, **{attr_name: existing_renewal_master}) def test_set_attribute_on_master_without_assoc_role_raises_validationerror( self, mock_api, mock_masters): attr_name = "ca_renewal_master_server" non_ca_fqdn = mock_masters.get_fqdn('trust-controller-dns') with pytest.raises(errors.ValidationError): self.config_update(mock_api, **{attr_name: non_ca_fqdn}) def test_set_unknown_attribute_on_master_raises_notfound( self, mock_api, mock_masters): attr_name = "ca_renuwal_maztah" fqdn = mock_masters.get_fqdn('trust-controller-ca') with pytest.raises(errors.NotFound): self.config_update(mock_api, **{attr_name: [fqdn]}) def test_set_ca_renewal_master_on_other_ca_and_back(self, mock_api, mock_masters): attr_name = "ca_renewal_master_server" role_name = "CA server" original_renewal_master = self.config_retrieve( role_name, mock_api)[attr_name] other_ca_server = mock_masters.get_fqdn('trust-controller-ca') for host in (other_ca_server, original_renewal_master): self.config_update(mock_api, **{attr_name: host}) assert ( self.config_retrieve(role_name, mock_api)[attr_name] == host)
23,457
Python
.py
602
27.58804
79
0.552836
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,349
test_installer.py
freeipa_freeipa/ipatests/test_ipaserver/test_install/test_installer.py
# # Copyright (C) 2018 FreeIPA Contributors. See COPYING for license # from __future__ import absolute_import from abc import ABCMeta, abstractmethod from collections import namedtuple import itertools import pytest from ipatests.util import assert_equal from ipaserver.install.ipa_replica_install import ReplicaInstall Keyval = namedtuple('Keyval', ['option', 'value']) class InstallerTestBase(metaclass=ABCMeta): OPTS_DICT = {} # don't allow creating classes with tested_cls unspecified @property @abstractmethod def tested_cls(self): return None @pytest.fixture(autouse=True, scope="class") def installer_setup(self, request): """Initializes the tested class so that it can be used later on """ cls = request.cls cls.tested_cls.make_parser() assert \ getattr(cls.tested_cls, 'option_parser', False), \ ("Unable to generate option parser for {}" .format(cls.tested_cls.__name__)) cls._populate_opts_dict() @classmethod def _populate_opts_dict(cls): """Populate the class-owned OPTS_DICT with available options """ if not getattr(cls.tested_cls, 'option_parser', False): raise RuntimeError("You need to create the parser of the tested " "class first.") # add all options from the option groups for opt_group in cls.tested_cls.option_parser.option_groups: for opt in opt_group.option_list: cls.OPTS_DICT[opt.dest] = opt._short_opts + opt._long_opts # add options outside groups for opt in cls.tested_cls.option_parser.option_list: cls.OPTS_DICT[opt.dest] = opt._short_opts + opt._long_opts def parse_cli_args(self, args): """Parses the CLI-like arguments and returns them in python objects :param args: A string representing the CLI arguments :returns: dictionary and a list of parsed options and arguments """ return self.tested_cls.option_parser.parse_args(args.split()) def get_installer_instance(self, args): """Get instance of the configuring class """ parsed_opts = self.parse_cli_args(args) cls = self.tested_cls.get_command_class(*parsed_opts) command_instance = cls(*parsed_opts) return command_instance.init_configurator() def combine_options(self, *args): return ' '.join(args) def all_option_permutations(self, *key_val): """Gets all short-option/long-option permutations :param key_val: Keyval tuples specifying the options to grab from OPTS_DICT along with the values to assign to them :returns: list or list of lists of all permutations """ if len(key_val) == 0: return [] elif len(key_val) == 1: val = key_val[0].value return ['{opt} {val}'.format(opt=opt, val=val) for opt in self.OPTS_DICT[key_val[0].option]] permutation_lists = [self.OPTS_DICT[k.option] for k in key_val] permutation = itertools.product(*permutation_lists) ret = [] for p in permutation: opt_vals = [] for i, kv in enumerate(key_val): opt_vals.append( '{opt} {val}'.format( opt=p[i], val=kv.value)) ret.append(opt_vals) return ret class TestReplicaInstaller(InstallerTestBase): tested_cls = ReplicaInstall PASSWORD = Keyval("auto_password", "c3ca2246bcf309d1b636581ce429da3522a8aec4") ADMIN_PASSWORD = Keyval("admin_password", "milan_je_buh123") PRINCIPAL = Keyval("principal", "ubercool_guy") def test_password_option_DL1(self): # OTP enrollment for passwd_opt in self.all_option_permutations(self.PASSWORD): ic = self.get_installer_instance(passwd_opt) assert_equal(ic.password, self.PASSWORD.value) # admin principal enrollment for adm_password_opt in ( self.all_option_permutations(self.ADMIN_PASSWORD) ): ic = self.get_installer_instance(adm_password_opt) assert_equal(ic.password, None) assert_equal(ic.admin_password, self.ADMIN_PASSWORD.value) # if principal is set, we interpret --password as that principal's for passwd_opt, principal_opt in ( self.all_option_permutations(self.PASSWORD, self.PRINCIPAL) ): ic = self.get_installer_instance( self.combine_options(passwd_opt, principal_opt)) assert_equal(ic.password, None) assert_equal(ic.principal, self.PRINCIPAL.value) assert_equal(ic.admin_password, self.PASSWORD.value) # if principal is set, we interpret --password as that principal's # unless admin-password is also specified, in which case it's once # again an OTP for adm_password_opt, passwd_opt, principal_opt in ( self.all_option_permutations( self.ADMIN_PASSWORD, self.PASSWORD, self.PRINCIPAL) ): ic = self.get_installer_instance( self.combine_options( adm_password_opt, passwd_opt, principal_opt)) assert_equal(ic.password, self.PASSWORD.value) assert_equal(ic.principal, self.PRINCIPAL.value) assert_equal(ic.admin_password, self.ADMIN_PASSWORD.value)
5,545
Python
.py
121
35.917355
77
0.633803
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,350
test_adtrustinstance.py
freeipa_freeipa/ipatests/test_ipaserver/test_install/test_adtrustinstance.py
# Authors: # Sumit Bose <sbose@redhat.com> # # Copyright (C) 2011 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test `adtrustinstance` """ import pytest import six from ipaserver.install import adtrustinstance if six.PY3: unicode = str @pytest.mark.tier0 class test_adtrustinstance: """ Test `adtrustinstance`. """ def test_make_netbios_name(self): s = adtrustinstance.make_netbios_name("ABCDEF") assert s == 'ABCDEF' and isinstance(s, str) s = adtrustinstance.make_netbios_name(U"ABCDEF") assert s == 'ABCDEF' and isinstance(s, unicode) s = adtrustinstance.make_netbios_name("abcdef") assert s == 'ABCDEF' s = adtrustinstance.make_netbios_name("abc.def") assert s == 'ABC' s = adtrustinstance.make_netbios_name("abcdefghijklmnopqr.def") assert s == 'ABCDEFGHIJKLMNO' s = adtrustinstance.make_netbios_name("A!$%B&/()C=?+*D") assert s == 'ABCD' s = adtrustinstance.make_netbios_name("!$%&/()=?+*") assert not s def test_check_netbios_name(self): assert adtrustinstance.check_netbios_name("ABCDEF") assert not adtrustinstance.check_netbios_name("abcdef") assert adtrustinstance.check_netbios_name("ABCDE12345ABCDE") assert not adtrustinstance.check_netbios_name("ABCDE12345ABCDE1") assert not adtrustinstance.check_netbios_name("") assert adtrustinstance.check_netbios_name(U"ABCDEF") assert not adtrustinstance.check_netbios_name(U"abcdef") assert adtrustinstance.check_netbios_name(U"ABCDE12345ABCDE") assert not adtrustinstance.check_netbios_name(U"ABCDE12345ABCDE1")
2,343
Python
.py
56
37
74
0.711842
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,351
test_installutils.py
freeipa_freeipa/ipatests/test_ipaserver/test_install/test_installutils.py
# # Copyright (C) 2017 FreeIPA Contributors. See COPYING for license # from __future__ import absolute_import import binascii import os import psutil import re import subprocess import textwrap import pytest from unittest.mock import patch, mock_open from ipaplatform.paths import paths from ipapython import ipautil from ipapython.admintool import ScriptError from ipaserver.install import installutils from ipaserver.install import ipa_backup from ipaserver.install import ipa_restore GPG_GENKEY = textwrap.dedent(""" %echo Generating a standard key Key-Type: RSA Key-Length: 2048 Name-Real: IPA Backup Name-Comment: IPA Backup Name-Email: root@example.com Expire-Date: 0 Passphrase: {passphrase} %commit %echo done """) @pytest.fixture def gpgkey(request, tempdir): passphrase = "Secret123" gnupghome = os.path.join(tempdir, "gnupg") os.makedirs(gnupghome, 0o700) # provide clean env for gpg test env = os.environ.copy() orig_gnupghome = env.get('GNUPGHOME') env['GNUPGHOME'] = gnupghome env['LC_ALL'] = 'C.UTF-8' env['LANGUAGE'] = 'C' devnull = open(os.devnull, 'w') # allow passing passphrases to agent with open(os.path.join(gnupghome, "gpg-agent.conf"), 'w') as f: f.write("verbose\n") f.write("allow-preset-passphrase\n") # daemonize agent (detach from the console and run in the background) subprocess.run( [paths.SYSTEMD_RUN, '--service-type=forking', '--property', 'SELinuxContext=system_u:system_r:initrc_t:s0', '--setenv=GNUPGHOME={}'.format(gnupghome), '--setenv=LC_ALL=C.UTF-8', '--setenv=LANGUAGE=C', '--unit=gpg-agent', '/bin/bash', '-c', ' '.join([paths.GPG_AGENT, '--daemon', '--batch'])], check=True, env=env, ) def fin(): subprocess.run( [paths.SYSTEMCTL, 'stop', 'gpg-agent'], check=True, env=env, ) if orig_gnupghome is not None: os.environ['GNUPGHOME'] = orig_gnupghome else: os.environ.pop('GNUPGHOME', None) request.addfinalizer(fin) # create public / private key pair keygen = os.path.join(gnupghome, 'keygen') with open(keygen, 'w') as f: f.write(GPG_GENKEY.format(passphrase=passphrase)) subprocess.check_call( [paths.GPG2, '--batch', '--gen-key', keygen], env=env, stdout=devnull, stderr=devnull ) # get keygrip of private key out = subprocess.check_output( [paths.GPG2, "--list-secret-keys", "--with-keygrip"], env=env, stderr=subprocess.STDOUT ) mo = re.search("Keygrip = ([A-Z0-9]{32,})", out.decode('utf-8')) if mo is None: raise ValueError(out.decode('utf-8')) keygrip = mo.group(1) # unlock private key cmd = "PRESET_PASSPHRASE {} -1 {}".format( keygrip, binascii.hexlify(passphrase.encode('utf-8')).decode('utf-8') ) subprocess.check_call( [paths.GPG_CONNECT_AGENT, cmd, "/bye"], env=env, stdout=devnull, stderr=devnull ) # set env for the rest of the progress os.environ['GNUPGHOME'] = gnupghome def test_gpg_encrypt(tempdir): src = os.path.join(tempdir, "data.txt") encrypted = os.path.join(tempdir, "data.gpg") decrypted = os.path.join(tempdir, "data.out") passwd = 'Secret123' payload = 'Dummy text\n' with open(src, 'w') as f: f.write(payload) installutils.encrypt_file(src, encrypted, password=passwd) assert os.path.isfile(encrypted) installutils.decrypt_file(encrypted, decrypted, password=passwd) assert os.path.isfile(decrypted) with open(decrypted) as f: assert f.read() == payload with pytest.raises(ipautil.CalledProcessError): installutils.decrypt_file(encrypted, decrypted, password='invalid') def test_gpg_asymmetric(tempdir, gpgkey): src = os.path.join(tempdir, "asymmetric.txt") encrypted = src + ".gpg" payload = 'Dummy text\n' with open(src, 'w') as f: f.write(payload) ipa_backup.encrypt_file(src, remove_original=True) assert os.path.isfile(encrypted) assert not os.path.exists(src) ipa_restore.decrypt_file(tempdir, encrypted) assert os.path.isfile(src) with open(src) as f: assert f.read() == payload @pytest.mark.parametrize( "platform, expected", [ ("fedora", "fedora"), ("fedora_container", "fedora"), ("fedora_containers", "fedora_containers"), ("fedoracontainer", "fedoracontainer"), ("rhel", "rhel"), ("rhel_container", "rhel"), ] ) def test_get_current_platform(monkeypatch, platform, expected): monkeypatch.setattr(installutils.ipaplatform, "NAME", platform) assert installutils.get_current_platform() == expected # The mock_exists in the following tests mocks that the cgroups # files exist even in non-containers. The values are provided by # mock_open_multi. @patch('ipaserver.install.installutils.in_container') @patch('os.path.exists') def test_in_container_no_cgroup(mock_exists, mock_in_container): """ In a container in a container without cgroups, can't detect RAM """ mock_in_container.return_value = True mock_exists.side_effect = [False, False] with pytest.raises(ScriptError): installutils.check_available_memory(False) def mock_open_multi(*contents): """Mock opening multiple files. For our purposes the first read is limit, second is usage. Note: this overrides *all* opens so if you use pdb then you will need to extend the list by 2. """ mock_files = [ mock_open(read_data=content).return_value for content in contents ] mock_multi = mock_open() mock_multi.side_effect = mock_files return mock_multi RAM_OK = str(1800 * 1000 * 1000) RAM_CA_USED = str(150 * 1000 * 1000) RAM_MOSTLY_USED = str(1500 * 1000 * 1000) RAM_NOT_OK = str(10 * 1000 * 1000) @patch('ipaserver.install.installutils.in_container') @patch('builtins.open', mock_open_multi(RAM_NOT_OK, "0")) @patch('os.path.exists') def test_cgroup_v1_insufficient_ram(mock_exists, mock_in_container): """In a container with insufficient RAM and zero used""" mock_in_container.return_value = True mock_exists.side_effect = [True, True] with pytest.raises(ScriptError): installutils.check_available_memory(True) @patch('ipaserver.install.installutils.in_container') @patch('builtins.open', mock_open_multi(RAM_OK, RAM_CA_USED)) @patch('os.path.exists') def test_cgroup_v1_ram_ok_no_ca(mock_exists, mock_in_container): """In a container with just enough RAM to install w/o a CA""" mock_in_container.return_value = True mock_exists.side_effect = [True, True] installutils.check_available_memory(False) @patch('ipaserver.install.installutils.in_container') @patch('builtins.open', mock_open_multi(RAM_OK, RAM_MOSTLY_USED)) @patch('os.path.exists') def test_cgroup_v1_insufficient_ram_with_ca(mock_exists, mock_in_container): """In a container and just miss the minimum RAM required""" mock_in_container.return_value = True mock_exists.side_effect = [True, True] with pytest.raises(ScriptError): installutils.check_available_memory(True) @patch('ipaserver.install.installutils.in_container') @patch('builtins.open', mock_open_multi(RAM_NOT_OK, "0")) @patch('os.path.exists') def test_cgroup_v2_insufficient_ram(mock_exists, mock_in_container): """In a container with insufficient RAM and zero used""" mock_in_container.return_value = True mock_exists.side_effect = [False, True, True] with pytest.raises(ScriptError): installutils.check_available_memory(True) @patch('ipaserver.install.installutils.in_container') @patch('builtins.open', mock_open_multi(RAM_OK, RAM_CA_USED)) @patch('os.path.exists') def test_cgroup_v2_ram_ok_no_ca(mock_exists, mock_in_container): """In a container with just enough RAM to install w/o a CA""" mock_in_container.return_value = True mock_exists.side_effect = [False, True, True] installutils.check_available_memory(False) @patch('ipaserver.install.installutils.in_container') @patch('builtins.open', mock_open_multi(RAM_OK, RAM_MOSTLY_USED)) @patch('os.path.exists') def test_cgroup_v2_insufficient_ram_with_ca(mock_exists, mock_in_container): """In a container and just miss the minimum RAM required""" mock_in_container.return_value = True mock_exists.side_effect = [False, True, True] with pytest.raises(ScriptError): installutils.check_available_memory(True) @patch('ipaserver.install.installutils.in_container') @patch('builtins.open', mock_open_multi('max', RAM_MOSTLY_USED)) @patch('os.path.exists') @patch('psutil.virtual_memory') def test_cgroup_v2_no_limit_ok(mock_psutil, mock_exists, mock_in_container): """In a container and just miss the minimum RAM required""" mock_in_container.return_value = True fake_memory = psutil._pslinux.svmem fake_memory.available = int(RAM_OK) mock_psutil.return_value = fake_memory mock_exists.side_effect = [False, True, True] installutils.check_available_memory(True) @patch('ipaserver.install.installutils.in_container') @patch('builtins.open', mock_open_multi('max', RAM_MOSTLY_USED)) @patch('os.path.exists') @patch('psutil.virtual_memory') def test_cgroup_v2_no_limit_not_ok(mock_psutil, mock_exists, mock_in_container): """In a container and just miss the minimum RAM required""" mock_in_container.return_value = True fake_memory = psutil._pslinux.svmem fake_memory.available = int(RAM_NOT_OK) mock_psutil.return_value = fake_memory mock_exists.side_effect = [False, True, True] with pytest.raises(ScriptError): installutils.check_available_memory(True) @patch('ipaserver.install.installutils.in_container') @patch('psutil.virtual_memory') def test_bare_insufficient_ram_with_ca(mock_psutil, mock_in_container): """Not a container and insufficient RAM""" mock_in_container.return_value = False fake_memory = psutil._pslinux.svmem fake_memory.available = int(RAM_NOT_OK) mock_psutil.return_value = fake_memory with pytest.raises(ScriptError): installutils.check_available_memory(True) @patch('ipaserver.install.installutils.in_container') @patch('psutil.virtual_memory') def test_bare_ram_ok(mock_psutil, mock_in_container): """Not a container and sufficient RAM""" mock_in_container.return_value = False fake_memory = psutil._pslinux.svmem fake_memory.available = int(RAM_OK) mock_psutil.return_value = fake_memory installutils.check_available_memory(True)
10,689
Python
.py
265
35.50566
80
0.702144
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,352
test_service.py
freeipa_freeipa/ipatests/test_ipaserver/test_install/test_service.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Tests for the `ipaserver.service` module. """ from ipaserver.install import service import pytest @pytest.mark.tier0 def test_format_seconds(): assert service.format_seconds(0) == '0 seconds' assert service.format_seconds(1) == '1 second' assert service.format_seconds(2) == '2 seconds' assert service.format_seconds(11) == '11 seconds' assert service.format_seconds(60) == '1 minute' assert service.format_seconds(61) == '1 minute 1 second' assert service.format_seconds(62) == '1 minute 2 seconds' assert service.format_seconds(120) == '2 minutes' assert service.format_seconds(125) == '2 minutes 5 seconds'
1,427
Python
.py
34
39.794118
71
0.74874
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,353
generate-matrix.py
freeipa_freeipa/ipatests/azure/scripts/generate-matrix.py
import argparse import copy import pprint import json import yaml parser = argparse.ArgumentParser(description='Generate Azure jobs matrix.') parser.add_argument('azure_template', help='path to Azure template') parser.add_argument('max_azure_env_jobs', type=int, help='maximum number of Docker envs within VM') args = parser.parse_args() with open(args.azure_template) as f: data = yaml.safe_load(f) default_resources = data["default_resources"] matrix_jobs = {} for vm in data['vms']: vm_jobs = vm['vm_jobs'] jobs = {} job_name = '' for job_id, vm_job in enumerate(vm_jobs, 1): if not job_name: job_name = f'{vm_job["container_job"]}_{job_id}' jobs[f'ipa_tests_env_name_{job_id}'] = vm_job['container_job'] jobs[f'ipa_tests_to_run_{job_id}'] = ' '.join(vm_job['tests']) jobs[f'ipa_tests_to_ignore_{job_id}'] = ' '.join( vm_job.get('ignore', '')) jobs[f'ipa_tests_type_{job_id}'] = vm_job.get( 'type', 'integration') jobs[f'ipa_tests_args_{job_id}'] = vm_job.get('args', '') jobs[f'ipa_tests_network_internal_{job_id}'] = vm_job.get( 'isolated', 'false' ) containers = vm_job.get('containers') cont_resources = copy.deepcopy(default_resources) replicas = 0 clients = 0 if containers: replicas = containers.get('replicas', 0) clients = containers.get('clients', 0) resources = containers.get("resources") if resources: for cont in ["server", "replica", "client"]: cont_resources[cont].update( resources.get(cont, {}) ) jobs[f'ipa_tests_replicas_{job_id}'] = replicas jobs[f'ipa_tests_clients_{job_id}'] = clients for cont in ["server", "replica", "client"]: for res in ["mem_limit", "memswap_limit"]: key = f"ipa_tests_{cont}_{res}_{job_id}" jobs[key] = cont_resources[cont][res] if len(vm_jobs) > args.max_azure_env_jobs: raise ValueError( f"Number of defined jobs:{len(vm_jobs)} within VM:'{job_name}'" f" is greater than limit:{args.max_azure_env_jobs}") job_name = f'{job_name}_to_{len(vm_jobs)}' if job_name in matrix_jobs: raise ValueError(f"Environment names should be unique:{job_name}") matrix_jobs[job_name] = jobs pprint.pprint(matrix_jobs) print("##vso[task.setVariable variable=matrix;isOutput=true]" + json.dumps(matrix_jobs))
2,797
Python
.py
61
34.081967
79
0.550826
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,354
gating_compare.py
freeipa_freeipa/ipatests/azure/scripts/gating_compare.py
import yaml PRCI_GATING = "ipatests/prci_definitions/gating.yaml" AZURE_GATING = "ipatests/azure/azure_definitions/gating.yml" prci_tests = [] azure_tests = [] SKIP_IN_AZURE_LIST = [ "test_integration/test_authselect.py", # requires external DNS ] EXTRA_AZURE_LIST = [] with open(PRCI_GATING) as f: prci_gating = yaml.safe_load(f) for task in prci_gating["jobs"].values(): job = task["job"] if job["class"] == "RunPytest": prci_tests.extend(job["args"]["test_suite"].split()) prci_tests.sort() with open(AZURE_GATING) as f: azure_gating = yaml.safe_load(f) for vm_jobs in azure_gating["vms"]: for job in vm_jobs["vm_jobs"]: azure_tests.extend(job["tests"]) azure_tests.sort() missing_in_azure = set(prci_tests) - set(azure_tests + SKIP_IN_AZURE_LIST) if missing_in_azure: print( "##vso[task.logissue type=warning]" "Missing gating tests in Azure Pipelines, compared to PR-CI", missing_in_azure, ) extra_in_azure = set(azure_tests) - set(prci_tests + EXTRA_AZURE_LIST) if extra_in_azure: print( "##vso[task.logissue type=warning]" "Extra gating tests in Azure Pipelines, compared to PR-CI", extra_in_azure, )
1,259
Python
.py
36
29.805556
74
0.657049
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,355
setup_containers.py
freeipa_freeipa/ipatests/azure/scripts/setup_containers.py
from __future__ import annotations from datetime import datetime import logging import os import subprocess import time import docker from jinja2 import Template from typing import NamedTuple, TYPE_CHECKING if TYPE_CHECKING: from typing import List, Tuple, Union, Dict logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") IPA_TESTS_ENV_WORKING_DIR = os.environ.get("IPA_TESTS_ENV_WORKING_DIR") IPA_TESTS_ENV_NAME = os.environ.get("IPA_TESTS_ENV_NAME") IPA_TESTS_ENV_ID = os.environ.get("IPA_TESTS_ENV_ID", "1") IPA_TESTS_CLIENTS = int(os.environ.get("IPA_TESTS_CLIENTS", 0)) IPA_TESTS_REPLICAS = int(os.environ.get("IPA_TESTS_REPLICAS", 0)) IPA_TESTS_DOMAIN = os.environ.get("IPA_TESTS_DOMAIN", "ipa.test") IPA_SSH_PRIV_KEY = os.environ.get("IPA_SSH_PRIV_KEY", "/root/.ssh/id_rsa") IPA_DNS_FORWARDER = os.environ.get("IPA_DNS_FORWARDER", "8.8.8.8") IPA_NETWORK = os.environ.get("IPA_NETWORK", "ipanet") IPA_CONTROLLER_TYPE = os.environ.get("IPA_CONTROLLER_TYPE", "master") IPA_TEST_CONFIG_TEMPLATE = os.environ.get( "IPA_TEST_CONFIG_TEMPLATE", "./templates/ipa-test-config-template.yaml" ) IPA_TESTS_ENV_DIR = os.path.join(IPA_TESTS_ENV_WORKING_DIR, IPA_TESTS_ENV_NAME) IPA_TEST_CONFIG = "ipa-test-config.yaml" class ExecRunReturn(NamedTuple): exit_code: int output: Tuple[bytes, bytes] class Container: """ Represents Docker container """ def __init__(self, name, hostname, network): self.name = name self.hostname = hostname self.network = network self.dclient = docker.from_env() @property def ip(self): """ ipv4 address of container """ if not hasattr(self, "_ip"): dcont = self.dclient.containers.get(self.name) self._ip = dcont.attrs["NetworkSettings"]["Networks"][ self.network ]["IPAddress"] return self._ip @property def ipv6(self): """ ipv6 address of container """ if not hasattr(self, "_ipv6"): dcont = self.dclient.containers.get(self.name) self._ipv6 = dcont.attrs["NetworkSettings"]["Networks"][ self.network ]["GlobalIPv6Address"] return self._ipv6 def execute( self, args: Union[str, List[str]], raiseonerr: bool = True, env: Union[Dict[str, str], List[str], None] = None, ) -> ExecRunReturn: """ Exec an arbitrary command within container """ dcont = self.dclient.containers.get(self.name) logging.info("%s: run: %s", dcont.name, args) result: ExecRunReturn = dcont.exec_run( args, demux=True, environment=env ) if result.output[0] is not None: logging.info("%s: %s", dcont.name, result.output[0]) logging.info("%s: result: %s", dcont.name, result.exit_code) if result.exit_code and raiseonerr: logging.error("stderr: %s", result.output[1].decode()) raise subprocess.CalledProcessError( result.exit_code, args, result.output[1] ) return result class ContainersGroup: """ Represents group of Docker containers """ HOME_SSH_DIR = "/root/.ssh" def __init__( self, role, nameservers=[IPA_DNS_FORWARDER], scale=1, prefix=IPA_TESTS_ENV_ID, domain=IPA_TESTS_DOMAIN, ): self.role = role self.scale = scale self.prefix = prefix self.nameservers = nameservers self.domain = domain # initialize containers self.containers = [ Container( name=f"{self.prefix}-{self.role}-{c}", hostname=f"{self.role}{c}.{self.domain}", network=f"{IPA_TESTS_ENV_ID}_{IPA_NETWORK}", ) for c in range(1, self.scale + 1) ] def execute_all(self, args, env=None): """ Sequentially exec an arbitrary command within every container of group """ results = [] for cont in self.containers: results.append(cont.execute(args, env=env)) return results def ips(self): return [cont.ip for cont in self.containers] def umount_docker_resource(self, path): """ Umount resource by its path """ cmd = ["/bin/umount", path] self.execute_all(cmd) cmd = [ "/bin/chmod", "a-x", path, ] self.execute_all(cmd) def add_ssh_pubkey(self, key): """ Add ssh public key into every container of group """ auth_keys = os.path.join(self.HOME_SSH_DIR, "authorized_keys") cmd = [ "/bin/bash", "-c", ( f"mkdir {self.HOME_SSH_DIR} " f"; chmod 0700 {self.HOME_SSH_DIR} " f"&& touch {auth_keys} " f"&& chmod 0600 {auth_keys} " f"&& echo {key} >> {auth_keys}" ), ] self.execute_all(cmd) def setup_hosts(self): """ Overwrite hosts within every container of group """ self.umount_docker_resource("/etc/hosts") for cont in self.containers: hosts = "\n".join( [ "127.0.0.1 localhost", "::1 localhost", f"{cont.ip} {cont.hostname}", f"{cont.ipv6} {cont.hostname}", ] ) cmd = ["/bin/bash", "-c", f"echo -e '{hosts}' > /etc/hosts"] cont.execute(cmd) def setup_hostname(self): self.umount_docker_resource("/etc/hostname") for cont in self.containers: cmd = [ "/bin/bash", "-c", f"echo -e '{cont.hostname}' > /etc/hostname", ] cont.execute(cmd) cmd = ["hostnamectl", "set-hostname", cont.hostname] # default timeout (25s) maybe not enough cont.execute(cmd, env={"SYSTEMD_BUS_TIMEOUT": "50"}) def setup_resolvconf(self): """ Overwrite resolv conf within every container of group """ self.umount_docker_resource("/etc/resolv.conf") nameservers = "\n".join( [f"nameserver {ns}" for ns in self.nameservers] ) cmd = [ "/bin/bash", "-c", f"echo -e '{nameservers}' > /etc/resolv.conf", ] self.execute_all(cmd) def ignore_service_in_container(self, service): """ Amend systemd service configuration to be ignored in a container """ service_dir = os.path.join( "/etc/systemd/system", "{}.service.d".format(service) ) override_file = os.path.join(service_dir, "ipa-override.conf") cmds = [ "/bin/bash", "-c", ( f"mkdir -p {service_dir};" f"echo '[Unit]' > {override_file};" f"echo 'ConditionVirtualization=!container' >> {override_file}" ), ] self.execute_all(cmds) def setup_container_overrides(self): """ Set services known to not work in containers to be ignored """ for service in [ "nis-domainname", ]: self.ignore_service_in_container(service) self.execute_all(["systemctl", "daemon-reload"]) def wait_systemd_target_reached( self, target_name: str = "default.target", startup_timeout: int = 180, ) -> None: RETRY_DELAY_SEC = 5 cmd = ["systemctl", "is-active", "--quiet", target_name] for cont in self.containers: reached = False start = datetime.today() while not reached: result = cont.execute(cmd, raiseonerr=False) reached = result.exit_code == 0 if not reached: elapsed = int((datetime.today() - start).total_seconds()) if elapsed > startup_timeout: raise RuntimeError( f"Systemd's target '{target_name}' wasn't reached " f"in container: '{cont.name}'\n" f"stderr: {result.output[1].decode('utf-8')}" ) time.sleep(RETRY_DELAY_SEC) class Controller(Container): """ Represents Controller, which manages groups of containers groups """ def __init__(self, contr_type=IPA_CONTROLLER_TYPE): self.containers_groups = [] self.contr_type = contr_type def append(self, containers_group): self.containers_groups.append(containers_group) def wait_systemd_target_reached( self, target_name: str = "multi-user.target" ) -> None: for containers_group in self.containers_groups: containers_group.wait_systemd_target_reached(target_name) def setup_ssh(self): """ Generate ssh key pair and copy public part to all containers """ cmd = ["rm", "-f", IPA_SSH_PRIV_KEY] self.execute(cmd) cmd = [ "ssh-keygen", "-q", "-f", IPA_SSH_PRIV_KEY, "-t", "rsa", "-m", "PEM", "-N", "", ] self.execute(cmd) cmd = ["/bin/bash", "-c", "cat {}.pub".format(IPA_SSH_PRIV_KEY)] key = self.execute(cmd).output[0].decode().rstrip() for containers_group in self.containers_groups: containers_group.add_ssh_pubkey(key) @property def master_container(self): if not hasattr(self, "_master_container"): master_containers_group = None for containers_group in self.containers_groups: if containers_group.role == "master": master_containers_group = containers_group break if master_containers_group is None: raise ValueError( "There must be container group with master role" ) # assume the only master self._master_container = master_containers_group.containers[0] return self._master_container def execute(self, args, env=None): """ Execute a command on controller (either master or local machine) """ if self.contr_type != "master": proc = subprocess.run(args, check=True, capture_output=True) return [proc.stdout.decode().rstrip().strip("'")] return self.master_container.execute(args, env=env) def setup_hosts(self): """ Overwrite Docker's hosts """ hosts = [] for containers_group in self.containers_groups: containers_group.setup_hosts() # prevent duplication of master entries if ( self.contr_type == "master" and containers_group.role == "master" ): continue for container in containers_group.containers: hosts.append(f"{container.ip} {container.hostname}") hosts.append(f"{container.ipv6} {container.hostname}") cmd = [ "/bin/bash", "-c", "echo -e '{hosts}' >> /etc/hosts".format(hosts="\n".join(hosts)), ] self.execute(cmd) def setup_hostname(self): """ Overwrite Docker's hostname """ for containers_group in self.containers_groups: containers_group.setup_hostname() def setup_resolvconf(self): """ Overwrite Docker's embedded DNS ns """ for containers_group in self.containers_groups: containers_group.setup_resolvconf() def generate_ipa_test_config(self, config): with open(IPA_TEST_CONFIG_TEMPLATE, "r") as f: template = Template(f.read(), trim_blocks=True, lstrip_blocks=True) logging.info(template.render(config)) with open(os.path.join(IPA_TESTS_ENV_DIR, IPA_TEST_CONFIG), "w") as f: f.write(template.render(config)) def setup_container_overrides(self): """ Override services known to not work in containers """ for containers_group in self.containers_groups: containers_group.setup_container_overrides() controller = Controller() master = ContainersGroup(role="master") # assume the only master master_ips = [master.containers[0].ip, master.containers[0].ipv6] clients = ContainersGroup( role="client", scale=IPA_TESTS_CLIENTS, nameservers=master_ips ) replicas = ContainersGroup( role="replica", scale=IPA_TESTS_REPLICAS, nameservers=master_ips ) controller.append(master) controller.append(clients) controller.append(replicas) controller.wait_systemd_target_reached() controller.setup_ssh() controller.setup_hosts() controller.setup_hostname() controller.setup_resolvconf() controller.setup_container_overrides() config = { "dns_forwarder": IPA_DNS_FORWARDER, "ssh_private_key": IPA_SSH_PRIV_KEY, "domain_name": IPA_TESTS_DOMAIN, "master": master.ips(), "replicas": replicas.ips(), "clients": clients.ips(), } controller.generate_ipa_test_config(config)
13,501
Python
.py
375
26.432
79
0.570805
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,356
test_authenticators.py
freeipa_freeipa/ipatests/test_custodia/test_authenticators.py
# Copyright (C) 2016 Custodia Project Contributors - see LICENSE file import configparser import grp import pwd from ipaserver.custodia.httpd import authenticators CONFIG = u""" [auth:cred_default] [auth:cred_int] uid = 0 gid = 0 [auth:cred_root] uid = root gid = root [auth:cred_user] uid = root [auth:cred_group] gid = root [auth:cred_other_int] uid = ${DEFAULT:other_uid} gid = ${DEFAULT:other_gid} [auth:cred_other_name] uid = ${DEFAULT:other_username} gid = ${DEFAULT:other_groupname} [auth:header_default] [auth:header_other] header = GSSAPI value = [auth:header_value] header = GSSAPI value = admin [auth:header_values] header = GSSAPI value = admin user [auth:header_commaspace] header = GSSAPI value = admin, user, space user [auth:header_comma] header = GSSAPI value = admin,user,other user """ class TestAuthenticators: @classmethod def setup_class(cls): # Tests are depending on two existing and distinct users and groups. # We chose 'root' with uid/gid 0 and 'nobody', because both exist on # all relevant platforms. Tests use a mocked request so they run # under any user. cls.user = user = pwd.getpwnam('nobody') cls.group = group = grp.getgrgid(user.pw_gid) cls.parser = configparser.ConfigParser( interpolation=configparser.ExtendedInterpolation(), defaults={ 'other_uid': str(user.pw_uid), 'other_username': user.pw_name, 'other_gid': str(group.gr_gid), 'other_groupname': group.gr_name, } ) cls.parser.read_string(CONFIG) def assertCredMatch(self, cred, uid, gid): request = {'creds': {'uid': uid, 'gid': gid}, 'client_id': 'tests'} assert cred.handle(request) def assertCredMismatch(self, cred, uid, gid): request = {'creds': {'uid': uid, 'gid': gid}, 'client_id': 'tests'} assert not cred.handle(request) def assertHeaderMatch(self, header, key, value, client_id): request = {'headers': {key: value}, 'client_id': client_id} assert header.handle(request) is True def assertHeaderMismatch(self, header, key, value, client_id): request = {'headers': {key: value}, 'client_id': client_id} assert header.handle(request) is False def test_cred(self): parser = self.parser cred = authenticators.SimpleCredsAuth(parser, 'auth:cred_default') assert cred.uid == -1 assert cred.gid == -1 self.assertCredMismatch(cred, 0, 0) cred = authenticators.SimpleCredsAuth(parser, 'auth:cred_int') assert cred.uid == 0 assert cred.gid == 0 self.assertCredMatch(cred, 0, 0) self.assertCredMatch(cred, 0, self.group.gr_gid) self.assertCredMatch(cred, self.user.pw_uid, 0) self.assertCredMismatch(cred, self.user.pw_uid, self.group.gr_gid) cred = authenticators.SimpleCredsAuth(parser, 'auth:cred_root') assert cred.uid == 0 assert cred.gid == 0 cred = authenticators.SimpleCredsAuth(parser, 'auth:cred_user') assert cred.uid == 0 assert cred.gid == -1 self.assertCredMatch(cred, 0, 0) self.assertCredMismatch(cred, self.user.pw_uid, 0) cred = authenticators.SimpleCredsAuth(parser, 'auth:cred_group') assert cred.uid == -1 assert cred.gid == 0 self.assertCredMatch(cred, 0, 0) self.assertCredMismatch(cred, 0, self.group.gr_gid) cred = authenticators.SimpleCredsAuth(parser, 'auth:cred_other_int') assert cred.uid != 0 assert cred.uid == self.user.pw_uid assert cred.gid != 0 assert cred.gid == self.group.gr_gid cred = authenticators.SimpleCredsAuth(parser, 'auth:cred_other_name') assert cred.uid != 0 assert cred.uid == self.user.pw_uid assert cred.gid != 0 assert cred.gid == self.group.gr_gid def test_header(self): parser = self.parser gssapi = 'GSSAPI' hdr = authenticators.SimpleHeaderAuth(parser, 'auth:header_default') assert hdr.header == 'REMOTE_USER' assert hdr.value is None self.assertHeaderMatch(hdr, 'REMOTE_USER', None, 0) hdr = authenticators.SimpleHeaderAuth(parser, 'auth:header_other') assert hdr.header == 'GSSAPI' assert hdr.value is None self.assertHeaderMatch(hdr, gssapi, None, 0) hdr = authenticators.SimpleHeaderAuth(parser, 'auth:header_value') assert hdr.header == 'GSSAPI' assert hdr.value == {'admin'} self.assertHeaderMatch(hdr, gssapi, 'admin', 0) self.assertHeaderMismatch(hdr, gssapi, 'invalid_rule', 0) # pylint: disable=R0133 hdr = authenticators.SimpleHeaderAuth(parser, 'auth:header_values') assert hdr.header == 'GSSAPI' assert hdr.value, {'admin' == 'user'} hdr = authenticators.SimpleHeaderAuth(parser, 'auth:header_commaspace') assert hdr.value, {'admin', 'user' == 'space user'} hdr = authenticators.SimpleHeaderAuth(parser, 'auth:header_comma') assert hdr.value, {'admin', 'user' == 'other user'} # pylint: enable=R0133
5,333
Python
.py
134
32.328358
77
0.640852
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,357
test_plugins.py
freeipa_freeipa/ipatests/test_custodia/test_plugins.py
# Copyright (C) 2016 Custodia Project Contributors - see LICENSE file import pkg_resources import pytest from ipaserver.custodia.plugin import ( CSStore, HTTPAuthenticator, HTTPAuthorizer ) class TestCustodiaPlugins: project_name = 'ipaserver.custodia' def get_entry_points(self, group): eps = [] for e in pkg_resources.iter_entry_points(group): if e.dist.project_name != self.project_name: # only interested in our own entry points continue eps.append(e) return eps def assert_ep(self, ep, basecls): try: # backwards compatibility with old setuptools if hasattr(ep, "resolve"): cls = ep.resolve() else: cls = ep.load(require=False) except Exception as e: # pylint: disable=broad-except pytest.fail("Failed to load %r: %r" % (ep, e)) if not issubclass(cls, basecls): pytest.fail("%r is not a subclass of %r" % (cls, basecls)) def test_authenticators(self): for ep in self.get_entry_points('custodia.authenticators'): self.assert_ep(ep, HTTPAuthenticator) def test_authorizers(self): for ep in self.get_entry_points('custodia.authorizers'): self.assert_ep(ep, HTTPAuthorizer) def test_stores(self): for ep in self.get_entry_points('custodia.stores'): self.assert_ep(ep, CSStore)
1,472
Python
.py
36
31.777778
70
0.626751
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,358
test_server.py
freeipa_freeipa/ipatests/test_custodia/test_server.py
# Copyright (C) 2017 Custodia Project Contributors - see LICENSE file import os import socket import pytest from ipaserver.custodia.server.args import parse_args from ipaserver.custodia.server.config import parse_config HERE = os.path.dirname(os.path.abspath(__file__)) EMPTY_CONF = os.path.join(HERE, 'empty.conf') @pytest.fixture() def args(): return parse_args([EMPTY_CONF]) @pytest.fixture() def args_instance(): return parse_args(['--instance=testing', '--debug', EMPTY_CONF]) def test_args(args): assert not args.debug assert args.instance is None assert args.configfile.name == EMPTY_CONF def test_args_instance(args_instance): assert args_instance.debug assert args_instance.instance == 'testing' assert args_instance.configfile.name == EMPTY_CONF def test_parse_config(args): parser, config = parse_config(args) assert parser.has_section(u'/') assert parser.get(u'/', u'handler') == u'Root' assert config == { 'auditlog': u'/var/log/custodia/audit.log', 'authenticators': {}, 'authorizers': {}, 'confdpattern': EMPTY_CONF + u'.d/*.conf', 'configdir': HERE, 'configfiles': [ EMPTY_CONF, EMPTY_CONF + u'.d/root.conf' ], 'consumers': {}, 'debug': False, 'hostname': socket.gethostname(), 'instance': u'', 'libdir': u'/var/lib/custodia', 'logdir': u'/var/log/custodia', 'makedirs': False, 'rundir': u'/var/run/custodia', 'server_url': 'http+unix://%2Fvar%2Frun%2Fcustodia%2Fcustodia.sock/', 'socketdir': u'/var/run/custodia', 'stores': {}, 'tls_verify_client': False, 'umask': 23 } def test_parse_config_instance(args_instance): parser, config = parse_config(args_instance) assert parser.has_section(u'/') assert parser.get(u'/', u'handler') == u'Root' assert config == { 'auditlog': u'/var/log/custodia/testing/audit.log', 'authenticators': {}, 'authorizers': {}, 'confdpattern': EMPTY_CONF + u'.d/*.conf', 'configdir': HERE, 'configfiles': [ EMPTY_CONF, EMPTY_CONF + u'.d/root.conf' ], 'consumers': {}, 'debug': True, 'hostname': socket.gethostname(), 'instance': u'testing', 'libdir': u'/var/lib/custodia/testing', 'logdir': u'/var/log/custodia/testing', 'makedirs': False, 'rundir': u'/var/run/custodia/testing', 'server_url': 'http+unix://%2Fvar%2Frun%2Fcustodia%2Ftesting.sock/', 'socketdir': u'/var/run/custodia', 'stores': {}, 'tls_verify_client': False, 'umask': 23 }
2,742
Python
.py
78
28.269231
77
0.608696
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,359
test_ipagetkeytab.py
freeipa_freeipa/ipatests/test_cmdline/test_ipagetkeytab.py
# Authors: # Rob Crittenden <rcritten@redhat.com> # # Copyright (C) 2010 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test `ipa-getkeytab` """ from __future__ import absolute_import import os import shutil import tempfile import gssapi import pytest from ipapython.ipautil import private_ccache from ipalib import api, errors from ipalib.request import context from ipaplatform.paths import paths from ipapython import ipautil, ipaldap from ipaserver.plugins.ldap2 import ldap2 from ipatests.test_cmdline.cmdline import cmdline_test from ipatests.test_xmlrpc.tracker import host_plugin, service_plugin from ipatests.test_xmlrpc.xmlrpc_test import fuzzy_digits, add_oc from contextlib import contextmanager @contextmanager def use_keytab(principal, keytab): with private_ccache() as ccache_file: old_principal = getattr(context, 'principal', None) try: name = gssapi.Name(principal, gssapi.NameType.kerberos_principal) store = {'ccache': ccache_file, 'client_keytab': keytab} gssapi.Credentials(name=name, usage='initiate', store=store) conn = ldap2(api) conn.connect(ccache=ccache_file, autobind=ipaldap.AUTOBIND_DISABLED) yield conn conn.disconnect() except gssapi.exceptions.GSSError as e: raise Exception('Unable to bind to LDAP. Error initializing ' 'principal %s in %s: %s' % (principal, keytab, str(e))) finally: setattr(context, 'principal', old_principal) @pytest.fixture(scope='class') def test_host(request): host_tracker = host_plugin.HostTracker(u'test-host') return host_tracker.make_fixture(request) @pytest.fixture(scope='class') def test_service(request, test_host, keytab_retrieval_setup): service_tracker = service_plugin.ServiceTracker(u'srv', test_host.name) test_host.ensure_exists() return service_tracker.make_fixture(request) @pytest.mark.needs_ipaapi class KeytabRetrievalTest(cmdline_test): """ Base class for keytab retrieval tests """ command = "ipa-getkeytab" keytabname = None @pytest.fixture(autouse=True, scope="class") def keytab_retrieval_setup(self, request, cmdline_setup): cls = request.cls keytabfd, keytabname = tempfile.mkstemp() os.close(keytabfd) os.unlink(keytabname) cls.keytabname = keytabname def fin(): try: os.unlink(cls.keytabname) except OSError: pass request.addfinalizer(fin) def run_ipagetkeytab(self, service_principal, args=tuple(), raiseonerr=False, stdin=None): new_args = [self.command, "-p", service_principal, "-k", self.keytabname] if not args: new_args.extend(['-s', api.env.host]) else: new_args.extend(list(args)) return ipautil.run( new_args, stdin=stdin, raiseonerr=raiseonerr, capture_error=True) def assert_success(self, *args, **kwargs): result = self.run_ipagetkeytab(*args, **kwargs) expected = 'Keytab successfully retrieved and stored in: %s\n' % ( self.keytabname) assert expected in result.error_output, ( 'Success message not in output:\n%s' % result.error_output) def assert_failure(self, retcode, message, *args, **kwargs): result = self.run_ipagetkeytab(*args, **kwargs) err = result.error_output assert message in err rc = result.returncode assert rc == retcode @pytest.mark.tier0 class test_ipagetkeytab(KeytabRetrievalTest): """ Test `ipa-getkeytab`. """ command = "ipa-getkeytab" keytabname = None def test_1_run(self, test_service): """ Create a keytab with `ipa-getkeytab` for a non-existent service. """ test_service.ensure_missing() result = self.run_ipagetkeytab(test_service.name) err = result.error_output assert 'Failed to parse result: PrincipalName not found.\n' in err, err rc = result.returncode assert rc > 0, rc def test_2_run(self, test_service): """ Create a keytab with `ipa-getkeytab` for an existing service. """ test_service.ensure_exists() self.assert_success(test_service.name, raiseonerr=True) def test_3_use(self, test_service): """ Try to use the service keytab. """ with use_keytab(test_service.name, self.keytabname) as conn: assert conn.can_read(test_service.dn, 'objectclass') is True assert getattr(context, 'principal') == test_service.name def test_4_disable(self, test_service): """ Disable a kerberos principal """ retrieve_cmd = test_service.make_retrieve_command() result = retrieve_cmd() # Verify that it has a principal key assert result[u'result'][u'has_keytab'] # Disable it disable_cmd = test_service.make_disable_command() disable_cmd() # Verify that it looks disabled result = retrieve_cmd() assert not result[u'result'][u'has_keytab'] def test_5_use_disabled(self, test_service): """ Try to use the disabled keytab """ try: with use_keytab(test_service.name, self.keytabname) as conn: assert conn.can_read(test_service.dn, 'objectclass') is True assert getattr(context, 'principal') == test_service.name except Exception as errmsg: assert('Unable to bind to LDAP. Error initializing principal' in str(errmsg)) def test_6_quiet_mode(self, test_service): """ Try to use quiet mode """ test_service.ensure_exists() # getkeytab without quiet mode option enabled result = self.run_ipagetkeytab(test_service.name) err = result.error_output.split("\n")[0] assert err == f"Keytab successfully retrieved and stored in:" \ f" {self.keytabname}" assert result.returncode == 0 # getkeytab with quiet mode option enabled result1 = self.run_ipagetkeytab(test_service.name, args=tuple("-q")) assert result1.returncode == 0 def test_7_server_name_check(self, test_service): """ Try to use -s for server name """ test_service.ensure_exists() self.assert_success(test_service.name, args=["-s", api.env.host]) def test_8_keytab_encryption_check(self, test_service): """ Try to use -e for different types of encryption check """ encryptes_list = [ "aes256-cts-hmac-sha1-96", "aes128-cts-hmac-sha256-128", ] self.assert_success( test_service.name, args=["-e", ",".join(encryptes_list)] ) def test_dangling_symlink(self, test_service): # see https://pagure.io/freeipa/issue/4607 test_service.ensure_exists() fd, symlink_target = tempfile.mkstemp() os.close(fd) os.unlink(symlink_target) # create dangling symlink os.symlink(self.keytabname, symlink_target) try: self.assert_success(test_service.name, raiseonerr=True) assert os.path.isfile(symlink_target) assert os.path.samefile(self.keytabname, symlink_target) finally: os.unlink(symlink_target) def retrieve_dm_password(): dmpw_file = os.path.join(api.env.dot_ipa, '.dmpw') if not os.path.isfile(dmpw_file): raise errors.NotFound(reason='{} file required ' 'for this test'.format(dmpw_file)) with open(dmpw_file, 'r') as f: dm_password = f.read().strip() return dm_password class TestBindMethods(KeytabRetrievalTest): """ Class that tests '-c'/'-H'/'-Y' flags """ dm_password = None ca_cert = None @pytest.fixture(autouse=True, scope="class") def bindmethods_setup(self, request, keytab_retrieval_setup): cls = request.cls try: cls.dm_password = retrieve_dm_password() except errors.NotFound as e: pytest.skip(e.args) tempfd, temp_ca_cert = tempfile.mkstemp() os.close(tempfd) shutil.copy(os.path.join(paths.IPA_CA_CRT), temp_ca_cert) cls.ca_cert = temp_ca_cert def fin(): try: os.unlink(cls.ca_cert) except OSError: pass request.addfinalizer(fin) def check_ldapi(self): if not api.env.ldap_uri.startswith('ldapi://'): pytest.skip("LDAP URI not pointing to LDAPI socket") def test_retrieval_with_dm_creds(self, test_service): test_service.ensure_exists() self.assert_success( test_service.name, args=[ '-D', "cn=Directory Manager", '-w', self.dm_password, '-s', api.env.host]) def test_retrieval_using_plain_ldap(self, test_service): test_service.ensure_exists() ldap_uri = 'ldap://{}'.format(api.env.host) self.assert_success( test_service.name, args=[ '-D', "cn=Directory Manager", '-w', self.dm_password, '-H', ldap_uri]) @pytest.mark.skipif(os.geteuid() != 0, reason="Must have root privileges to run this test") def test_retrieval_using_ldapi_external(self, test_service): test_service.ensure_exists() self.check_ldapi() self.assert_success( test_service.name, args=[ '-Y', 'EXTERNAL', '-H', api.env.ldap_uri]) def test_retrieval_using_ldap_gssapi(self, test_service): test_service.ensure_exists() self.check_ldapi() self.assert_success( test_service.name, args=[ '-Y', 'GSSAPI', '-H', api.env.ldap_uri]) def test_retrieval_using_ldaps_ca_cert(self, test_service): test_service.ensure_exists() self.assert_success( test_service.name, args=[ '-D', "cn=Directory Manager", '-w', self.dm_password, '-H', 'ldaps://{}'.format(api.env.host), '--cacert', self.ca_cert]) def test_ldap_uri_server_raises_error(self, test_service): test_service.ensure_exists() self.assert_failure( 2, "Cannot specify server and LDAP uri simultaneously", test_service.name, args=[ '-H', 'ldaps://{}'.format(api.env.host), '-s', api.env.host], raiseonerr=False) def test_invalid_mech_raises_error(self, test_service): test_service.ensure_exists() self.assert_failure( 2, "Invalid SASL bind mechanism", test_service.name, args=[ '-H', 'ldaps://{}'.format(api.env.host), '-Y', 'BOGUS'], raiseonerr=False) def test_mech_bind_dn_raises_error(self, test_service): test_service.ensure_exists() self.assert_failure( 2, "Cannot specify both SASL mechanism and bind DN simultaneously", test_service.name, args=[ '-D', "cn=Directory Manager", '-w', self.dm_password, '-H', 'ldaps://{}'.format(api.env.host), '-Y', 'EXTERNAL'], raiseonerr=False) class SMBServiceTracker(service_plugin.ServiceTracker): def __init__(self, name, host_fqdn, options=None): super(SMBServiceTracker, self).__init__(name, host_fqdn, options=options) # Create SMB service principal that has POSIX attributes to allow # generating SID and adding proper objectclasses self.create_keys |= {u'uidnumber', u'gidnumber'} self.options[u'addattr'] = [ u'objectclass=ipaIDObject', u'uidNumber=-1', u'gidNumber=-1'] def track_create(self, **options): super(SMBServiceTracker, self).track_create(**options) self.attrs[u'uidnumber'] = [fuzzy_digits] self.attrs[u'gidnumber'] = [fuzzy_digits] self.attrs[u'objectclass'].append(u'ipaIDObject') @pytest.fixture(scope='class') def test_smb_svc(request, test_host, smb_service_setup): service_tracker = SMBServiceTracker(u'cifs', test_host.name) test_host.ensure_exists() return service_tracker.make_fixture(request) @pytest.mark.tier0 @pytest.mark.skipif(u'ipantuserattrs' not in add_oc([], u'ipantuserattrs'), reason="Must have trust support enabled for this test") class test_smb_service(KeytabRetrievalTest): """ Test `ipa-getkeytab` for retrieving explicit enctypes """ command = "ipa-getkeytab" dm_password = None keytabname = None @pytest.fixture(autouse=True, scope="class") def smb_service_setup(self, request, keytab_retrieval_setup): cls = request.cls try: cls.dm_password = retrieve_dm_password() except errors.NotFound as e: pytest.skip(e.args) def test_create(self, test_smb_svc): """ Create a keytab with `ipa-getkeytab` for an existing service. """ test_smb_svc.ensure_exists() # Request a keytab with explicit encryption types enctypes = ['aes128-cts-hmac-sha1-96', 'aes256-cts-hmac-sha1-96', 'arcfour-hmac'] args = ['-e', ','.join(enctypes), '-s', api.env.host] self.assert_success(test_smb_svc.name, args=args, raiseonerr=True) def test_use(self, test_smb_svc): """ Try to use the service keytab to regenerate ipaNTHash value """ # Step 1. Extend objectclass to allow ipaNTHash attribute # We cannot verify write access to objectclass with use_keytab(test_smb_svc.name, self.keytabname) as conn: entry = conn.get_entry(test_smb_svc.dn, ['objectclass']) entry['objectclass'].extend(['ipaNTUserAttrs']) try: conn.update_entry(entry) except errors.ACIError: assert False, ('No correct ACI to the allow ipaNTUserAttrs ' 'for SMB service') # Step 2. With ipaNTUserAttrs in place, we can ask to regenerate # ipaNTHash value. We can also verify it is possible to write to # ipaNTHash attribute while being an SMB service with use_keytab(test_smb_svc.name, self.keytabname) as conn: assert conn.can_write(test_smb_svc.dn, 'ipaNTHash') is True entry = conn.get_entry(test_smb_svc.dn, ['ipaNTHash']) entry['ipanthash'] = b'MagicRegen' try: conn.update_entry(entry) except errors.ACIError: assert False, "No correct ACI to the ipaNTHash for SMB service" except errors.EmptyResult: assert False, "No arcfour-hmac in Kerberos keys" except errors.DatabaseError: # Most likely ipaNTHash already existed -- we either get # OPERATIONS_ERROR or UNWILLING_TO_PERFORM, both map to # the same DatabaseError class. assert False, "LDAP Entry corruption after generation" # Update succeeded, now we have either MagicRegen (broken) or # a real NT hash in the entry. However, we can only retrieve it as # a cn=Directory Manager. When bind_dn is None, ldap2.connect() wil # default to cn=Directory Manager. conn = ldap2(api) conn.connect(bind_dn=None, bind_pw=self.dm_password, autobind=ipaldap.AUTOBIND_DISABLED) entry = conn.retrieve(test_smb_svc.dn, ['ipaNTHash']) ipanthash = entry.single_value.get('ipanthash') conn.disconnect() assert ipanthash != b'MagicRegen', 'LDBM backend entry corruption'
17,064
Python
.py
412
31.735437
89
0.611638
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,360
test_cli.py
freeipa_freeipa/ipatests/test_cmdline/test_cli.py
import contextlib import os from io import StringIO import shlex import subprocess import sys import tempfile import six from ipatests import util from ipatests.test_ipalib.test_x509 import goodcert_headers from ipalib import api, errors import pytest if six.PY3: unicode = str TEST_ZONE = u'zoneadd.%(domain)s' % api.env HERE = os.path.abspath(os.path.dirname(__file__)) BASE_DIR = os.path.abspath(os.path.join(HERE, os.pardir, os.pardir)) @pytest.mark.tier0 @pytest.mark.needs_ipaapi class TestCLIParsing: """Tests that commandlines are correctly parsed to Command keyword args """ def check_command(self, commandline, expected_command_name, **kw_expected): argv = shlex.split(commandline) executioner = api.Backend.cli cmd = executioner.get_command(argv) kw_got = executioner.parse(cmd, argv[1:]) kw_got = executioner.process_keyword_arguments(cmd, kw_got) util.assert_deepequal(expected_command_name, cmd.name, 'Command name') util.assert_deepequal(kw_expected, kw_got) def run_command(self, command_name, **kw): """Run a command on the server""" if not api.Backend.rpcclient.isconnected(): api.Backend.rpcclient.connect() try: api.Command[command_name](**kw) except errors.NetworkError: pytest.skip('%r: Server not available: %r' % (self.__module__, api.env.xmlrpc_uri)) @contextlib.contextmanager def fake_stdin(self, string_in): """Context manager that temporarily replaces stdin to read a string""" old_stdin = sys.stdin sys.stdin = StringIO(string_in) yield sys.stdin = old_stdin def test_ping(self): self.check_command('ping', 'ping') def test_plugins(self): self.check_command('plugins', 'plugins') def test_user_show(self): self.check_command('user-show admin', 'user_show', uid=u'admin') def test_user_show_underscore(self): self.check_command('user_show admin', 'user_show', uid=u'admin') def test_group_add(self): self.check_command( 'group-add tgroup1 --desc="Test group"', 'group_add', cn=u'tgroup1', description=u'Test group', ) def test_sudocmdgroup_add_member(self): # Test CSV splitting is not done self.check_command( # The following is as it would appear on the command line: r'sudocmdgroup-add-member tcmdgroup1 --sudocmds=ab,c --sudocmds=d', 'sudocmdgroup_add_member', cn=u'tcmdgroup1', sudocmd=[u'ab,c', u'd'], ) def test_group_add_nonposix(self): self.check_command( 'group-add tgroup1 --desc="Test group" --nonposix', 'group_add', cn=u'tgroup1', description=u'Test group', nonposix=True, ) def test_group_add_gid(self): self.check_command( 'group-add tgroup1 --desc="Test group" --gid=1234', 'group_add', cn=u'tgroup1', description=u'Test group', gidnumber=u'1234', ) def test_group_add_interactive(self): with self.fake_stdin('Test group\n'): self.check_command( 'group-add tgroup1', 'group_add', cn=u'tgroup1', ) def test_dnsrecord_add(self): self.check_command( 'dnsrecord-add %s ns --a-rec=1.2.3.4' % TEST_ZONE, 'dnsrecord_add', dnszoneidnsname=TEST_ZONE, idnsname=u'ns', arecord=u'1.2.3.4', ) def test_dnsrecord_del_all(self): try: self.run_command('dnszone_add', idnsname=TEST_ZONE) except errors.NotFound: pytest.skip('DNS is not configured') try: self.run_command('dnsrecord_add', dnszoneidnsname=TEST_ZONE, idnsname=u'ns', arecord=u'1.2.3.4', force=True) with self.fake_stdin('yes\n'): self.check_command( 'dnsrecord_del %s ns' % TEST_ZONE, 'dnsrecord_del', dnszoneidnsname=TEST_ZONE, idnsname=u'ns', del_all=True, ) with self.fake_stdin('YeS\n'): self.check_command( 'dnsrecord_del %s ns' % TEST_ZONE, 'dnsrecord_del', dnszoneidnsname=TEST_ZONE, idnsname=u'ns', del_all=True, ) finally: self.run_command('dnszone_del', idnsname=TEST_ZONE) def test_dnsrecord_del_one_by_one(self): try: self.run_command('dnszone_add', idnsname=TEST_ZONE) except errors.NotFound: pytest.skip('DNS is not configured') try: records = (u'1 1 E3B72BA346B90570EED94BE9334E34AA795CED23', u'2 1 FD2693C1EFFC11A8D2BE57229212A04B45663791') for record in records: self.run_command('dnsrecord_add', dnszoneidnsname=TEST_ZONE, idnsname=u'ns', sshfprecord=record) with self.fake_stdin('no\nyes\nyes\n'): self.check_command( 'dnsrecord_del %s ns' % TEST_ZONE, 'dnsrecord_del', dnszoneidnsname=TEST_ZONE, idnsname=u'ns', sshfprecord=records, ) finally: self.run_command('dnszone_del', idnsname=TEST_ZONE) def test_dnsrecord_add_ask_for_missing_fields(self): sshfp_parts = (1, 1, u'E3B72BA346B90570EED94BE9334E34AA795CED23') with self.fake_stdin('SSHFP\n%d\n%d\n%s' % sshfp_parts): self.check_command( 'dnsrecord-add %s sshfp' % TEST_ZONE, 'dnsrecord_add', dnszoneidnsname=TEST_ZONE, idnsname=u'sshfp', sshfp_part_fp_type=sshfp_parts[0], sshfp_part_algorithm=sshfp_parts[1], sshfp_part_fingerprint=sshfp_parts[2], ) # test with lowercase record type with self.fake_stdin('sshfp\n%d\n%d\n%s' % sshfp_parts): self.check_command( 'dnsrecord-add %s sshfp' % TEST_ZONE, 'dnsrecord_add', dnszoneidnsname=TEST_ZONE, idnsname=u'sshfp', sshfp_part_fp_type=sshfp_parts[0], sshfp_part_algorithm=sshfp_parts[1], sshfp_part_fingerprint=sshfp_parts[2], ) # NOTE: when a DNS record part is passed via command line, it is not # converted to its base type when transfered via wire with self.fake_stdin('%d\n%s' % (sshfp_parts[1], sshfp_parts[2])): self.check_command( 'dnsrecord-add %s sshfp --sshfp-algorithm=%d' % ( TEST_ZONE, sshfp_parts[0]), 'dnsrecord_add', dnszoneidnsname=TEST_ZONE, idnsname=u'sshfp', sshfp_part_fp_type=sshfp_parts[0], # passed via cmdline sshfp_part_algorithm=unicode(sshfp_parts[1]), sshfp_part_fingerprint=sshfp_parts[2], ) with self.fake_stdin(sshfp_parts[2]): self.check_command( 'dnsrecord-add %s sshfp --sshfp-algorithm=%d ' '--sshfp-fp-type=%d' % ( TEST_ZONE, sshfp_parts[0], sshfp_parts[1]), 'dnsrecord_add', dnszoneidnsname=TEST_ZONE, idnsname=u'sshfp', # passed via cmdline sshfp_part_fp_type=unicode(sshfp_parts[0]), # passed via cmdline sshfp_part_algorithm=unicode(sshfp_parts[1]), sshfp_part_fingerprint=sshfp_parts[2], ) def test_dnsrecord_del_comma(self): try: self.run_command( 'dnszone_add', idnsname=TEST_ZONE) except errors.NotFound: pytest.skip('DNS is not configured') try: self.run_command( 'dnsrecord_add', dnszoneidnsname=TEST_ZONE, idnsname=u'test', txtrecord=u'"A pretty little problem," said Holmes.') with self.fake_stdin('no\nyes\n'): self.check_command( 'dnsrecord_del %s test' % TEST_ZONE, 'dnsrecord_del', dnszoneidnsname=TEST_ZONE, idnsname=u'test', txtrecord=[u'"A pretty little problem," said Holmes.']) finally: self.run_command('dnszone_del', idnsname=TEST_ZONE) def test_idrange_add(self): """ Test idrange-add with interative prompt """ def test_with_interactive_input(): with self.fake_stdin('5\n500000\n'): self.check_command( 'idrange_add range1 --base-id=1 --range-size=1', 'idrange_add', cn=u'range1', ipabaseid=u'1', ipaidrangesize=u'1', ipabaserid=5, ipasecondarybaserid=500000, ) def test_with_command_line_options(): self.check_command( 'idrange_add range1 --base-id=1 --range-size=1 ' '--rid-base=5 --secondary-rid-base=500000', 'idrange_add', cn=u'range1', ipabaseid=u'1', ipaidrangesize=u'1', ipabaserid=u'5', ipasecondarybaserid=u'500000', ) def test_without_options(): self.check_command( 'idrange_add range1 --base-id=1 --range-size=1', 'idrange_add', cn=u'range1', ipabaseid=u'1', ipaidrangesize=u'1', ) adtrust_dn = 'cn=ADTRUST,cn=%s,cn=masters,cn=ipa,cn=etc,%s' % \ (api.env.host, api.env.basedn) adtrust_is_enabled = api.Command['adtrust_is_enabled']()['result'] mockldap = None if not adtrust_is_enabled: # ipa-adtrust-install not run - no need to pass rid-base # and secondary-rid-base test_without_options() # Create a mock service object to test against adtrust_add = dict( ipaconfigstring=b'enabledService', objectclass=[b'top', b'nsContainer', b'ipaConfigObject'] ) mockldap = util.MockLDAP() mockldap.add_entry(adtrust_dn, adtrust_add) # Pass rid-base and secondary-rid-base interactively test_with_interactive_input() # Pass rid-base and secondary-rid-base on the command-line test_with_command_line_options() if not adtrust_is_enabled: mockldap.del_entry(adtrust_dn) def test_certfind(self): with tempfile.NamedTemporaryFile() as f: f.write(goodcert_headers) f.flush() self.check_command( 'cert_find --file={}'.format(f.name), 'cert_find', file=goodcert_headers ) def test_cli_fsencoding(): # https://pagure.io/freeipa/issue/5887 env = { key: value for key, value in os.environ.items() if not key.startswith(('LC_', 'LANG')) } env['LC_ALL'] = 'C' env['PYTHONPATH'] = BASE_DIR # override confdir so test always fails and does not depend on an # existing installation. env['IPA_CONFDIR'] = '/' p = subprocess.Popen( [sys.executable, '-m', 'ipaclient', 'help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, ) out, err = p.communicate() assert p.returncode != 0, (out, err) if sys.version_info >= (3, 7): # Python 3.7+ has PEP 538: Legacy C Locale Coercion assert b'IPA client is not configured' in err, (out, err) else: # Python 3.6 does not support UTF-8 fs encoding with non-UTF LC assert b'System encoding must be UTF-8' in err, (out, err) IPA_NOT_CONFIGURED = b'IPA is not configured on this system' IPA_CLIENT_NOT_CONFIGURED = b'IPA client is not configured on this system' @pytest.mark.needs_ipaapi @pytest.mark.skipif( os.geteuid() != 0 or os.path.isfile('/etc/ipa/default.conf'), reason="Must have root privileges to run this test " "and IPA must not be installed") @pytest.mark.parametrize( "args, retcode, output, error", [ # Commands delivered by the client pkg (['ipa'], 1, None, IPA_CLIENT_NOT_CONFIGURED), (['ipa-certupdate'], 2, None, IPA_CLIENT_NOT_CONFIGURED), (['ipa-client-automount'], 2, IPA_CLIENT_NOT_CONFIGURED, None), # Commands delivered by the server pkg (['ipa-adtrust-install'], 2, None, IPA_NOT_CONFIGURED), (['ipa-advise'], 2, None, IPA_NOT_CONFIGURED), (['ipa-backup'], 2, None, IPA_NOT_CONFIGURED), (['ipa-cacert-manage'], 2, None, IPA_NOT_CONFIGURED), (['ipa-ca-install'], 1, None, b'IPA server is not configured on this system'), (['ipa-compat-manage'], 2, None, IPA_NOT_CONFIGURED), (['ipa-crlgen-manage'], 2, None, IPA_NOT_CONFIGURED), (['ipa-csreplica-manage'], 1, None, IPA_NOT_CONFIGURED), (['ipactl', 'status'], 4, None, b'IPA is not configured'), (['ipa-dns-install'], 2, None, IPA_NOT_CONFIGURED), (['ipa-kra-install'], 2, None, IPA_NOT_CONFIGURED), (['ipa-ldap-updater', '/usr/share/ipa/updates/05-pre_upgrade_plugins.update'], 2, None, IPA_NOT_CONFIGURED), (['ipa-managed-entries'], 2, None, IPA_NOT_CONFIGURED), (['ipa-pkinit-manage'], 2, None, IPA_NOT_CONFIGURED), (['ipa-replica-manage', 'list'], 1, IPA_NOT_CONFIGURED, None), (['ipa-server-certinstall'], 2, None, IPA_NOT_CONFIGURED), (['ipa-server-upgrade'], 2, None, IPA_NOT_CONFIGURED), (['ipa-winsync-migrate'], 1, None, IPA_NOT_CONFIGURED) ]) def test_command_ipa_not_installed(args, retcode, output, error): """ Test that the commands properly return that IPA client|server is not configured on this system. Launch the command specified in args. Check that the exit code is as expected and that stdout and stderr contain the expected strings. """ p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() assert retcode == p.returncode if output: assert output in out if error: assert error in err
14,916
Python
.py
362
29.759669
79
0.564171
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,361
cmdline.py
freeipa_freeipa/ipatests/test_cmdline/cmdline.py
# Authors: # Rob Crittenden <rcritten@redhat.com> # # Copyright (C) 2010 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Base class for all cmdline tests """ from __future__ import absolute_import import os import pytest import shutil from ipalib import api from ipalib import errors from ipaplatform.paths import paths from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test from ipaserver.plugins.ldap2 import ldap2 # See if our LDAP server is up and we can talk to it over GSSAPI try: conn = ldap2(api) conn.connect() conn.disconnect() server_available = True except errors.DatabaseError: server_available = False except Exception as e: server_available = False class cmdline_test(XMLRPC_test): """ Base class for all command-line tests """ # some reasonable default command command = paths.LS @pytest.fixture(autouse=True, scope="class") def cmdline_setup(self, request, xmlrpc_setup): # Find the executable in $PATH # This is neded because ipautil.run resets the PATH to # a system default. cls = request.cls original_command = cls.command if not os.path.isabs(cls.command): cls.command = shutil.which(cls.command) # raise an error if the command is missing even if the remote # server is not available. if not cls.command: raise AssertionError( 'Command %r not available' % original_command ) if not server_available: pytest.skip( 'Server not available: %r' % api.env.xmlrpc_uri )
2,277
Python
.py
65
30.461538
71
0.710526
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,362
test_schema.py
freeipa_freeipa/ipatests/test_cmdline/test_schema.py
# # Copyright (C) 2021 FreeIPA Contributors see COPYING for license # import pytest import time from ipaclient.remote_plugins import ServerInfo class TestServerInfo(ServerInfo): """Simplified ServerInfo class with hardcoded values""" def __init__(self, fingerprint='deadbeef', hostname='ipa.example.test', force_check=False, language='en_US', version='2.0', expiration=None): self._force_check = force_check self._language = language self._now = time.time() self._dict = { 'fingerprint': fingerprint, 'expiration': expiration or time.time() + 3600, 'language': language, 'version': version, } def _read(self): """Running on test controller, this is a no-op""" def _write(self): """Running on test controller, this is a no-op""" @pytest.mark.tier0 class TestIPAServerInfo: """Test that ServerInfo detects changes in remote configuration""" def test_valid(self): server_info = TestServerInfo() assert server_info.is_valid() is True def test_force_check(self): server_info = TestServerInfo(force_check=True) assert server_info.is_valid() is False def test_language_change(self): server_info = TestServerInfo() assert server_info.is_valid() is True server_info._language = 'fr_FR' assert server_info.is_valid() is False server_info._language = 'en_US' def test_expired(self): server_info = TestServerInfo(expiration=time.time() + 2) assert server_info.is_valid() is True # skip past the expiration time server_info._now = time.time() + 5 assert server_info.is_valid() is False # set a new expiration time in the future server_info.update_validity(10) assert server_info.is_valid() is True # move to the future beyond expiration server_info._now = time.time() + 15 assert server_info.is_valid() is False def test_update_validity(self): server_info = TestServerInfo(expiration=time.time() + 1) # Expiration and time are one second off so the cache is ok assert server_info.is_valid() is True # Simulate time passing by server_info._now = time.time() + 2 # the validity should be updated because it is now expired server_info.update_validity(3600) # the cache is now valid for another hour assert server_info.is_valid() is True
2,551
Python
.py
61
33.786885
75
0.645892
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,363
__init__.py
freeipa_freeipa/ipatests/test_cmdline/__init__.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # import ipatests.util ipatests.util.check_ipaclient_unittests()
136
Python
.py
5
25.8
66
0.821705
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,364
test_help.py
freeipa_freeipa/ipatests/test_cmdline/test_help.py
# Authors: Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2012 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys import os from io import StringIO import shutil import errno import six from ipalib import api, errors from ipaserver.plugins.user import user_add import pytest if six.PY3: unicode = str pytestmark = pytest.mark.needs_ipaapi @pytest.mark.tier0 class CLITestContext: """Context manager that replaces stdout & stderr, and catches SystemExit Whatever was printed to the streams is available in ``stdout`` and ``stderr`` attrributes once the with statement finishes. When exception is given, asserts that exception is raised. The exception will be available in the ``exception`` attribute. """ def __init__(self, exception=None): self.exception = exception def __enter__(self): self.old_streams = sys.stdout, sys.stderr self.stdout_fileobj = sys.stdout = StringIO() self.stderr_fileobj = sys.stderr = StringIO() return self def __exit__(self, exc_type, exc_value, traceback): sys.stdout, sys.stderr = self.old_streams self.stdout = self.stdout_fileobj.getvalue() self.stderr = self.stderr_fileobj.getvalue() self.stdout_fileobj.close() self.stderr_fileobj.close() if self.exception: if not isinstance(exc_value, self.exception): return False self.exception = exc_value return True else: return None def test_ipa_help(): """Test that `ipa help` only writes to stdout""" with CLITestContext() as ctx: return_value = api.Backend.cli.run(['help']) assert return_value == 0 assert ctx.stderr == '' def test_ipa_help_without_cache(): """Test `ipa help` without schema cache""" cache_dir = os.path.expanduser('~/.cache/ipa/schema/') backup_dir = os.path.expanduser('~/.cache/ipa/schema.bak/') shutil.rmtree(backup_dir, ignore_errors=True) if os.path.isdir(cache_dir): os.rename(cache_dir, backup_dir) try: with CLITestContext() as ctx: return_value = api.Backend.cli.run(['help']) assert return_value == 0 assert ctx.stderr == '' finally: shutil.rmtree(cache_dir, ignore_errors=True) try: os.rename(backup_dir, cache_dir) except OSError as e: if e.errno != errno.ENOENT: raise def test_ipa_without_arguments(): """Test that `ipa` errors out, and prints the help to stderr""" with CLITestContext(exception=SystemExit) as ctx: api.Backend.cli.run([]) assert ctx.exception.code == 2 assert ctx.stdout == '' assert 'Error: Command not specified' in ctx.stderr with CLITestContext() as help_ctx: api.Backend.cli.run(['help']) assert help_ctx.stdout in ctx.stderr def test_bare_topic(): """Test that `ipa user` errors out, and prints the help to stderr This is because `user` is a topic, not a command, so `ipa user` doesn't match our usage string. The help should be accessed using `ipa help user`. """ with CLITestContext(exception=errors.CommandError) as ctx: api.Backend.cli.run(['user']) assert ctx.exception.name == 'user' assert ctx.stdout == '' with CLITestContext() as help_ctx: return_value = api.Backend.cli.run(['help', 'user']) assert return_value == 0 assert help_ctx.stdout in ctx.stderr def test_command_help(): """Test that `help user-add` & `user-add -h` are equivalent and contain doc """ with CLITestContext() as help_ctx: return_value = api.Backend.cli.run(['help', 'user-add']) assert return_value == 0 assert help_ctx.stderr == '' with CLITestContext(exception=SystemExit) as h_ctx: api.Backend.cli.run(['user-add', '-h']) assert h_ctx.exception.code == 0 assert h_ctx.stderr == '' assert h_ctx.stdout == help_ctx.stdout assert unicode(user_add.doc) in help_ctx.stdout def test_ambiguous_command_or_topic(): """Test that `help ping` & `ping -h` are NOT equivalent One is a topic, the other is a command """ with CLITestContext() as help_ctx: return_value = api.Backend.cli.run(['help', 'ping']) assert return_value == 0 assert help_ctx.stderr == '' with CLITestContext(exception=SystemExit) as h_ctx: api.Backend.cli.run(['ping', '-h']) assert h_ctx.exception.code == 0 assert h_ctx.stderr == '' assert h_ctx.stdout != help_ctx.stdout def test_multiline_description(): """Test that all of a multi-line command description appears in output """ # This assumes trust_add has multiline doc. Ensure it is so. assert '\n\n' in unicode(api.Command.trust_add.doc).strip() with CLITestContext(exception=SystemExit) as help_ctx: api.Backend.cli.run(['trust-add', '-h']) assert unicode(api.Command.trust_add.doc).strip() in help_ctx.stdout
5,658
Python
.py
140
34.842857
79
0.678949
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,365
test_console.py
freeipa_freeipa/ipatests/test_cmdline/test_console.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # import inspect import io import pydoc import pytest from ipalib import api @pytest.fixture() def api_obj(): if not api.Backend.rpcclient.isconnected(): api.Backend.rpcclient.connect() yield api @pytest.mark.tier0 @pytest.mark.needs_ipaapi class TestIPAConsole: def run_pydoc(self, plugin): s = io.StringIO() # help() calls pydoc.doc() with pager pydoc.doc(plugin, "Help %s", output=s) return s.getvalue() def test_dir(self, api_obj): assert "Command" in dir(api_obj) assert "group_add" in dir(api_obj.Command) def test_signature(self, api_obj): sig = api_obj.Command.group_add.__signature__ assert isinstance(sig, inspect.Signature) params = sig.parameters assert params['cn'].kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert params['cn'].annotation is str assert params['description'].kind is inspect.Parameter.KEYWORD_ONLY def test_help(self, api_obj): s = self.run_pydoc(api_obj.Command.group_add) # check for __signature__ in help() assert "group_add(cn: str, *, description: str = None," in s
1,236
Python
.py
35
29.714286
75
0.677852
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,366
test_cookie.py
freeipa_freeipa/ipatests/test_ipapython/test_cookie.py
# Authors: # John Dennis <jdennis@redhat.com> # # Copyright (C) 2012 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import datetime import email.utils from ipapython.cookie import Cookie from ipapython.ipautil import datetime_from_utctimestamp import pytest pytestmark = pytest.mark.tier0 class TestParse: def test_parse(self): # Empty string s = '' cookies = Cookie.parse(s) assert len(cookies) == 0 # Invalid single token s = 'color' with pytest.raises(ValueError): cookies = Cookie.parse(s) # Invalid single token that's keyword s = 'HttpOnly' with pytest.raises(ValueError): cookies = Cookie.parse(s) # Invalid key/value pair whose key is a keyword s = 'domain=example.com' with pytest.raises(ValueError): cookies = Cookie.parse(s) # 1 cookie with empty value s = 'color=' cookies = Cookie.parse(s) assert len(cookies) == 1 cookie = cookies[0] assert cookie.key == 'color' assert cookie.value == '' assert cookie.domain is None assert cookie.path is None assert cookie.max_age is None assert cookie.expires is None assert cookie.secure is None assert cookie.httponly is None assert str(cookie) == "color=" assert cookie.http_cookie() == "color=;" # 1 cookie with name/value s = 'color=blue' cookies = Cookie.parse(s) assert len(cookies) == 1 cookie = cookies[0] assert cookie.key == 'color' assert cookie.value == 'blue' assert cookie.domain is None assert cookie.path is None assert cookie.max_age is None assert cookie.expires is None assert cookie.secure is None assert cookie.httponly is None assert str(cookie) == "color=blue" assert cookie.http_cookie() == "color=blue;" # 1 cookie with whose value is quoted # Use "get by name" utility to extract specific cookie s = 'color="blue"' cookie = Cookie.get_named_cookie_from_string(s, 'color') assert cookie is not None, Cookie assert cookie.key == 'color' assert cookie.value == 'blue' assert cookie.domain is None assert cookie.path is None assert cookie.max_age is None assert cookie.expires is None assert cookie.secure is None assert cookie.httponly is None assert str(cookie) == "color=blue" assert cookie.http_cookie() == "color=blue;" # 1 cookie with name/value and domain, path attributes. # Change up the whitespace a bit. s = 'color =blue; domain= example.com ; path = /toplevel ' cookies = Cookie.parse(s) assert len(cookies) == 1 cookie = cookies[0] assert cookie.key == 'color' assert cookie.value == 'blue' assert cookie.domain == 'example.com' assert cookie.path == '/toplevel' assert cookie.max_age is None assert cookie.expires is None assert cookie.secure is None assert cookie.httponly is None assert str(cookie) == "color=blue; Domain=example.com; Path=/toplevel" assert cookie.http_cookie() == "color=blue;" # 2 cookies, various attributes s = 'color=blue; Max-Age=3600; temperature=hot; HttpOnly' cookies = Cookie.parse(s) assert len(cookies) == 2 cookie = cookies[0] assert cookie.key == 'color' assert cookie.value == 'blue' assert cookie.domain is None assert cookie.path is None assert cookie.max_age == 3600 assert cookie.expires is None assert cookie.secure is None assert cookie.httponly is None assert str(cookie) == "color=blue; Max-Age=3600" assert cookie.http_cookie() == "color=blue;" cookie = cookies[1] assert cookie.key == 'temperature' assert cookie.value == 'hot' assert cookie.domain is None assert cookie.path is None assert cookie.max_age is None assert cookie.expires is None assert cookie.secure is None assert cookie.httponly is True assert str(cookie) == "temperature=hot; HttpOnly" assert cookie.http_cookie() == "temperature=hot;" class TestExpires: @pytest.fixture(autouse=True) def expires_setup(self): # Force microseconds to zero because cookie timestamps only have second resolution self.now = datetime.datetime.now( tz=datetime.timezone.utc).replace(microsecond=0) self.now_timestamp = datetime_from_utctimestamp( self.now.utctimetuple(), units=1).timestamp() self.now_string = email.utils.formatdate(self.now_timestamp, usegmt=True) self.max_age = 3600 # 1 hour self.age_expiration = self.now + datetime.timedelta(seconds=self.max_age) self.age_timestamp = datetime_from_utctimestamp( self.age_expiration.utctimetuple(), units=1).timestamp() self.age_string = email.utils.formatdate(self.age_timestamp, usegmt=True) self.expires = self.now + datetime.timedelta(days=1) # 1 day self.expires_timestamp = datetime_from_utctimestamp( self.expires.utctimetuple(), units=1).timestamp() self.expires_string = email.utils.formatdate(self.expires_timestamp, usegmt=True) def test_expires(self): # 1 cookie with name/value and no Max-Age and no Expires s = 'color=blue;' cookies = Cookie.parse(s) assert len(cookies) == 1 cookie = cookies[0] # Force timestamp to known value cookie.timestamp = self.now assert cookie.key == 'color' assert cookie.value == 'blue' assert cookie.domain is None assert cookie.path is None assert cookie.max_age is None assert cookie.expires is None assert cookie.secure is None assert cookie.httponly is None assert str(cookie) == "color=blue" assert cookie.get_expiration() is None # Normalize assert cookie.normalize_expiration() is None assert cookie.max_age is None assert cookie.expires is None assert str(cookie) == "color=blue" # 1 cookie with name/value and Max-Age s = 'color=blue; max-age=%d' % (self.max_age) cookies = Cookie.parse(s) assert len(cookies) == 1 cookie = cookies[0] # Force timestamp to known value cookie.timestamp = self.now assert cookie.key == 'color' assert cookie.value == 'blue' assert cookie.domain is None assert cookie.path is None assert cookie.max_age == self.max_age assert cookie.expires is None assert cookie.secure is None assert cookie.httponly is None assert str(cookie) == "color=blue; Max-Age=%d" % (self.max_age) assert cookie.get_expiration() == self.age_expiration # Normalize assert cookie.normalize_expiration() == self.age_expiration assert cookie.max_age is None assert cookie.expires == self.age_expiration assert str(cookie) == "color=blue; Expires=%s" % (self.age_string) # 1 cookie with name/value and Expires s = 'color=blue; Expires=%s' % (self.expires_string) cookies = Cookie.parse(s) assert len(cookies) == 1 cookie = cookies[0] # Force timestamp to known value cookie.timestamp = self.now assert cookie.key == 'color' assert cookie.value == 'blue' assert cookie.domain is None assert cookie.path is None assert cookie.max_age is None assert cookie.expires == self.expires assert cookie.secure is None assert cookie.httponly is None assert str(cookie) == "color=blue; Expires=%s" % (self.expires_string) assert cookie.get_expiration() == self.expires # Normalize assert cookie.normalize_expiration() == self.expires assert cookie.max_age is None assert cookie.expires == self.expires assert str(cookie) == "color=blue; Expires=%s" % (self.expires_string) # 1 cookie with name/value witht both Max-Age and Expires, Max-Age takes precedence s = 'color=blue; Expires=%s; max-age=%d' % (self.expires_string, self.max_age) cookies = Cookie.parse(s) assert len(cookies) == 1 cookie = cookies[0] # Force timestamp to known value cookie.timestamp = self.now assert cookie.key == 'color' assert cookie.value == 'blue' assert cookie.domain is None assert cookie.path is None assert cookie.max_age == self.max_age assert cookie.expires == self.expires assert cookie.secure is None assert cookie.httponly is None expected = "color=blue; Max-Age={}; Expires={}".format( self.max_age, self.expires_string) assert str(cookie) == expected assert cookie.get_expiration() == self.age_expiration # Normalize assert cookie.normalize_expiration() == self.age_expiration assert cookie.max_age is None assert cookie.expires == self.age_expiration assert str(cookie) == "color=blue; Expires=%s" % (self.age_string) # Verify different types can be assigned to the timestamp and # expires attribute. cookie = Cookie('color', 'blue') cookie.timestamp = self.now assert cookie.timestamp == self.now cookie.timestamp = self.now_timestamp assert cookie.timestamp == self.now cookie.timestamp = self.now_string assert cookie.timestamp == self.now assert cookie.expires is None cookie.expires = self.expires assert cookie.expires == self.expires cookie.expires = self.expires_timestamp assert cookie.expires == self.expires cookie.expires = self.expires_string assert cookie.expires == self.expires class TestInvalidAttributes: def test_invalid(self): # Invalid Max-Age s = 'color=blue; Max-Age=over-the-hill' with pytest.raises(ValueError): Cookie.parse(s) cookie = Cookie('color', 'blue') with pytest.raises(ValueError): cookie.max_age = 'over-the-hill' # Invalid Expires s = 'color=blue; Expires=Sun, 06 Xxx 1994 08:49:37 GMT' with pytest.raises(ValueError): Cookie.parse(s) cookie = Cookie('color', 'blue') with pytest.raises(ValueError): cookie.expires = 'Sun, 06 Xxx 1994 08:49:37 GMT' class TestAttributes: def test_attributes(self): cookie = Cookie('color', 'blue') assert cookie.key == 'color' assert cookie.value == 'blue' assert cookie.domain is None assert cookie.path is None assert cookie.max_age is None assert cookie.expires is None assert cookie.secure is None assert cookie.httponly is None cookie.domain = 'example.com' assert cookie.domain == 'example.com' cookie.domain = None assert cookie.domain is None cookie.path = '/toplevel' assert cookie.path == '/toplevel' cookie.path = None assert cookie.path is None cookie.max_age = 400 assert cookie.max_age == 400 cookie.max_age = None assert cookie.max_age is None cookie.expires = 'Sun, 06 Nov 1994 08:49:37 GMT' assert cookie.expires == datetime.datetime( 1994, 11, 6, 8, 49, 37, tzinfo=datetime.timezone.utc) cookie.expires = None assert cookie.expires is None cookie.secure = True assert cookie.secure is True assert str(cookie) == "color=blue; Secure" cookie.secure = False assert cookie.secure is False assert str(cookie) == "color=blue" cookie.secure = None assert cookie.secure is None assert str(cookie) == "color=blue" cookie.httponly = True assert cookie.httponly is True assert str(cookie) == "color=blue; HttpOnly" cookie.httponly = False assert cookie.httponly is False assert str(cookie) == "color=blue" cookie.httponly = None assert cookie.httponly is None assert str(cookie) == "color=blue" class TestHTTPReturn: @pytest.fixture(autouse=True) def http_return_setup(self): self.url = 'http://www.foo.bar.com/one/two' def test_no_attributes(self): cookie = Cookie('color', 'blue') assert cookie.http_return_ok(self.url) def test_domain(self): cookie = Cookie('color', 'blue', domain='www.foo.bar.com') assert cookie.http_return_ok(self.url) cookie = Cookie('color', 'blue', domain='.foo.bar.com') assert cookie.http_return_ok(self.url) cookie = Cookie('color', 'blue', domain='.bar.com') assert cookie.http_return_ok(self.url) cookie = Cookie('color', 'blue', domain='bar.com') with pytest.raises(Cookie.URLMismatch): assert cookie.http_return_ok(self.url) cookie = Cookie('color', 'blue', domain='bogus.com') with pytest.raises(Cookie.URLMismatch): assert cookie.http_return_ok(self.url) cookie = Cookie('color', 'blue', domain='www.foo.bar.com') with pytest.raises(Cookie.URLMismatch): assert cookie.http_return_ok('http://192.168.1.1/one/two') def test_path(self): cookie = Cookie('color', 'blue') assert cookie.http_return_ok(self.url) cookie = Cookie('color', 'blue', path='/') assert cookie.http_return_ok(self.url) cookie = Cookie('color', 'blue', path='/one') assert cookie.http_return_ok(self.url) cookie = Cookie('color', 'blue', path='/oneX') with pytest.raises(Cookie.URLMismatch): assert cookie.http_return_ok(self.url) def test_expires(self): now = datetime.datetime.now( tz=datetime.timezone.utc).replace( microsecond=0) # expires 1 day from now expires = now + datetime.timedelta(days=1) cookie = Cookie('color', 'blue', expires=expires) assert cookie.http_return_ok(self.url) # expired 1 day ago expires = now + datetime.timedelta(days=-1) cookie = Cookie('color', 'blue', expires=expires) with pytest.raises(Cookie.Expired): assert cookie.http_return_ok(self.url) def test_httponly(self): cookie = Cookie('color', 'blue', httponly=True) assert cookie.http_return_ok('http://example.com') assert cookie.http_return_ok('https://example.com') with pytest.raises(Cookie.URLMismatch): assert cookie.http_return_ok('ftp://example.com') def test_secure(self): cookie = Cookie('color', 'blue', secure=True) assert cookie.http_return_ok('https://Xexample.com') with pytest.raises(Cookie.URLMismatch): assert cookie.http_return_ok('http://Xexample.com') class TestNormalization: @pytest.fixture(autouse=True) def normalization_setup(self): # Force microseconds to zero because cookie timestamps only have second resolution self.now = datetime.datetime.now( tz=datetime.timezone.utc).replace(microsecond=0) self.now_timestamp = datetime_from_utctimestamp( self.now.utctimetuple(), units=1).timestamp() self.now_string = email.utils.formatdate(self.now_timestamp, usegmt=True) self.max_age = 3600 # 1 hour self.age_expiration = self.now + datetime.timedelta(seconds=self.max_age) self.age_timestamp = datetime_from_utctimestamp( self.age_expiration.utctimetuple(), units=1).timestamp() self.age_string = email.utils.formatdate(self.age_timestamp, usegmt=True) self.expires = self.now + datetime.timedelta(days=1) # 1 day self.expires_timestamp = datetime_from_utctimestamp( self.expires.utctimetuple(), units=1).timestamp() self.expires_string = email.utils.formatdate(self.expires_timestamp, usegmt=True) def test_path_normalization(self): assert Cookie.normalize_url_path('') == '/' assert Cookie.normalize_url_path('foo') == '/' assert Cookie.normalize_url_path('foo/') == '/' assert Cookie.normalize_url_path('/foo') == '/' assert Cookie.normalize_url_path('/foo/') == '/foo' assert Cookie.normalize_url_path('/Foo/bar') == '/foo' assert Cookie.normalize_url_path('/foo/baR/') == '/foo/bar' def test_normalization(self): cookie = Cookie('color', 'blue', expires=self.expires) cookie.timestamp = self.now_timestamp assert cookie.domain is None assert cookie.path is None url = 'http://example.COM/foo' cookie.normalize(url) assert cookie.domain == 'example.com' assert cookie.path == '/' assert cookie.expires == self.expires cookie = Cookie('color', 'blue', max_age=self.max_age) cookie.timestamp = self.now_timestamp assert cookie.domain is None assert cookie.path is None url = 'http://example.com/foo/' cookie.normalize(url) assert cookie.domain == 'example.com' assert cookie.path == '/foo' assert cookie.expires == self.age_expiration cookie = Cookie('color', 'blue') url = 'http://example.com/foo' cookie.normalize(url) assert cookie.domain == 'example.com' assert cookie.path == '/' cookie = Cookie('color', 'blue') url = 'http://example.com/foo/bar' cookie.normalize(url) assert cookie.domain == 'example.com' assert cookie.path == '/foo' cookie = Cookie('color', 'blue') url = 'http://example.com/foo/bar/' cookie.normalize(url) assert cookie.domain == 'example.com' assert cookie.path == '/foo/bar'
18,858
Python
.py
433
34.856813
91
0.635838
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,367
test_session_storage.py
freeipa_freeipa/ipatests/test_ipapython/test_session_storage.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # """ Test the `session_storage.py` module. """ import pytest from ipapython import session_storage @pytest.mark.skip_ipaclient_unittest @pytest.mark.needs_ipaapi class test_session_storage: """ Test the session storage interface """ @pytest.fixture(autouse=True) def session_storage_setup(self): # TODO: set up test user and kinit to it # tmpdir = tempfile.mkdtemp(prefix = "tmp-") # os.environ['KRB5CCNAME'] = 'FILE:%s/ccache' % tmpdir self.principal = 'admin' self.key = 'X-IPA-test-session-storage' self.data = b'Test Data' def test_01(self): session_storage.store_data(self.principal, self.key, self.data) def test_02(self): data = session_storage.get_data(self.principal, self.key) assert(data == self.data) def test_03(self): session_storage.remove_data(self.principal, self.key) try: session_storage.get_data(self.principal, self.key) except session_storage.KRB5Error: pass
1,111
Python
.py
33
27.818182
71
0.668224
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,368
test_keyring.py
freeipa_freeipa/ipatests/test_ipapython/test_keyring.py
# Authors: # Rob Crittenden <rcritten@redhat.com> # # Copyright (C) 2012 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `kernel_keyring.py` module. """ from ipapython import kernel_keyring import pytest pytestmark = pytest.mark.tier0 TEST_KEY = 'ipa_test' TEST_UNICODEKEY = u'ipa_unicode' TEST_VALUE = b'abc123' UPDATE_VALUE = b'123abc' SIZE_256 = 'abcdefgh' * 32 SIZE_512 = 'abcdefgh' * 64 SIZE_1024 = 'abcdefgh' * 128 @pytest.mark.skip_if_container( "any", reason="kernel keyrings are not namespaced yet" ) class test_keyring: """ Test the kernel keyring interface """ @pytest.fixture(autouse=True) def keyring_setup(self): try: kernel_keyring.del_key(TEST_KEY) except ValueError: pass try: kernel_keyring.del_key(SIZE_256) except ValueError: pass try: kernel_keyring.del_key(TEST_UNICODEKEY) except ValueError: pass def test_01(self): """ Add a new key and value, then remove it """ kernel_keyring.add_key(TEST_KEY, TEST_VALUE) result = kernel_keyring.read_key(TEST_KEY) assert(result == TEST_VALUE) kernel_keyring.del_key(TEST_KEY) # Make sure it is gone try: result = kernel_keyring.read_key(TEST_KEY) except ValueError as e: assert str(e) == 'key %s not found' % TEST_KEY def test_02(self): """ Delete a non_existent key """ try: kernel_keyring.del_key(TEST_KEY) raise AssertionError('key should not have been deleted') except ValueError: pass def test_03(self): """ Add a duplicate key """ kernel_keyring.add_key(TEST_KEY, TEST_VALUE) with pytest.raises(ValueError): kernel_keyring.add_key(TEST_KEY, TEST_VALUE) def test_04(self): """ Update the value in a key """ kernel_keyring.update_key(TEST_KEY, UPDATE_VALUE) result = kernel_keyring.read_key(TEST_KEY) assert(result == UPDATE_VALUE) # Now update it 10 times for i in range(10): value = ('test %d' % i).encode('ascii') kernel_keyring.update_key(TEST_KEY, value) result = kernel_keyring.read_key(TEST_KEY) assert(result == value) kernel_keyring.del_key(TEST_KEY) def test_05(self): """ Read a non-existent key """ with pytest.raises(ValueError): kernel_keyring.read_key(TEST_KEY) def test_06(self): """ See if a key is available """ kernel_keyring.add_key(TEST_KEY, TEST_VALUE) assert kernel_keyring.has_key(TEST_KEY) # noqa kernel_keyring.del_key(TEST_KEY) assert not kernel_keyring.has_key(TEST_KEY) # noqa def test_07(self): """ Test a 256-byte key """ kernel_keyring.add_key(SIZE_256, TEST_VALUE) result = kernel_keyring.read_key(SIZE_256) assert(result == TEST_VALUE) kernel_keyring.del_key(SIZE_256) def test_08(self): """ Test 512-bytes of data """ kernel_keyring.add_key(TEST_KEY, SIZE_512.encode('ascii')) result = kernel_keyring.read_key(TEST_KEY) assert(result == SIZE_512.encode('ascii')) kernel_keyring.del_key(TEST_KEY) def test_09(self): """ Test 1k bytes of data """ kernel_keyring.add_key(TEST_KEY, SIZE_1024.encode('ascii')) result = kernel_keyring.read_key(TEST_KEY) assert(result == SIZE_1024.encode('ascii')) kernel_keyring.del_key(TEST_KEY) def test_10(self): """ Test a unicode key """ kernel_keyring.add_key(TEST_UNICODEKEY, TEST_VALUE) result = kernel_keyring.read_key(TEST_UNICODEKEY) assert(result == TEST_VALUE) kernel_keyring.del_key(TEST_UNICODEKEY)
4,697
Python
.py
141
26.021277
71
0.620667
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,369
test_ipavalidate.py
freeipa_freeipa/ipatests/test_ipapython/test_ipavalidate.py
# # Copyright (C) 2007 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys sys.path.insert(0, ".") import pytest from ipapython import ipavalidate pytestmark = pytest.mark.tier0 class TestValidate: def test_validEmail(self): assert ipavalidate.Email("test@freeipa.org") is True assert ipavalidate.Email("", notEmpty=False) is True def test_invalidEmail(self): assert ipavalidate.Email("test") is False assert ipavalidate.Email("test@freeipa") is False assert ipavalidate.Email("test@.com") is False assert ipavalidate.Email("") is False assert ipavalidate.Email(None) is False def test_validPlain(self): assert ipavalidate.Plain("Joe User") is True assert ipavalidate.Plain("Joe O'Malley") is True assert ipavalidate.Plain("", notEmpty=False) is True assert ipavalidate.Plain(None, notEmpty=False) is True assert ipavalidate.Plain("JoeUser", allowSpaces=False) is True assert ipavalidate.Plain("JoeUser", allowSpaces=True) is True def test_invalidPlain(self): assert ipavalidate.Plain("Joe (User)") is False assert ipavalidate.Plain("Joe C. User") is False assert ipavalidate.Plain("", notEmpty=True) is False assert ipavalidate.Plain(None, notEmpty=True) is False assert ipavalidate.Plain("Joe User", allowSpaces=False) is False assert ipavalidate.Plain("Joe C. User") is False def test_validString(self): assert ipavalidate.String("Joe User") is True assert ipavalidate.String("Joe O'Malley") is True assert ipavalidate.String("", notEmpty=False) is True assert ipavalidate.String(None, notEmpty=False) is True assert ipavalidate.String("Joe C. User") is True def test_invalidString(self): assert ipavalidate.String("", notEmpty=True) is False assert ipavalidate.String(None, notEmpty=True) is False def test_validPath(self): assert ipavalidate.Path("/") is True assert ipavalidate.Path("/home/user") is True assert ipavalidate.Path("../home/user") is True assert ipavalidate.Path("", notEmpty=False) is True assert ipavalidate.Path(None, notEmpty=False) is True def test_invalidPath(self): assert ipavalidate.Path("(foo)") is False assert ipavalidate.Path("", notEmpty=True) is False assert ipavalidate.Path(None, notEmpty=True) is False def test_validName(self): assert ipavalidate.GoodName("foo") is True assert ipavalidate.GoodName("1foo") is True assert ipavalidate.GoodName("foo.bar") is True assert ipavalidate.GoodName("foo.bar$") is True def test_invalidName(self): assert ipavalidate.GoodName("foo bar") is False assert ipavalidate.GoodName("foo%bar") is False assert ipavalidate.GoodName("*foo") is False assert ipavalidate.GoodName("$foo.bar$") is False
3,623
Python
.py
75
42.093333
72
0.710727
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,370
test_ssh.py
freeipa_freeipa/ipatests/test_ipapython/test_ssh.py
# Authors: # Jan Cholasta <jcholast@redhat.com> # # Copyright (C) 2011 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipapython/ssh.py` module. """ import base64 import six import pytest from ipapython import ssh if six.PY3: unicode = str pytestmark = pytest.mark.tier0 b64 = 'AAAAB3NzaC1yc2EAAAADAQABAAABAQDGAX3xAeLeaJggwTqMjxNwa6XHBUAikXPGMzEpVrlLDCZtv00djsFTBi38PkgxBJVkgRWMrcBsr/35lq7P6w8KGIwA8GI48Z0qBS2NBMJ2u9WQ2hjLN6GdMlo77O0uJY3251p12pCVIS/bHRSq8kHO2No8g7KA9fGGcagPfQH+ee3t7HUkpbQkFTmbPPN++r3V8oVUk5LxbryB3UIIVzNmcSIn3JrXynlvui4MixvrtX6zx+O/bBo68o8/eZD26QrahVbA09fivrn/4h3TM019Eu/c2jOdckfU3cHUV/3Tno5d6JicibyaoDDK7S/yjdn5jhaz8MSEayQvFkZkiF0L' raw = base64.b64decode(b64) openssh = 'ssh-rsa %s' % b64 @pytest.mark.parametrize("pk,out", [ (b'\xff', UnicodeDecodeError), (u'\xff', ValueError), (raw, openssh), (b'\0\0\0\x04none', u'none AAAABG5vbmU='), (b'\0\0\0', ValueError), (b'\0\0\0\0', ValueError), (b'\0\0\0\x01', ValueError), (b'\0\0\0\x01\xff', ValueError), (u'\0\0\0\x04none', ValueError), (u'\0\0\0', ValueError), (u'\0\0\0\0', ValueError), (u'\0\0\0\x01', ValueError), (u'\0\0\0\x01\xff', ValueError), (b64, openssh), (unicode(b64), openssh), (b64.encode('ascii'), openssh), (u'\n%s\n\n' % b64, openssh), (u'AAAABG5vbmU=', u'none AAAABG5vbmU='), (u'AAAAB', ValueError), (openssh, openssh), (unicode(openssh), openssh), (openssh.encode('ascii'), openssh), (u'none AAAABG5vbmU=', u'none AAAABG5vbmU='), (u'\t \t ssh-rsa \t \t%s\t \tthis is a comment\t \t ' % b64, u'%s this is a comment' % openssh), (u'opt3,opt2="\tx ",opt1,opt2="\\"x " %s comment ' % openssh, u'opt1,opt2="\\"x ",opt3 %s comment' % openssh), (u'permitopen=\"1.1.1.1:111\",permitopen=\"2.2.2.2:222\" %s' % openssh, u'permitopen=\"1.1.1.1:111\",permitopen=\"2.2.2.2:222\" %s' % openssh), (u'permitlisten=\"1.1.1.1:111\",permitlisten=\"2.2.2.2:222\" %s' % openssh, u'permitlisten=\"1.1.1.1:111\",permitlisten=\"2.2.2.2:222\" %s' % openssh), (u'ssh-rsa\n%s' % b64, ValueError), (u'ssh-rsa\t%s' % b64, ValueError), (u'vanitas %s' % b64, ValueError), (u'@opt %s' % openssh, ValueError), (u'opt=val %s' % openssh, ValueError), (u'opt, %s' % openssh, ValueError)], # ids=repr is workaround for pytest issue with NULL bytes, # see https://github.com/pytest-dev/pytest/issues/2644 ids=repr ) def test_public_key_parsing(pk, out): if isinstance(out, type) and issubclass(out, Exception): pytest.raises(out, ssh.SSHPublicKey, pk) else: parsed = ssh.SSHPublicKey(pk) assert parsed.openssh() == out
3,349
Python
.py
79
38.708861
380
0.688459
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,371
test_certdb.py
freeipa_freeipa/ipatests/test_ipapython/test_certdb.py
from __future__ import absolute_import import os import pytest from ipapython.certdb import ( NSSDatabase, TRUSTED_PEER_TRUST_FLAGS, nss_supports_dbm, ) from ipapython import ipautil from ipaplatform.osinfo import osinfo CERTNICK = 'testcert' CERTSAN = 'testcert.certdb.test' if osinfo.id == 'fedora': if osinfo.version_number >= (28,): NSS_DEFAULT = 'sql' else: NSS_DEFAULT = 'dbm' else: NSS_DEFAULT = None def create_selfsigned(nssdb): # create self-signed cert + key noisefile = os.path.join(nssdb.secdir, 'noise') with open(noisefile, 'wb') as f: f.write(os.urandom(64)) try: nssdb.run_certutil([ '-S', '-x', '-z', noisefile, '-k', 'rsa', '-g', '2048', '-Z', 'SHA256', '-t', 'CTu,Cu,Cu', '-s', 'CN=testcert', '-n', CERTNICK, '-m', '365', '--extSAN', f'dns:{CERTSAN}' ]) finally: os.unlink(noisefile) @pytest.mark.skipif( not nss_supports_dbm(), reason="NSS is built without support of the legacy database(DBM)", ) def test_dbm_tmp(): with NSSDatabase(dbtype='dbm') as nssdb: assert nssdb.dbtype == 'dbm' for filename in nssdb.filenames: assert not os.path.isfile(filename) assert not nssdb.exists() nssdb.create_db() for filename in nssdb.filenames: assert os.path.isfile(filename) assert os.path.dirname(filename) == nssdb.secdir assert nssdb.exists() assert os.path.basename(nssdb.certdb) == 'cert8.db' assert nssdb.certdb in nssdb.filenames assert os.path.basename(nssdb.keydb) == 'key3.db' assert os.path.basename(nssdb.secmod) == 'secmod.db' @pytest.mark.skipif( nss_supports_dbm(), reason="NSS is built with support of the legacy database(DBM)", ) def test_dbm_raise(): with pytest.raises(ValueError) as e: NSSDatabase(dbtype="dbm") assert ( "NSS is built without support of the legacy database(DBM)" in str(e.value) ) def test_sql_tmp(): with NSSDatabase(dbtype='sql') as nssdb: assert nssdb.dbtype == 'sql' for filename in nssdb.filenames: assert not os.path.isfile(filename) assert not nssdb.exists() nssdb.create_db() for filename in nssdb.filenames: assert os.path.isfile(filename) assert os.path.dirname(filename) == nssdb.secdir assert nssdb.exists() assert os.path.basename(nssdb.certdb) == 'cert9.db' assert nssdb.certdb in nssdb.filenames assert os.path.basename(nssdb.keydb) == 'key4.db' assert os.path.basename(nssdb.secmod) == 'pkcs11.txt' @pytest.mark.skipif( not nss_supports_dbm(), reason="NSS is built without support of the legacy database(DBM)", ) def test_convert_db(): with NSSDatabase(dbtype='dbm') as nssdb: assert nssdb.dbtype == 'dbm' nssdb.create_db() assert nssdb.exists() create_selfsigned(nssdb) oldcerts = nssdb.list_certs() assert len(oldcerts) == 1 oldkeys = nssdb.list_keys() assert len(oldkeys) == 1 nssdb.convert_db() assert nssdb.exists() assert nssdb.dbtype == 'sql' newcerts = nssdb.list_certs() assert len(newcerts) == 1 assert newcerts == oldcerts newkeys = nssdb.list_keys() assert len(newkeys) == 1 assert newkeys == oldkeys for filename in nssdb.filenames: assert os.path.isfile(filename) assert os.path.dirname(filename) == nssdb.secdir assert os.path.basename(nssdb.certdb) == 'cert9.db' assert nssdb.certdb in nssdb.filenames assert os.path.basename(nssdb.keydb) == 'key4.db' assert os.path.basename(nssdb.secmod) == 'pkcs11.txt' @pytest.mark.skipif( not nss_supports_dbm(), reason="NSS is built without support of the legacy database(DBM)", ) def test_convert_db_nokey(): with NSSDatabase(dbtype='dbm') as nssdb: assert nssdb.dbtype == 'dbm' nssdb.create_db() create_selfsigned(nssdb) assert len(nssdb.list_certs()) == 1 assert len(nssdb.list_keys()) == 1 # remove key, readd cert cert = nssdb.get_cert(CERTNICK) nssdb.run_certutil(['-F', '-n', CERTNICK]) nssdb.add_cert(cert, CERTNICK, TRUSTED_PEER_TRUST_FLAGS) assert len(nssdb.list_keys()) == 0 oldcerts = nssdb.list_certs() assert len(oldcerts) == 1 nssdb.convert_db() assert nssdb.dbtype == 'sql' newcerts = nssdb.list_certs() assert len(newcerts) == 1 assert newcerts == oldcerts assert nssdb.get_cert(CERTNICK) == cert newkeys = nssdb.list_keys() assert newkeys == () for filename in nssdb.filenames: assert os.path.isfile(filename) assert os.path.dirname(filename) == nssdb.secdir old = os.path.join(nssdb.secdir, 'cert8.db') assert not os.path.isfile(old) assert os.path.isfile(old + '.migrated') assert os.path.basename(nssdb.certdb) == 'cert9.db' assert nssdb.certdb in nssdb.filenames assert os.path.basename(nssdb.keydb) == 'key4.db' assert os.path.basename(nssdb.secmod) == 'pkcs11.txt' def test_auto_db(): with NSSDatabase() as nssdb: assert nssdb.dbtype == 'auto' assert nssdb.filenames is None assert not nssdb.exists() with pytest.raises(RuntimeError): nssdb.list_certs() nssdb.create_db() assert nssdb.dbtype in ('dbm', 'sql') if NSS_DEFAULT is not None: assert nssdb.dbtype == NSS_DEFAULT assert nssdb.filenames is not None assert nssdb.exists() nssdb.list_certs() def test_delete_cert_and_key(): """Test that delete_cert + delete_key always deletes everything Test with a NSSDB that contains: - cert + key - key only - cert only - none of them """ cmd = ipautil.run(['mktemp'], capture_output=True) p12file = cmd.output.strip() try: with NSSDatabase() as nssdb: nssdb.create_db() # 1. Test delete_key_and_cert when cert + key are present # Create a NSS DB with cert + key create_selfsigned(nssdb) # Save both in a p12 file for latter use ipautil.run( [ 'pk12util', '-o', p12file, '-n', CERTNICK, '-d', nssdb.secdir, '-k', nssdb.pwd_file, '-w', nssdb.pwd_file ]) # Delete cert and key nssdb.delete_key_and_cert(CERTNICK) # make sure that everything was deleted assert len(nssdb.list_keys()) == 0 assert len(nssdb.list_certs()) == 0 # 2. Test delete_key_and_cert when only key is present # Import cert and key then remove cert import_args = [ 'pk12util', '-i', p12file, '-d', nssdb.secdir, '-k', nssdb.pwd_file, '-w', nssdb.pwd_file] ipautil.run(import_args) nssdb.delete_cert(CERTNICK) # Delete cert and key nssdb.delete_key_and_cert(CERTNICK) # make sure that everything was deleted assert len(nssdb.list_keys()) == 0 assert len(nssdb.list_certs()) == 0 # 3. Test delete_key_and_cert when only cert is present # Import cert and key then remove key ipautil.run(import_args) nssdb.delete_key_only(CERTNICK) # make sure the db contains only the cert assert len(nssdb.list_keys()) == 0 assert len(nssdb.list_certs()) == 1 # Delete cert and key when key is not present nssdb.delete_key_and_cert(CERTNICK) # make sure that everything was deleted assert len(nssdb.list_keys()) == 0 assert len(nssdb.list_certs()) == 0 # 4. Test delete_key_and_cert with a wrong nickname # Import cert and key ipautil.run(import_args) # Delete cert and key nssdb.delete_key_and_cert('wrongnick') # make sure that nothing was deleted assert len(nssdb.list_keys()) == 1 assert len(nssdb.list_certs()) == 1 finally: os.unlink(p12file) def test_check_validity(): with NSSDatabase() as nssdb: nssdb.create_db() create_selfsigned(nssdb) with pytest.raises(ValueError): nssdb.verify_ca_cert_validity(CERTNICK) nssdb.verify_server_cert_validity(CERTNICK, CERTSAN) with pytest.raises(ValueError): nssdb.verify_server_cert_validity(CERTNICK, 'invalid.example')
8,960
Python
.py
236
28.889831
74
0.597533
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,372
test_dnsutil.py
freeipa_freeipa/ipatests/test_ipapython/test_dnsutil.py
# # Copyright (C) 2018 FreeIPA Contributors. See COPYING for license # import dns.name import dns.rdataclass import dns.rdatatype from dns.rdtypes.IN.SRV import SRV from dns.rdtypes.ANY.URI import URI from ipapython import dnsutil import pytest def mksrv(priority, weight, port, target): return SRV( rdclass=dns.rdataclass.IN, rdtype=dns.rdatatype.SRV, priority=priority, weight=weight, port=port, target=dns.name.from_text(target) ) def mkuri(priority, weight, target): return URI( rdclass=dns.rdataclass.IN, rdtype=dns.rdatatype.URI, priority=priority, weight=weight, target=target ) class TestSortSRV: def test_empty(self): assert dnsutil.sort_prio_weight([]) == [] def test_one(self): h1 = mksrv(1, 0, 443, u"host1") assert dnsutil.sort_prio_weight([h1]) == [h1] h2 = mksrv(10, 5, 443, u"host2") assert dnsutil.sort_prio_weight([h2]) == [h2] def test_prio(self): h1 = mksrv(1, 0, 443, u"host1") h2 = mksrv(2, 0, 443, u"host2") h3 = mksrv(3, 0, 443, u"host3") assert dnsutil.sort_prio_weight([h3, h2, h1]) == [h1, h2, h3] assert dnsutil.sort_prio_weight([h3, h3, h3]) == [h3] assert dnsutil.sort_prio_weight([h2, h2, h1, h1]) == [h1, h2] h380 = mksrv(4, 0, 80, u"host3") assert dnsutil.sort_prio_weight([h1, h3, h380]) == [h1, h3, h380] def assert_permutations(self, answers, permutations): seen = set() for _unused in range(1000): result = tuple(dnsutil.sort_prio_weight(answers)) assert result in permutations seen.add(result) if seen == permutations: break else: pytest.fail("sorting didn't exhaust all permutations.") def test_sameprio(self): h1 = mksrv(1, 0, 443, u"host1") h2 = mksrv(1, 0, 443, u"host2") permutations = { (h1, h2), (h2, h1), } self.assert_permutations([h1, h2], permutations) def test_weight(self): h1 = mksrv(1, 0, 443, u"host1") h2_w15 = mksrv(2, 15, 443, u"host2") h3_w10 = mksrv(2, 10, 443, u"host3") permutations = { (h1, h2_w15, h3_w10), (h1, h3_w10, h2_w15), } self.assert_permutations([h1, h2_w15, h3_w10], permutations) def test_large(self): records = tuple( mksrv(1, i, 443, "host{}".format(i)) for i in range(1000) ) assert len(dnsutil.sort_prio_weight(records)) == len(records) class TestSortURI: def test_prio(self): h1 = mkuri(1, 0, u"https://host1/api") h2 = mkuri(2, 0, u"https://host2/api") h3 = mkuri(3, 0, u"https://host3/api") assert dnsutil.sort_prio_weight([h3, h2, h1]) == [h1, h2, h3] assert dnsutil.sort_prio_weight([h3, h3, h3]) == [h3] assert dnsutil.sort_prio_weight([h2, h2, h1, h1]) == [h1, h2] class TestDNSResolver: @pytest.fixture(name="res") def resolver(self): """Resolver that doesn't read /etc/resolv.conf /etc/resolv.conf is not mandatory on systems """ return dnsutil.DNSResolver(configure=False) def test_nameservers(self, res): res.nameservers = ["4.4.4.4", "8.8.8.8"] assert res.nameservers == ["4.4.4.4", "8.8.8.8"] def test_nameservers_with_ports(self, res): res.nameservers = ["4.4.4.4 port 53", "8.8.8.8 port 8053"] assert res.nameservers == ["4.4.4.4", "8.8.8.8"] assert res.nameserver_ports == {"4.4.4.4": 53, "8.8.8.8": 8053} res.nameservers = ["4.4.4.4 port 53", "8.8.8.8 port 8053"] assert res.nameservers == ["4.4.4.4", "8.8.8.8"] assert res.nameserver_ports == {"4.4.4.4": 53, "8.8.8.8": 8053} def test_nameservers_with_bad_ports(self, res): try: res.nameservers = ["4.4.4.4 port a"] except ValueError: pass else: pytest.fail("No fail on bad port a") try: res.nameservers = ["4.4.4.4 port -1"] except ValueError: pass else: pytest.fail("No fail on bad port -1") try: res.nameservers = ["4.4.4.4 port 65536"] except ValueError: pass else: pytest.fail("No fail on bad port 65536")
4,446
Python
.py
120
28.683333
73
0.5698
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,373
__init__.py
freeipa_freeipa/ipatests/test_ipapython/__init__.py
# Authors: # Jan Cholasta <jcholast@redhat.com> # # Copyright (C) 2011 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Sub-package containing unit tests for `ipapython` package. """
840
Python
.py
21
38.952381
71
0.771394
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,374
test_kerberos.py
freeipa_freeipa/ipatests/test_ipapython/test_kerberos.py
# # Copyright (C) 2016 FreeIPA Project Contributors - see LICENSE file # import pytest import six from ipapython.kerberos import Principal if six.PY3: unicode = str valid_principals = { u'tuser@REALM.TEST': { 'components': (u'tuser',), 'realm': u'REALM.TEST', 'username': u'tuser' }, u'tuser\\@tupn.test@REALM.TEST': { 'components': (u'tuser@tupn.test',), 'realm': u'REALM.TEST', 'username': u'tuser@tupn.test', 'upn_suffix': u'tupn.test' }, u'test/host.ipa.test@REALM.TEST': { 'components': (u'test', u'host.ipa.test'), 'realm': u'REALM.TEST', 'hostname': u'host.ipa.test' }, u'test/service/host.ipa.test@REALM.TEST': { 'components': (u'test', u'service', u'host.ipa.test'), 'realm': u'REALM.TEST', 'service_name': u'test/service' }, u'tuser': { 'components': (u'tuser',), 'realm': None, 'username': u'tuser' }, u'$%user@REALM.TEST': { 'components': (u'$%user',), 'realm': u'REALM.TEST', 'username': u'$%user' }, u'host/host.ipa.test': { 'components': (u'host', u'host.ipa.test'), 'realm': None, 'hostname': u'host.ipa.test' }, u's$c/$%^.ipa.t%$t': { 'components': (u's$c', u'$%^.ipa.t%$t'), 'realm': None, 'hostname': u'$%^.ipa.t%$t', 'service_name': u's$c' }, u'test\\/service/test\\/host@REALM\\@TEST': { 'components': (u'test/service', u'test/host'), 'realm': u'REALM@TEST', 'hostname': u'test/host', 'service_name': r'test\/service' } } def valid_principal_iter(principals): for princ, data in principals.items(): yield princ, data @pytest.fixture(params=list(valid_principal_iter(valid_principals))) def valid_principal(request): return request.param def test_principals(valid_principal): principal_name, data = valid_principal princ = Principal(principal_name) for name, value in data.items(): assert getattr(princ, name) == value assert unicode(princ) == principal_name assert repr(princ) == "ipapython.kerberos.Principal('{}')".format( principal_name) def test_multiple_unescaped_ats_raise_error(): pytest.raises(ValueError, Principal, u'too@many@realms') principals_properties = { u'user@REALM': { 'property_true': ('is_user',), 'property_raises': ('upn_suffix', 'hostname', 'service_name') }, u'host/m1.ipa.test@REALM': { 'property_true': ('is_host', 'is_service'), 'property_raises': ('username', 'upn_suffix') }, u'service/m1.ipa.test@REALM': { 'property_true': ('is_service'), 'property_raises': ('username', 'upn_suffix') }, u'user\\@domain@REALM': { 'property_true': ('is_user', 'is_enterprise'), 'property_raises': ('hostname', 'service_name') } } def principal_properties_iter(principals_properties): for p, data in principals_properties.items(): yield p, data @pytest.fixture(params=list(principal_properties_iter(principals_properties))) def principal_properties(request): return request.param def test_principal_properties(principal_properties): principal, data = principal_properties princ = Principal(principal) boolean_propertes = [prop for prop in dir(princ) if prop.startswith('is_')] for b in boolean_propertes: if b in data['property_true']: assert getattr(princ, b) else: assert not getattr(princ, b) for property_raises in data['property_raises']: with pytest.raises(ValueError): getattr(princ, property_raises)
3,760
Python
.py
111
27.315315
78
0.605081
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,375
test_ipautil.py
freeipa_freeipa/ipatests/test_ipapython/test_ipautil.py
# encoding: utf-8 # Authors: # Jan Cholasta <jcholast@redhat.com> # # Copyright (C) 2011 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipapython/ipautil.py` module. """ from __future__ import absolute_import import os import socket import sys import tempfile import textwrap import time import pytest import six from ipalib.constants import IPAAPI_USER from ipaplatform.paths import paths from ipapython import ipautil pytestmark = pytest.mark.tier0 def assert_equal(a, b): __tracebackhide__ = True assert a == b @pytest.mark.parametrize("addr,words,prefixlen", [ ('0.0.0.0/0', None, None), ('10.11.12.13', (10, 11, 12, 13), 8), ('10.11.12.13/14', (10, 11, 12, 13), 14), ('10.11.12.13%zoneid', None, None), ('10.11.12.13%zoneid/14', None, None), ('10.11.12.1337', None, None), ('10.11.12.13/33', None, None), ('127.0.0.1', None, None), ('241.1.2.3', None, None), ('169.254.1.2', None, None), ('10.11.12.0/24', (10, 11, 12, 0), 24), ('10.0.0.255', (10, 0, 0, 255), 8), ('224.5.6.7', None, None), ('10.11.12.255/24', (10, 11, 12, 255), 24), ('255.255.255.255', None, None), ('::/0', None, None), ('2001::1', (0x2001, 0, 0, 0, 0, 0, 0, 1), 64), ('2001::1/72', (0x2001, 0, 0, 0, 0, 0, 0, 1), 72), ('2001::1%zoneid', (0x2001, 0, 0, 0, 0, 0, 0, 1), 64), ('2001::1%zoneid/72', None, None), ('2001::1beef', None, None), ('2001::1/129', None, None), ('::1', None, None), ('6789::1', None, None), ('fe89::1', None, None), ('2001::/64', (0x2001, 0, 0, 0, 0, 0, 0, 0), 64), ('ff01::1', None, None), ('junk', None, None) ]) def test_ip_address(addr, words, prefixlen): if words is None: pytest.raises( ValueError, ipautil.CheckedIPAddress, addr) else: ip = ipautil.CheckedIPAddress(addr) assert ip.words == words assert ip.prefixlen == prefixlen class TestCIDict: @pytest.fixture(autouse=True) def cidict_setup(self): self.cidict = ipautil.CIDict() self.cidict["Key1"] = "val1" self.cidict["key2"] = "val2" self.cidict["KEY3"] = "VAL3" def test_init(self): cidict = ipautil.CIDict() assert dict(cidict.items()) == {} cidict = ipautil.CIDict([('a', 2), ('b', 3), ('C', 4)]) assert dict(cidict.items()) == {'a': 2, 'b': 3, 'C': 4} cidict = ipautil.CIDict([('a', 2), ('b', None)], b=3, C=4) assert dict(cidict.items()) == {'a': 2, 'b': 3, 'C': 4} cidict = ipautil.CIDict({'a': 2, 'b': None}, b=3, C=4) assert dict(cidict.items()) == {'a': 2, 'b': 3, 'C': 4} cidict = ipautil.CIDict(a=2, b=3, C=4) assert dict(cidict.items()) == {'a': 2, 'b': 3, 'C': 4} def test_len(self): assert_equal(3, len(self.cidict)) def test_getitem(self): assert_equal("val1", self.cidict["Key1"]) assert_equal("val1", self.cidict["key1"]) assert_equal("val2", self.cidict["KEY2"]) assert_equal("VAL3", self.cidict["key3"]) assert_equal("VAL3", self.cidict["KEY3"]) with pytest.raises(KeyError): self.cidict["key4"] # pylint: disable=pointless-statement def test_get(self): assert_equal("val1", self.cidict.get("Key1")) assert_equal("val1", self.cidict.get("key1")) assert_equal("val2", self.cidict.get("KEY2")) assert_equal("VAL3", self.cidict.get("key3")) assert_equal("VAL3", self.cidict.get("KEY3")) assert_equal("default", self.cidict.get("key4", "default")) def test_setitem(self): self.cidict["key4"] = "val4" assert_equal("val4", self.cidict["key4"]) self.cidict["KEY4"] = "newval4" assert_equal("newval4", self.cidict["key4"]) def test_del(self): assert "Key1" in self.cidict del(self.cidict["Key1"]) assert "Key1" not in self.cidict assert "key2" in self.cidict del(self.cidict["KEY2"]) assert "key2" not in self.cidict def test_clear(self): assert_equal(3, len(self.cidict)) self.cidict.clear() assert_equal(0, len(self.cidict)) assert self.cidict == {} assert list(self.cidict) == [] assert list(self.cidict.values()) == [] assert list(self.cidict.items()) == [] if six.PY2: assert self.cidict.keys() == [] assert self.cidict.values() == [] assert self.cidict.items() == [] assert self.cidict._keys == {} def test_copy(self): copy = self.cidict.copy() assert copy == self.cidict assert_equal(3, len(copy)) assert "Key1" in copy assert "key1" in copy assert_equal("val1", copy["Key1"]) @pytest.mark.skipif(not six.PY2, reason="Python 2 only") def test_haskey(self): assert self.cidict.has_key("KEY1") # noqa assert self.cidict.has_key("key2") # noqa assert self.cidict.has_key("key3") # noqa assert not self.cidict.has_key("Key4") # noqa def test_contains(self): assert "KEY1" in self.cidict assert "key2" in self.cidict assert "key3" in self.cidict assert "Key4" not in self.cidict def test_items(self): items = list(self.cidict.items()) assert_equal(3, len(items)) items_set = set(items) assert ("Key1", "val1") in items_set assert ("key2", "val2") in items_set assert ("KEY3", "VAL3") in items_set # pylint: disable=dict-iter-method # pylint: disable=dict-keys-not-iterating, dict-values-not-iterating assert list(self.cidict.items()) == list(self.cidict.iteritems()) == list(zip( self.cidict.keys(), self.cidict.values())) def test_iter(self): assert list(self.cidict) == list(self.cidict.keys()) assert sorted(self.cidict) == sorted(['Key1', 'key2', 'KEY3']) def test_iteritems(self): items = [] # pylint: disable=dict-iter-method for k, v in self.cidict.iteritems(): items.append((k, v)) assert_equal(3, len(items)) items_set = set(items) assert ("Key1", "val1") in items_set assert ("key2", "val2") in items_set assert ("KEY3", "VAL3") in items_set def test_iterkeys(self): keys = [] # pylint: disable=dict-iter-method for k in self.cidict.iterkeys(): keys.append(k) assert_equal(3, len(keys)) keys_set = set(keys) assert "Key1" in keys_set assert "key2" in keys_set assert "KEY3" in keys_set def test_itervalues(self): values = [] # pylint: disable=dict-iter-method for k in self.cidict.itervalues(): values.append(k) assert_equal(3, len(values)) values_set = set(values) assert "val1" in values_set assert "val2" in values_set assert "VAL3" in values_set def test_keys(self): keys = list(self.cidict.keys()) assert_equal(3, len(keys)) keys_set = set(keys) assert "Key1" in keys_set assert "key2" in keys_set assert "KEY3" in keys_set # pylint: disable=dict-iter-method assert list(self.cidict.keys()) == list(self.cidict.iterkeys()) def test_values(self): values = list(self.cidict.values()) assert_equal(3, len(values)) values_set = set(values) assert "val1" in values_set assert "val2" in values_set assert "VAL3" in values_set # pylint: disable=dict-iter-method assert list(self.cidict.values()) == list(self.cidict.itervalues()) def test_update(self): newdict = { "KEY2": "newval2", "key4": "val4" } self.cidict.update(newdict) assert_equal(4, len(self.cidict)) items = list(self.cidict.items()) assert_equal(4, len(items)) items_set = set(items) assert ("Key1", "val1") in items_set # note the update "overwrites" the case of the key2 assert ("KEY2", "newval2") in items_set assert ("KEY3", "VAL3") in items_set assert ("key4", "val4") in items_set def test_update_dict_and_kwargs(self): self.cidict.update({'a': 'va', 'b': None}, b='vb', key2='v2') assert dict(self.cidict.items()) == { 'a': 'va', 'b': 'vb', 'Key1': 'val1', 'key2': 'v2', 'KEY3': 'VAL3'} def test_update_list_and_kwargs(self): self.cidict.update([('a', 'va'), ('b', None)], b='vb', key2='val2') assert dict(self.cidict.items()) == { 'a': 'va', 'b': 'vb', 'Key1': 'val1', 'key2': 'val2', 'KEY3': 'VAL3'} def test_update_duplicate_values_dict(self): with pytest.raises(ValueError): self.cidict.update({'a': 'va', 'A': None, 'b': 3}) def test_update_duplicate_values_list(self): with pytest.raises(ValueError): self.cidict.update([('a', 'va'), ('A', None), ('b', 3)]) def test_update_duplicate_values_kwargs(self): with pytest.raises(ValueError): self.cidict.update(a='va', A=None, b=3) def test_update_kwargs(self): self.cidict.update(b='vb', key2='val2') assert dict(self.cidict.items()) == { 'b': 'vb', 'Key1': 'val1', 'key2': 'val2', 'KEY3': 'VAL3'} def test_setdefault(self): assert_equal("val1", self.cidict.setdefault("KEY1", "default")) assert "KEY4" not in self.cidict assert_equal("default", self.cidict.setdefault("KEY4", "default")) assert "KEY4" in self.cidict assert_equal("default", self.cidict["key4"]) assert "KEY5" not in self.cidict assert_equal(None, self.cidict.setdefault("KEY5")) assert "KEY5" in self.cidict assert_equal(None, self.cidict["key5"]) def test_pop(self): assert_equal("val1", self.cidict.pop("KEY1", "default")) assert "key1" not in self.cidict assert_equal("val2", self.cidict.pop("KEY2")) assert "key2" not in self.cidict assert_equal("default", self.cidict.pop("key4", "default")) with pytest.raises(KeyError): self.cidict.pop("key4") def test_popitem(self): items = set(self.cidict.items()) assert_equal(3, len(self.cidict)) item = self.cidict.popitem() assert_equal(2, len(self.cidict)) assert item in items items.discard(item) item = self.cidict.popitem() assert_equal(1, len(self.cidict)) assert item in items items.discard(item) item = self.cidict.popitem() assert_equal(0, len(self.cidict)) assert item in items items.discard(item) def test_fromkeys(self): dct = ipautil.CIDict.fromkeys(('A', 'b', 'C')) assert sorted(dct.keys()) == sorted(['A', 'b', 'C']) assert list(dct.values()) == [None] * 3 class TestTimeParser: def test_simple(self): timestr = "20070803" time = ipautil.parse_generalized_time(timestr) assert_equal(2007, time.year) assert_equal(8, time.month) assert_equal(3, time.day) assert_equal(0, time.hour) assert_equal(0, time.minute) assert_equal(0, time.second) def test_hour_min_sec(self): timestr = "20051213141205" time = ipautil.parse_generalized_time(timestr) assert_equal(2005, time.year) assert_equal(12, time.month) assert_equal(13, time.day) assert_equal(14, time.hour) assert_equal(12, time.minute) assert_equal(5, time.second) def test_fractions(self): timestr = "2003092208.5" time = ipautil.parse_generalized_time(timestr) assert_equal(2003, time.year) assert_equal(9, time.month) assert_equal(22, time.day) assert_equal(8, time.hour) assert_equal(30, time.minute) assert_equal(0, time.second) timestr = "199203301544,25" time = ipautil.parse_generalized_time(timestr) assert_equal(1992, time.year) assert_equal(3, time.month) assert_equal(30, time.day) assert_equal(15, time.hour) assert_equal(44, time.minute) assert_equal(15, time.second) timestr = "20060401185912,8" time = ipautil.parse_generalized_time(timestr) assert_equal(2006, time.year) assert_equal(4, time.month) assert_equal(1, time.day) assert_equal(18, time.hour) assert_equal(59, time.minute) assert_equal(12, time.second) assert_equal(800000, time.microsecond) def test_time_zones(self): timestr = "20051213141205Z" time = ipautil.parse_generalized_time(timestr) assert_equal(0, time.tzinfo.houroffset) assert_equal(0, time.tzinfo.minoffset) offset = time.tzinfo.utcoffset(time.tzinfo.dst()) assert_equal(0, offset.seconds) timestr = "20051213141205+0500" time = ipautil.parse_generalized_time(timestr) assert_equal(5, time.tzinfo.houroffset) assert_equal(0, time.tzinfo.minoffset) offset = time.tzinfo.utcoffset(time.tzinfo.dst()) assert_equal(5 * 60 * 60, offset.seconds) timestr = "20051213141205-0500" time = ipautil.parse_generalized_time(timestr) assert_equal(-5, time.tzinfo.houroffset) assert_equal(0, time.tzinfo.minoffset) # NOTE - the offset is always positive - it's minutes # _east_ of UTC offset = time.tzinfo.utcoffset(time.tzinfo.dst()) assert_equal((24 - 5) * 60 * 60, offset.seconds) timestr = "20051213141205-0930" time = ipautil.parse_generalized_time(timestr) assert_equal(-9, time.tzinfo.houroffset) assert_equal(-30, time.tzinfo.minoffset) offset = time.tzinfo.utcoffset(time.tzinfo.dst()) assert_equal(((24 - 9) * 60 * 60) - (30 * 60), offset.seconds) def test_run(): result = ipautil.run([paths.ECHO, 'foo\x02bar'], capture_output=True, capture_error=True) assert result.returncode == 0 assert result.output == 'foo\x02bar\n' assert result.raw_output == b'foo\x02bar\n' assert result.error_output == '' assert result.raw_error_output == b'' def test_run_no_capture_output(): result = ipautil.run([paths.ECHO, 'foo\x02bar']) assert result.returncode == 0 assert result.output is None assert result.raw_output == b'foo\x02bar\n' assert result.error_output is None assert result.raw_error_output == b'' def test_run_bytes(): result = ipautil.run([paths.ECHO, b'\x01\x02'], capture_output=True) assert result.returncode == 0 assert result.raw_output == b'\x01\x02\n' def test_run_decode(): result = ipautil.run([paths.ECHO, u'รก'.encode('utf-8')], encoding='utf-8', capture_output=True) assert result.returncode == 0 if six.PY3: assert result.output == 'รก\n' else: assert result.output == 'รก\n'.encode('utf-8') def test_run_decode_bad(): if six.PY3: with pytest.raises(UnicodeDecodeError): ipautil.run([paths.ECHO, b'\xa0\xa1'], capture_output=True, encoding='utf-8') else: result = ipautil.run([paths.ECHO, '\xa0\xa1'], capture_output=True, encoding='utf-8') assert result.returncode == 0 assert result.output == '\xa0\xa1\n' def test_backcompat(): result = out, err, rc = ipautil.run([paths.ECHO, 'foo\x02bar'], capture_output=True, capture_error=True) assert rc is result.returncode assert out is result.output assert err is result.error_output def test_flush_sync(): with tempfile.NamedTemporaryFile('wb+') as f: f.write(b'data') ipautil.flush_sync(f) def test_run_stderr(): args = [ sys.executable, '-c', 'import sys; sys.exit(" ".join(("error", "message")))' ] with pytest.raises(ipautil.CalledProcessError) as cm: ipautil.run(args) assert cm.value.cmd == repr(args) assert cm.value.stderr == "error message\n" assert "CalledProcessError(" in str(cm.value) assert repr(args) in str(cm.value) assert str(cm.value).endswith("'error message\\n')") with pytest.raises(ipautil.CalledProcessError) as cm: ipautil.run(args, nolog=["message"]) assert cm.value.cmd == repr(args).replace("message", "XXXXXXXX") assert str(cm.value).endswith("'error XXXXXXXX\\n')") assert "message" not in str(cm.value) assert "message" not in str(cm.value.output) assert "message" not in str(cm.value.stderr) @pytest.mark.skipif(os.geteuid() != 0, reason="Must have root privileges to run this test") def test_run_runas(): """ Test run method with the runas parameter. The test executes 'id' to make sure that the process is executed with the user identity specified in runas parameter. The test is using 'ipaapi' user as it is configured when ipa-server-common package is installed. """ res = ipautil.run(['/usr/bin/id', '-u'], runas=IPAAPI_USER) assert res.returncode == 0 assert res.raw_output == b'%d\n' % IPAAPI_USER.uid res = ipautil.run(['/usr/bin/id', '-g'], runas=IPAAPI_USER) assert res.returncode == 0 assert res.raw_output == b'%d\n' % IPAAPI_USER.pgid @pytest.fixture(scope='function') def tcp_listen(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) # port 0 means the OS selects a random, unused port for the test. s.bind(('', 0)) s.listen(1) yield s.getsockname()[-1], s finally: s.close() @pytest.fixture(scope='function') def udp_listen(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # port 0 means the OS selects a random, unused port for the test. s.bind(('', 0)) yield s.getsockname()[-1], s finally: s.close() def test_check_port_bindable_tcp(tcp_listen): port, sock = tcp_listen assert not ipautil.check_port_bindable(port) assert not ipautil.check_port_bindable(port, socket.SOCK_STREAM) sock.close() assert ipautil.check_port_bindable(port) def test_check_port_bindable_udp(udp_listen): port, sock = udp_listen assert not ipautil.check_port_bindable(port, socket.SOCK_DGRAM) sock.close() assert ipautil.check_port_bindable(port, socket.SOCK_DGRAM) def test_config_replace_variables(tempdir): conffile = os.path.join(tempdir, 'test.conf') conf = textwrap.dedent(""" replaced=foo removed=gone """) expected = textwrap.dedent(""" replaced=bar addreplaced=baz """) with open(conffile, 'w') as f: f.write(conf) result = ipautil.config_replace_variables( conffile, replacevars=dict(replaced="bar", addreplaced="baz"), removevars={'removed'} ) assert result == { 'removed': 'gone', 'replaced': 'foo' } with open(conffile, 'r') as f: newconf = f.read() assert newconf == expected def test_sleeper(): start = time.monotonic() sleep = ipautil.Sleeper(sleep=0.020, timeout=0.200, raises=TimeoutError) assert sleep with pytest.raises(TimeoutError): while True: sleep() dur = time.monotonic() - start assert not sleep assert dur >= 0.2 # should finish in 0.2, accept longer time in case the system is busy assert dur < 1. start = time.monotonic() loops = 0 sleep = ipautil.Sleeper(sleep=0.020, timeout=0.200) assert sleep while True: if not sleep(): break loops += 1 dur = time.monotonic() - start assert not sleep assert dur >= 0.2 assert dur < 1. # should be 10 loops, accept 9 for slow systems assert loops in {9, 10}
20,865
Python
.py
527
32.00759
86
0.606922
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,376
test_dn.py
freeipa_freeipa/ipatests/test_ipapython/test_dn.py
import contextlib import pytest from cryptography import x509 import six from ipapython.dn import DN, RDN, AVA, str2dn, dn2str, DECODING_ERROR from ipapython import dn_ctypes if six.PY3: unicode = str def cmp(a, b): if a == b: assert not a < b assert not a > b assert not a != b assert a <= b assert a >= b return 0 elif a < b: assert not a > b assert a != b assert a <= b assert not a >= b return -1 else: assert a > b assert a != b assert not a <= b assert a >= b return 1 pytestmark = pytest.mark.tier0 def expected_class(klass, component): if klass is AVA: if component == 'self': return AVA elif klass is RDN: if component == 'self': return RDN elif component == 'AVA': return AVA elif klass is DN: if component == 'self': return DN elif component == 'AVA': return AVA elif component == 'RDN': return RDN raise ValueError("class %s with component '%s' unknown" % (klass.__name__, component)) class TestAVA: @pytest.fixture(autouse=True) def ava_setup(self): self.attr1 = 'cn' self.value1 = 'Bob' self.str_ava1 = '%s=%s' % (self.attr1, self.value1) self.ava1 = AVA(self.attr1, self.value1) self.attr2 = 'ou' self.value2 = 'People' self.str_ava2 = '%s=%s' % (self.attr2, self.value2) self.ava2 = AVA(self.attr2, self.value2) self.attr3 = 'c' self.value3 = 'US' self.str_ava3 = '%s=%s' % (self.attr3, self.value3) self.ava3 = AVA(self.attr3, self.value3) def assertExpectedClass(self, klass, obj, component): assert obj.__class__ is expected_class(klass, component) def test_create(self): # Create with attr,value pair ava1 = AVA(self.attr1, self.value1) self.assertExpectedClass(AVA, ava1, 'self') assert ava1 == self.ava1 # Create with "attr=value" string ava1 = AVA(self.str_ava1) self.assertExpectedClass(AVA, ava1, 'self') assert ava1 == self.ava1 # Create with tuple (attr, value) ava1 = AVA((self.attr1, self.value1)) self.assertExpectedClass(AVA, ava1, 'self') assert ava1 == self.ava1 # Create with list [attr, value] ava1 = AVA([self.attr1, self.value1]) self.assertExpectedClass(AVA, ava1, 'self') assert ava1 == self.ava1 # Create with no args should fail with pytest.raises(TypeError): AVA() # Create with more than 3 args should fail with pytest.raises(TypeError): AVA(self.attr1, self.value1, self.attr1, self.attr1) # Create with 1 arg which is not string should fail with pytest.raises(TypeError): AVA(1) # Create with malformed AVA string should fail with pytest.raises(ValueError): AVA("cn") # Create with non-string parameters, should convert ava1 = AVA(1, self.value1) self.assertExpectedClass(AVA, ava1, 'self') assert ava1.attr == u'1' ava1 = AVA((1, self.value1)) self.assertExpectedClass(AVA, ava1, 'self') assert ava1.attr == u'1' ava1 = AVA(self.attr1, 1) self.assertExpectedClass(AVA, ava1, 'self') assert ava1.value == u'1' ava1 = AVA((self.attr1, 1)) self.assertExpectedClass(AVA, ava1, 'self') assert ava1.value == u'1' def test_indexing(self): ava1 = AVA(self.ava1) assert ava1[self.attr1] == self.value1 assert ava1[0] == self.attr1 assert ava1[1] == self.value1 with pytest.raises(KeyError): ava1['foo'] # pylint: disable=pointless-statement with pytest.raises(KeyError): ava1[3] # pylint: disable=pointless-statement def test_properties(self): ava1 = AVA(self.ava1) assert ava1.attr == self.attr1 assert isinstance(ava1.attr, unicode) assert ava1.value == self.value1 assert isinstance(ava1.value, unicode) def test_str(self): ava1 = AVA(self.ava1) assert str(ava1) == self.str_ava1 assert isinstance(str(ava1), str) def test_cmp(self): # Equality ava1 = AVA(self.attr1, self.value1) assert ava1 == self.ava1 assert ava1 == self.ava1 assert ava1 == self.str_ava1 assert ava1 == self.str_ava1 result = cmp(ava1, self.ava1) assert result == 0 # Upper case attr should still be equal ava1 = AVA(self.attr1.upper(), self.value1) assert ava1.attr != self.attr1 assert ava1.value == self.value1 assert ava1 == self.ava1 assert ava1 == self.ava1 result = cmp(ava1, self.ava1) assert result == 0 # Upper case value should still be equal ava1 = AVA(self.attr1, self.value1.upper()) assert ava1.attr == self.attr1 assert ava1.value != self.value1 assert ava1 == self.ava1 assert ava1 == self.ava1 result = cmp(ava1, self.ava1) assert result == 0 # Make ava1's attr greater with pytest.raises(AttributeError): ava1.attr = self.attr1 + "1" ava1 = AVA(self.attr1 + "1", self.value1.upper()) assert ava1 != self.ava1 assert ava1 != self.ava1 result = cmp(ava1, self.ava1) assert result == 1 result = cmp(self.ava1, ava1) assert result == -1 # Reset ava1's attr, should be equal again with pytest.raises(AttributeError): ava1.attr = self.attr1 ava1 = AVA(self.attr1, self.value1.upper()) result = cmp(ava1, self.ava1) assert result == 0 # Make ava1's value greater # attr will be equal, this tests secondary comparision component with pytest.raises(AttributeError): ava1.value = self.value1 + "1" ava1 = AVA(self.attr1, self.value1 + "1") result = cmp(ava1, self.ava1) assert result == 1 result = cmp(self.ava1, ava1) assert result == -1 def test_hashing(self): # create AVA's that are equal but differ in case ava1 = AVA((self.attr1.lower(), self.value1.upper())) ava2 = AVA((self.attr1.upper(), self.value1.lower())) # AVAs that are equal should hash to the same value. assert ava1 == ava2 assert hash(ava1) == hash(ava2) # Different AVA objects with the same value should # map to 1 common key and 1 member in a set. The key and # member are based on the object's value. ava1_a = AVA(self.ava1) ava1_b = AVA(self.ava1) ava2_a = AVA(self.ava2) ava2_b = AVA(self.ava2) ava3_a = AVA(self.ava3) ava3_b = AVA(self.ava3) assert ava1_a == ava1_b assert ava2_a == ava2_b assert ava3_a == ava3_b d = dict() s = set() d[ava1_a] = str(ava1_a) d[ava1_b] = str(ava1_b) d[ava2_a] = str(ava2_a) d[ava2_b] = str(ava2_b) s.add(ava1_a) s.add(ava1_b) s.add(ava2_a) s.add(ava2_b) assert len(d) == 2 assert len(s) == 2 assert sorted(d) == sorted([ava1_a, ava2_a]) assert sorted(s) == sorted([ava1_a, ava2_a]) assert ava1_a in d assert ava1_b in d assert ava2_a in d assert ava2_b in d assert ava3_a not in d assert ava3_b not in d assert ava1_a in s assert ava1_b in s assert ava2_a in s assert ava2_b in s assert ava3_a not in s assert ava3_b not in s class TestRDN: @pytest.fixture(autouse=True) def rdn_setup(self): # ava1 must sort before ava2 self.attr1 = 'cn' self.value1 = 'Bob' self.str_ava1 = '%s=%s' % (self.attr1, self.value1) self.ava1 = AVA(self.attr1, self.value1) self.str_rdn1 = '%s=%s' % (self.attr1, self.value1) self.rdn1 = RDN((self.attr1, self.value1)) self.attr2 = 'ou' self.value2 = 'people' self.str_ava2 = '%s=%s' % (self.attr2, self.value2) self.ava2 = AVA(self.attr2, self.value2) self.str_rdn2 = '%s=%s' % (self.attr2, self.value2) self.rdn2 = RDN((self.attr2, self.value2)) self.str_ava3 = '%s=%s+%s=%s' % (self.attr1, self.value1, self.attr2, self.value2) self.str_rdn3 = '%s=%s+%s=%s' % (self.attr1, self.value1, self.attr2, self.value2) self.rdn3 = RDN(self.ava1, self.ava2) def assertExpectedClass(self, klass, obj, component): assert obj.__class__ is expected_class(klass, component) def test_create(self): # Create with single attr,value pair rdn1 = RDN((self.attr1, self.value1)) assert len(rdn1) == 1 assert rdn1 == self.rdn1 self.assertExpectedClass(RDN, rdn1, 'self') for i in range(0, len(rdn1)): self.assertExpectedClass(RDN, rdn1[i], 'AVA') assert rdn1[0] == self.ava1 # Create with multiple attr,value pairs rdn3 = RDN((self.attr1, self.value1), (self.attr2, self.value2)) assert len(rdn3) == 2 assert rdn3 == self.rdn3 self.assertExpectedClass(RDN, rdn3, 'self') for i in range(0, len(rdn3)): self.assertExpectedClass(RDN, rdn3[i], 'AVA') assert rdn3[0] == self.ava1 assert rdn3[1] == self.ava2 # Create with multiple attr,value pairs passed as lists rdn3 = RDN([self.attr1, self.value1], [self.attr2, self.value2]) assert len(rdn3) == 2 assert rdn3 == self.rdn3 self.assertExpectedClass(RDN, rdn3, 'self') for i in range(0, len(rdn3)): self.assertExpectedClass(RDN, rdn3[i], 'AVA') assert rdn3[0] == self.ava1 assert rdn3[1] == self.ava2 # Create with multiple attr,value pairs but reverse # constructor parameter ordering. RDN canonical ordering # should remain the same rdn3 = RDN((self.attr2, self.value2), (self.attr1, self.value1)) assert len(rdn3) == 2 assert rdn3 == self.rdn3 self.assertExpectedClass(RDN, rdn3, 'self') for i in range(0, len(rdn3)): self.assertExpectedClass(RDN, rdn3[i], 'AVA') assert rdn3[0] == self.ava1 assert rdn3[1] == self.ava2 # Create with single AVA object rdn1 = RDN(self.ava1) assert len(rdn1) == 1 assert rdn1 == self.rdn1 self.assertExpectedClass(RDN, rdn1, 'self') for i in range(0, len(rdn1)): self.assertExpectedClass(RDN, rdn1[i], 'AVA') assert rdn1[0] == self.ava1 # Create with multiple AVA objects rdn3 = RDN(self.ava1, self.ava2) assert len(rdn3) == 2 assert rdn3 == self.rdn3 self.assertExpectedClass(RDN, rdn3, 'self') for i in range(0, len(rdn3)): self.assertExpectedClass(RDN, rdn3[i], 'AVA') assert rdn3[0] == self.ava1 assert rdn3[1] == self.ava2 # Create with multiple AVA objects but reverse constructor # parameter ordering. RDN canonical ordering should remain # the same rdn3 = RDN(self.ava2, self.ava1) assert len(rdn3) == 2 assert rdn3 == self.rdn3 self.assertExpectedClass(RDN, rdn3, 'self') for i in range(0, len(rdn3)): self.assertExpectedClass(RDN, rdn3[i], 'AVA') assert rdn3[0] == self.ava1 assert rdn3[1] == self.ava2 # Create with single string with 1 AVA rdn1 = RDN(self.str_rdn1) assert len(rdn1) == 1 assert rdn1 == self.rdn1 self.assertExpectedClass(RDN, rdn1, 'self') for i in range(0, len(rdn1)): self.assertExpectedClass(RDN, rdn1[i], 'AVA') assert rdn1[0] == self.ava1 # Create with single string with 2 AVA's rdn3 = RDN(self.str_rdn3) assert len(rdn3) == 2 assert rdn3 == self.rdn3 self.assertExpectedClass(RDN, rdn3, 'self') for i in range(0, len(rdn3)): self.assertExpectedClass(RDN, rdn3[i], 'AVA') assert rdn3[0] == self.ava1 assert rdn3[1] == self.ava2 def test_properties(self): rdn1 = RDN(self.rdn1) rdn2 = RDN(self.rdn2) rdn3 = RDN(self.rdn3) assert rdn1.attr == self.attr1 assert isinstance(rdn1.attr, unicode) assert rdn1.value == self.value1 assert isinstance(rdn1.value, unicode) assert rdn2.attr == self.attr2 assert isinstance(rdn2.attr, unicode) assert rdn2.value == self.value2 assert isinstance(rdn2.value, unicode) assert rdn3.attr == self.attr1 assert isinstance(rdn3.attr, unicode) assert rdn3.value == self.value1 assert isinstance(rdn3.value, unicode) def test_str(self): rdn1 = RDN(self.rdn1) rdn2 = RDN(self.rdn2) rdn3 = RDN(self.rdn3) assert str(rdn1) == self.str_rdn1 assert isinstance(str(rdn1), str) assert str(rdn2) == self.str_rdn2 assert isinstance(str(rdn2), str) assert str(rdn3) == self.str_rdn3 assert isinstance(str(rdn3), str) def test_cmp(self): # Equality rdn1 = RDN((self.attr1, self.value1)) assert rdn1 == self.rdn1 assert rdn1 == self.rdn1 assert rdn1 == self.str_rdn1 assert rdn1 == self.str_rdn1 result = cmp(rdn1, self.rdn1) assert result == 0 # Make rdn1's attr greater rdn1 = RDN((self.attr1 + "1", self.value1)) assert rdn1 != self.rdn1 assert rdn1 != self.rdn1 result = cmp(rdn1, self.rdn1) assert result == 1 result = cmp(self.rdn1, rdn1) assert result == -1 # Reset rdn1's attr, should be equal again rdn1 = RDN((self.attr1, self.value1)) result = cmp(rdn1, self.rdn1) assert result == 0 # Make rdn1's value greater # attr will be equal, this tests secondary comparision component rdn1 = RDN((self.attr1, self.value1 + "1")) result = cmp(rdn1, self.rdn1) assert result == 1 result = cmp(self.rdn1, rdn1) assert result == -1 # Make sure rdn's with more ava's are greater result = cmp(self.rdn1, self.rdn3) assert result == -1 result = cmp(self.rdn3, self.rdn1) assert result == 1 def test_indexing(self): rdn1 = RDN(self.rdn1) rdn2 = RDN(self.rdn2) rdn3 = RDN(self.rdn3) assert rdn1[0] == self.ava1 assert rdn1[self.ava1.attr] == self.ava1.value with pytest.raises(KeyError): rdn1['foo'] # pylint: disable=pointless-statement assert rdn2[0] == self.ava2 assert rdn2[self.ava2.attr] == self.ava2.value with pytest.raises(KeyError): rdn2['foo'] # pylint: disable=pointless-statement assert rdn3[0] == self.ava1 assert rdn3[self.ava1.attr] == self.ava1.value assert rdn3[1] == self.ava2 assert rdn3[self.ava2.attr] == self.ava2.value with pytest.raises(KeyError): rdn3['foo'] # pylint: disable=pointless-statement assert rdn1.attr == self.attr1 assert rdn1.value == self.value1 with pytest.raises(TypeError): rdn3[1.0] # pylint: disable=pointless-statement # Slices assert rdn3[0:1] == [self.ava1] assert rdn3[:] == [self.ava1, self.ava2] def test_assignments(self): rdn = RDN((self.attr1, self.value1)) with pytest.raises(TypeError): rdn[0] = self.ava2 def test_iter(self): rdn1 = RDN(self.rdn1) rdn2 = RDN(self.rdn2) rdn3 = RDN(self.rdn3) assert len(rdn1) == 1 assert rdn1[:] == [self.ava1] for i, ava in enumerate(rdn1): if i == 0: assert ava == self.ava1 else: pytest.fail( "got iteration index %d, but len=%d" % (i, len(rdn1))) assert len(rdn2) == 1 assert rdn2[:] == [self.ava2] for i, ava in enumerate(rdn2): if i == 0: assert ava == self.ava2 else: pytest.fail( "got iteration index %d, but len=%d" % (i, len(rdn2))) assert len(rdn3) == 2 assert rdn3[:] == [self.ava1, self.ava2] for i, ava in enumerate(rdn3): if i == 0: assert ava == self.ava1 elif i == 1: assert ava == self.ava2 else: pytest.fail( "got iteration index %d, but len=%d" % (i, len(rdn3))) def test_concat(self): rdn1 = RDN((self.attr1, self.value1)) rdn2 = RDN((self.attr2, self.value2)) # in-place addtion rdn1 += rdn2 assert rdn1 == self.rdn3 self.assertExpectedClass(RDN, rdn1, 'self') for i in range(0, len(rdn1)): self.assertExpectedClass(RDN, rdn1[i], 'AVA') rdn1 = RDN((self.attr1, self.value1)) rdn1 += self.ava2 assert rdn1 == self.rdn3 self.assertExpectedClass(RDN, rdn1, 'self') for i in range(0, len(rdn1)): self.assertExpectedClass(RDN, rdn1[i], 'AVA') rdn1 = RDN((self.attr1, self.value1)) rdn1 += self.str_ava2 assert rdn1 == self.rdn3 self.assertExpectedClass(RDN, rdn1, 'self') for i in range(0, len(rdn1)): self.assertExpectedClass(RDN, rdn1[i], 'AVA') # concatenation rdn1 = RDN((self.attr1, self.value1)) rdn3 = rdn1 + rdn2 assert rdn3 == self.rdn3 self.assertExpectedClass(RDN, rdn3, 'self') for i in range(0, len(rdn3)): self.assertExpectedClass(RDN, rdn3[i], 'AVA') rdn3 = rdn1 + self.ava2 assert rdn3 == self.rdn3 self.assertExpectedClass(RDN, rdn3, 'self') for i in range(0, len(rdn3)): self.assertExpectedClass(RDN, rdn3[i], 'AVA') rdn3 = rdn1 + self.str_ava2 assert rdn3 == self.rdn3 self.assertExpectedClass(RDN, rdn3, 'self') for i in range(0, len(rdn3)): self.assertExpectedClass(RDN, rdn3[i], 'AVA') def test_hashing(self): # create RDN's that are equal but differ in case rdn1 = RDN((self.attr1.lower(), self.value1.upper())) rdn2 = RDN((self.attr1.upper(), self.value1.lower())) # RDNs that are equal should hash to the same value. assert rdn1 == rdn2 assert hash(rdn1) == hash(rdn2) class TestDN: @pytest.fixture(autouse=True) def dn_setup(self): # ava1 must sort before ava2 self.attr1 = 'cn' self.value1 = u'Bob' self.str_ava1 = '%s=%s' % (self.attr1, self.value1) self.ava1 = AVA(self.attr1, self.value1) self.str_rdn1 = '%s=%s' % (self.attr1, self.value1) self.rdn1 = RDN((self.attr1, self.value1)) self.attr2 = 'ou' self.value2 = u'people' self.str_ava2 = '%s=%s' % (self.attr2, self.value2) self.ava2 = AVA(self.attr2, self.value2) self.str_rdn2 = '%s=%s' % (self.attr2, self.value2) self.rdn2 = RDN((self.attr2, self.value2)) self.str_dn1 = self.str_rdn1 self.dn1 = DN(self.rdn1) self.str_dn2 = self.str_rdn2 self.dn2 = DN(self.rdn2) self.str_dn3 = '%s,%s' % (self.str_rdn1, self.str_rdn2) self.dn3 = DN(self.rdn1, self.rdn2) self.base_rdn1 = RDN(('dc', 'redhat')) self.base_rdn2 = RDN(('dc', 'com')) self.base_dn = DN(self.base_rdn1, self.base_rdn2) self.container_rdn1 = RDN(('cn', 'sudorules')) self.container_rdn2 = RDN(('cn', 'sudo')) self.container_dn = DN(self.container_rdn1, self.container_rdn2) self.base_container_dn = DN((self.attr1, self.value1), self.container_dn, self.base_dn) ou = x509.NameAttribute( x509.NameOID.ORGANIZATIONAL_UNIT_NAME, self.value2) cn = x509.NameAttribute(x509.NameOID.COMMON_NAME, self.value1) c = x509.NameAttribute(x509.NameOID.COUNTRY_NAME, 'AU') st = x509.NameAttribute( x509.NameOID.STATE_OR_PROVINCE_NAME, 'Queensland') self.x500name = x509.Name([ou, cn]) self.x500nameMultiRDN = x509.Name([ x509.RelativeDistinguishedName([c, st]), x509.RelativeDistinguishedName([cn]), ]) self.x500nameMultiRDN2 = x509.Name([ x509.RelativeDistinguishedName([st, c]), x509.RelativeDistinguishedName([cn]), ]) def assertExpectedClass(self, klass, obj, component): assert obj.__class__ is expected_class(klass, component) def test_create(self): # Create with single attr,value pair dn1 = DN((self.attr1, self.value1)) assert len(dn1) == 1 self.assertExpectedClass(DN, dn1, 'self') for i in range(0, len(dn1)): self.assertExpectedClass(DN, dn1[i], 'RDN') for j in range(0, len(dn1[i])): self.assertExpectedClass(DN, dn1[i][j], 'AVA') assert isinstance(dn1[0].attr, unicode) assert isinstance(dn1[0].value, unicode) assert dn1[0] == self.rdn1 # Create with single attr,value pair passed as a tuple dn1 = DN((self.attr1, self.value1)) assert len(dn1) == 1 self.assertExpectedClass(DN, dn1, 'self') for i in range(0, len(dn1)): self.assertExpectedClass(DN, dn1[i], 'RDN') for j in range(0, len(dn1[i])): self.assertExpectedClass(DN, dn1[i][j], 'AVA') assert isinstance(dn1[i].attr, unicode) assert isinstance(dn1[i].value, unicode) assert dn1[0] == self.rdn1 # Creation with multiple attr,value string pairs should fail with pytest.raises(ValueError): dn1 = DN(self.attr1, self.value1, self.attr2, self.value2) # Create with multiple attr,value pairs passed as tuples & lists dn1 = DN((self.attr1, self.value1), [self.attr2, self.value2]) assert len(dn1) == 2 self.assertExpectedClass(DN, dn1, 'self') for i in range(0, len(dn1)): self.assertExpectedClass(DN, dn1[i], 'RDN') for j in range(0, len(dn1[i])): self.assertExpectedClass(DN, dn1[i][j], 'AVA') assert isinstance(dn1[i].attr, unicode) assert isinstance(dn1[i].value, unicode) assert dn1[0] == self.rdn1 assert dn1[1] == self.rdn2 # Create with multiple attr,value pairs passed as tuple and RDN dn1 = DN((self.attr1, self.value1), RDN((self.attr2, self.value2))) assert len(dn1) == 2 self.assertExpectedClass(DN, dn1, 'self') for i in range(0, len(dn1)): self.assertExpectedClass(DN, dn1[i], 'RDN') for j in range(0, len(dn1[i])): self.assertExpectedClass(DN, dn1[i][j], 'AVA') assert isinstance(dn1[i].attr, unicode) assert isinstance(dn1[i].value, unicode) assert dn1[0] == self.rdn1 assert dn1[1] == self.rdn2 # Create with multiple attr,value pairs but reverse # constructor parameter ordering. RDN ordering should also be # reversed because DN's are a ordered sequence of RDN's dn1 = DN((self.attr2, self.value2), (self.attr1, self.value1)) assert len(dn1) == 2 self.assertExpectedClass(DN, dn1, 'self') for i in range(0, len(dn1)): self.assertExpectedClass(DN, dn1[i], 'RDN') for j in range(0, len(dn1[i])): self.assertExpectedClass(DN, dn1[i][j], 'AVA') assert isinstance(dn1[i].attr, unicode) assert isinstance(dn1[i].value, unicode) assert dn1[0] == self.rdn2 assert dn1[1] == self.rdn1 # Create with single RDN object dn1 = DN(self.rdn1) assert len(dn1) == 1 self.assertExpectedClass(DN, dn1, 'self') for i in range(0, len(dn1)): self.assertExpectedClass(DN, dn1[i], 'RDN') for j in range(0, len(dn1[i])): self.assertExpectedClass(DN, dn1[i][j], 'AVA') assert isinstance(dn1[i].attr, unicode) assert isinstance(dn1[i].value, unicode) assert dn1[0] == self.rdn1 # Create with multiple RDN objects, assure ordering is preserved. dn1 = DN(self.rdn1, self.rdn2) assert len(dn1) == 2 self.assertExpectedClass(DN, dn1, 'self') for i in range(0, len(dn1)): self.assertExpectedClass(DN, dn1[i], 'RDN') for j in range(0, len(dn1[i])): self.assertExpectedClass(DN, dn1[i][j], 'AVA') assert isinstance(dn1[i].attr, unicode) assert isinstance(dn1[i].value, unicode) assert dn1[0] == self.rdn1 assert dn1[1] == self.rdn2 # Create with multiple RDN objects in different order, assure # ordering is preserved. dn1 = DN(self.rdn2, self.rdn1) assert len(dn1) == 2 self.assertExpectedClass(DN, dn1, 'self') for i in range(0, len(dn1)): self.assertExpectedClass(DN, dn1[i], 'RDN') for j in range(0, len(dn1[i])): self.assertExpectedClass(DN, dn1[i][j], 'AVA') assert isinstance(dn1[i].attr, unicode) assert isinstance(dn1[i].value, unicode) assert dn1[0] == self.rdn2 assert dn1[1] == self.rdn1 # Create with single string with 1 RDN dn1 = DN(self.str_rdn1) assert len(dn1) == 1 self.assertExpectedClass(DN, dn1, 'self') for i in range(0, len(dn1)): self.assertExpectedClass(DN, dn1[i], 'RDN') for j in range(0, len(dn1[i])): self.assertExpectedClass(DN, dn1[i][j], 'AVA') assert isinstance(dn1[i].attr, unicode) assert isinstance(dn1[i].value, unicode) assert dn1[0] == self.rdn1 # Create with single string with 2 RDN's dn1 = DN(self.str_dn3) assert len(dn1) == 2 self.assertExpectedClass(DN, dn1, 'self') for i in range(0, len(dn1)): self.assertExpectedClass(DN, dn1[i], 'RDN') for j in range(0, len(dn1[i])): self.assertExpectedClass(DN, dn1[i][j], 'AVA') assert isinstance(dn1[i].attr, unicode) assert isinstance(dn1[i].value, unicode) assert dn1[0] == self.rdn1 assert dn1[1] == self.rdn2 # Create with a python-cryptography 'Name' dn1 = DN(self.x500name) assert len(dn1) == 2 self.assertExpectedClass(DN, dn1, 'self') for i in range(0, len(dn1)): self.assertExpectedClass(DN, dn1[i], 'RDN') for j in range(0, len(dn1[i])): self.assertExpectedClass(DN, dn1[i][j], 'AVA') assert isinstance(dn1[i].attr, unicode) assert isinstance(dn1[i].value, unicode) assert dn1[0] == self.rdn1 assert dn1[1] == self.rdn2 # Create from 'Name' with multi-valued RDN dn1 = DN(self.x500nameMultiRDN) assert len(dn1) == 2 assert len(dn1[1]) == 2 assert AVA('c', 'au') in dn1[1] assert AVA('st', 'queensland') in dn1[1] assert len(dn1[0]) == 1 assert self.ava1 in dn1[0] # Create with RDN, and 2 DN's (e.g. attr + container + base) dn1 = DN((self.attr1, self.value1), self.container_dn, self.base_dn) assert len(dn1) == 5 dn_str = ','.join([str(self.rdn1), str(self.container_rdn1), str(self.container_rdn2), str(self.base_rdn1), str(self.base_rdn2)]) assert str(dn1) == dn_str def test_str(self): dn1 = DN(self.dn1) dn2 = DN(self.dn2) dn3 = DN(self.dn3) assert str(dn1) == self.str_dn1 assert isinstance(str(dn1), str) assert str(dn2) == self.str_dn2 assert isinstance(str(dn2), str) assert str(dn3) == self.str_dn3 assert isinstance(str(dn3), str) def test_cmp(self): # Equality dn1 = DN((self.attr1, self.value1)) assert dn1 == self.dn1 assert dn1 == self.dn1 assert dn1 == self.str_dn1 assert dn1 == self.str_dn1 result = cmp(dn1, self.dn1) assert result == 0 # Make dn1's attr greater with pytest.raises(AttributeError): dn1[0].attr = self.attr1 + "1" dn1 = DN((self.attr1 + "1", self.value1)) assert dn1 != self.dn1 assert dn1 != self.dn1 result = cmp(dn1, self.dn1) assert result == 1 result = cmp(self.dn1, dn1) assert result == -1 # Reset dn1's attr, should be equal again with pytest.raises(AttributeError): dn1[0].attr = self.attr1 dn1 = DN((self.attr1, self.value1)) result = cmp(dn1, self.dn1) assert result == 0 # Make dn1's value greater # attr will be equal, this tests secondary comparision component with pytest.raises(AttributeError): dn1[0].value = self.value1 + "1" dn1 = DN((self.attr1, self.value1 + "1")) result = cmp(dn1, self.dn1) assert result == 1 result = cmp(self.dn1, dn1) assert result == -1 # Make sure dn's with more rdn's are greater result = cmp(self.dn1, self.dn3) assert result == -1 result = cmp(self.dn3, self.dn1) assert result == 1 # Test startswith, endswith container_dn = DN(self.container_dn) base_container_dn = DN(self.base_container_dn) assert base_container_dn.startswith(self.rdn1) assert base_container_dn.startswith(self.dn1) assert base_container_dn.startswith(self.dn1 + container_dn) assert not base_container_dn.startswith(self.dn2) assert not base_container_dn.startswith(self.rdn2) assert base_container_dn.startswith((self.dn1)) assert base_container_dn.startswith((self.rdn1)) assert not base_container_dn.startswith((self.rdn2)) assert base_container_dn.startswith((self.rdn2, self.rdn1)) assert base_container_dn.startswith((self.dn1, self.dn2)) assert base_container_dn.endswith(self.base_dn) assert base_container_dn.endswith(container_dn + self.base_dn) assert not base_container_dn.endswith(DN(self.base_rdn1)) assert base_container_dn.endswith(DN(self.base_rdn2)) assert base_container_dn.endswith( (DN(self.base_rdn1), DN(self.base_rdn2))) # Test "in" membership assert self.container_rdn1 in container_dn # pylint: disable=comparison-with-itself assert container_dn in container_dn assert self.base_rdn1 not in container_dn assert self.container_rdn1 in base_container_dn assert container_dn in base_container_dn assert container_dn + self.base_dn in base_container_dn assert self.dn1 + container_dn + self.base_dn in base_container_dn assert self.dn1 + container_dn + self.base_dn == base_container_dn assert self.container_rdn1 not in self.base_dn def test_eq_multi_rdn(self): dn1 = DN(self.ava1, 'ST=Queensland+C=AU') dn2 = DN(self.ava1, 'C=AU+ST=Queensland') assert dn1 == dn2 # ensure AVAs get sorted when constructing from x509.Name dn3 = DN(self.x500nameMultiRDN) dn4 = DN(self.x500nameMultiRDN2) assert dn3 == dn4 # ensure AVAs get sorted in the same way regardless of what # the DN was constructed from assert dn1 == dn3 assert dn1 == dn4 assert dn2 == dn3 assert dn2 == dn4 def test_indexing(self): dn1 = DN(self.dn1) dn2 = DN(self.dn2) dn3 = DN(self.dn3) assert dn1[0] == self.rdn1 assert dn1[self.rdn1.attr] == self.rdn1.value with pytest.raises(KeyError): dn1['foo'] # pylint: disable=pointless-statement assert dn2[0] == self.rdn2 assert dn2[self.rdn2.attr] == self.rdn2.value with pytest.raises(KeyError): dn2['foo'] # pylint: disable=pointless-statement assert dn3[0] == self.rdn1 assert dn3[self.rdn1.attr] == self.rdn1.value assert dn3[1] == self.rdn2 assert dn3[self.rdn2.attr] == self.rdn2.value with pytest.raises(KeyError): dn3['foo'] # pylint: disable=pointless-statement with pytest.raises(TypeError): dn3[1.0] # pylint: disable=pointless-statement def test_assignments(self): dn = DN('t=0,t=1,t=2,t=3,t=4,t=5,t=6,t=7,t=8,t=9') with pytest.raises(TypeError): dn[0] = RDN('t=a') with pytest.raises(TypeError): dn[0:1] = [RDN('t=a'), RDN('t=b')] def test_iter(self): dn1 = DN(self.dn1) dn2 = DN(self.dn2) dn3 = DN(self.dn3) assert len(dn1) == 1 assert dn1[:] == self.rdn1 for i, ava in enumerate(dn1): if i == 0: assert ava == self.rdn1 else: pytest.fail( "got iteration index %d, but len=%d" % (i, len(self.rdn1))) assert len(dn2) == 1 assert dn2[:] == self.rdn2 for i, ava in enumerate(dn2): if i == 0: assert ava == self.rdn2 else: pytest.fail( "got iteration index %d, but len=%d" % (i, len(self.rdn2))) assert len(dn3) == 2 assert dn3[:] == DN(self.rdn1, self.rdn2) for i, ava in enumerate(dn3): if i == 0: assert ava == self.rdn1 elif i == 1: assert ava == self.rdn2 else: pytest.fail( "got iteration index %d, but len=%d" % (i, len(dn3))) def test_concat(self): dn1 = DN((self.attr1, self.value1)) dn2 = DN([self.attr2, self.value2]) # in-place addtion dn1 += dn2 assert dn1 == self.dn3 self.assertExpectedClass(DN, dn1, 'self') for i in range(0, len(dn1)): self.assertExpectedClass(DN, dn1[i], 'RDN') for j in range(0, len(dn1[i])): self.assertExpectedClass(DN, dn1[i][j], 'AVA') dn1 = DN((self.attr1, self.value1)) dn1 += self.rdn2 assert dn1 == self.dn3 self.assertExpectedClass(DN, dn1, 'self') for i in range(0, len(dn1)): self.assertExpectedClass(DN, dn1[i], 'RDN') for j in range(0, len(dn1[i])): self.assertExpectedClass(DN, dn1[i][j], 'AVA') dn1 = DN((self.attr1, self.value1)) dn1 += self.dn2 assert dn1 == self.dn3 self.assertExpectedClass(DN, dn1, 'self') for i in range(0, len(dn1)): self.assertExpectedClass(DN, dn1[i], 'RDN') for j in range(0, len(dn1[i])): self.assertExpectedClass(DN, dn1[i][j], 'AVA') dn1 = DN((self.attr1, self.value1)) dn1 += self.str_dn2 assert dn1 == self.dn3 self.assertExpectedClass(DN, dn1, 'self') for i in range(0, len(dn1)): self.assertExpectedClass(DN, dn1[i], 'RDN') for j in range(0, len(dn1[i])): self.assertExpectedClass(DN, dn1[i][j], 'AVA') # concatenation dn1 = DN((self.attr1, self.value1)) dn3 = dn1 + dn2 assert dn3 == self.dn3 self.assertExpectedClass(DN, dn3, 'self') for i in range(0, len(dn3)): self.assertExpectedClass(DN, dn3[i], 'RDN') for j in range(0, len(dn3[i])): self.assertExpectedClass(DN, dn3[i][j], 'AVA') dn1 = DN((self.attr1, self.value1)) dn3 = dn1 + self.rdn2 assert dn3 == self.dn3 self.assertExpectedClass(DN, dn3, 'self') for i in range(0, len(dn3)): self.assertExpectedClass(DN, dn3[i], 'RDN') for j in range(0, len(dn3[i])): self.assertExpectedClass(DN, dn3[i][j], 'AVA') dn3 = dn1 + self.str_rdn2 assert dn3 == self.dn3 self.assertExpectedClass(DN, dn3, 'self') for i in range(0, len(dn3)): self.assertExpectedClass(DN, dn3[i], 'RDN') self.assertExpectedClass(DN, dn3[i][0], 'AVA') dn3 = dn1 + self.str_dn2 assert dn3 == self.dn3 self.assertExpectedClass(DN, dn3, 'self') self.assertExpectedClass(DN, dn3, 'self') for i in range(0, len(dn3)): self.assertExpectedClass(DN, dn3[i], 'RDN') for j in range(0, len(dn3[i])): self.assertExpectedClass(DN, dn3[i][j], 'AVA') dn3 = dn1 + self.dn2 assert dn3 == self.dn3 self.assertExpectedClass(DN, dn3, 'self') self.assertExpectedClass(DN, dn3, 'self') for i in range(0, len(dn3)): self.assertExpectedClass(DN, dn3[i], 'RDN') for j in range(0, len(dn3[i])): self.assertExpectedClass(DN, dn3[i][j], 'AVA') def test_find(self): # -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 dn = DN('t=0,t=1,cn=bob,t=3,t=4,t=5,cn=bob,t=7,t=8,t=9') pat = DN('cn=bob') # forward assert dn.find(pat) == 2 assert dn.find(pat, 1) == 2 assert dn.find(pat, 1, 3) == 2 assert dn.find(pat, 2, 3) == 2 assert dn.find(pat, 6) == 6 assert dn.find(pat, 7) == -1 assert dn.find(pat, 1, 2) == -1 with pytest.raises(ValueError): assert dn.index(pat, 7) == -1 with pytest.raises(ValueError): assert dn.index(pat, 1, 2) == -1 # reverse assert dn.rfind(pat) == 6 assert dn.rfind(pat, -4) == 6 assert dn.rfind(pat, 6) == 6 assert dn.rfind(pat, 6, 8) == 6 assert dn.rfind(pat, 6, 8) == 6 assert dn.rfind(pat, -8) == 6 assert dn.rfind(pat, -8, -4) == 6 assert dn.rfind(pat, -8, -5) == 2 assert dn.rfind(pat, 7) == -1 assert dn.rfind(pat, -3) == -1 with pytest.raises(ValueError): assert dn.rindex(pat, 7) == -1 with pytest.raises(ValueError): assert dn.rindex(pat, -3) == -1 def test_replace(self): # pylint: disable=no-member dn = DN('t=0,t=1,t=2,t=3,t=4,t=5,t=6,t=7,t=8,t=9') with pytest.raises(AttributeError): dn.replace # pylint: disable=pointless-statement def test_hashing(self): # create DN's that are equal but differ in case dn1 = DN((self.attr1.lower(), self.value1.upper())) dn2 = DN((self.attr1.upper(), self.value1.lower())) # DNs that are equal should hash to the same value. assert dn1 == dn2 # Good, everyone's equal, now verify their hash values assert hash(dn1) == hash(dn2) # Different DN objects with the same value should # map to 1 common key and 1 member in a set. The key and # member are based on the object's value. dn1_a = DN(self.dn1) dn1_b = DN(self.dn1) dn2_a = DN(self.dn2) dn2_b = DN(self.dn2) dn3_a = DN(self.dn3) dn3_b = DN(self.dn3) assert dn1_a == dn1_b assert dn2_a == dn2_b assert dn3_a == dn3_b d = dict() s = set() d[dn1_a] = str(dn1_a) d[dn1_b] = str(dn1_b) d[dn2_a] = str(dn2_a) d[dn2_b] = str(dn2_b) s.add(dn1_a) s.add(dn1_b) s.add(dn2_a) s.add(dn2_b) assert len(d) == 2 assert len(s) == 2 assert sorted(d) == sorted([dn1_a, dn2_a]) assert sorted(s) == sorted([dn1_a, dn2_a]) assert dn1_a in d assert dn1_b in d assert dn2_a in d assert dn2_b in d assert dn3_a not in d assert dn3_b not in d assert dn1_a in s assert dn1_b in s assert dn2_a in s assert dn2_b in s assert dn3_a not in s assert dn3_b not in s def test_x500_text(self): # null DN x500 ordering and LDAP ordering are the same nulldn = DN() assert nulldn.ldap_text() == nulldn.x500_text() # reverse a DN with a single RDN assert self.dn1.ldap_text() == self.dn1.x500_text() # reverse a DN with 2 RDNs dn3_x500 = self.dn3.x500_text() dn3_rev = DN(self.rdn2, self.rdn1) assert dn3_rev.ldap_text() == dn3_x500 # reverse a longer DN longdn_x500 = self.base_container_dn.x500_text() longdn_rev = DN(longdn_x500) l = len(self.base_container_dn) for i in range(l): assert longdn_rev[i] == self.base_container_dn[l - 1 - i] class TestEscapes: @pytest.fixture(autouse=True) def escapes_setup(self): self.privilege = 'R,W privilege' self.dn_str_hex_escape = 'cn=R\\2cW privilege,cn=privileges,cn=pbac,dc=idm,dc=lab,dc=bos,dc=redhat,dc=com' self.dn_str_backslash_escape = 'cn=R\\,W privilege,cn=privileges,cn=pbac,dc=idm,dc=lab,dc=bos,dc=redhat,dc=com' def test_escape(self): dn = DN(self.dn_str_hex_escape) assert dn['cn'] == self.privilege assert dn[0].value == self.privilege dn = DN(self.dn_str_backslash_escape) assert dn['cn'] == self.privilege assert dn[0].value == self.privilege class TestInternationalization: @pytest.fixture(autouse=True) def i18n_setup(self): # Hello in Arabic self.arabic_hello_utf8 = (b'\xd9\x85\xd9\x83\xd9\x8a\xd9\x84' + b'\xd8\xb9\x20\xd9\x85\xd8\xa7\xd9' + b'\x84\xd9\x91\xd8\xb3\xd9\x84\xd8\xa7') self.arabic_hello_unicode = self.arabic_hello_utf8.decode('utf-8') def assert_equal_utf8(self, obj, b): if six.PY2: assert str(obj) == b else: assert str(obj) == b.decode('utf-8') @contextlib.contextmanager def fail_py3(self, exception_type): try: yield except exception_type: if six.PY2: raise def test_i18n(self): actual = self.arabic_hello_unicode.encode('utf-8') expected = self.arabic_hello_utf8 assert actual == expected # AVA's # test attr i18n ava1 = AVA(self.arabic_hello_unicode, 'foo') assert isinstance(ava1.attr, unicode) assert isinstance(ava1.value, unicode) assert ava1.attr == self.arabic_hello_unicode self.assert_equal_utf8(ava1, self.arabic_hello_utf8 + b'=foo') with self.fail_py3(TypeError): ava1 = AVA(self.arabic_hello_utf8, 'foo') if six.PY2: assert isinstance(ava1.attr, unicode) assert isinstance(ava1.value, unicode) assert ava1.attr == self.arabic_hello_unicode self.assert_equal_utf8(ava1, self.arabic_hello_utf8 + b'=foo') # test value i18n ava1 = AVA('cn', self.arabic_hello_unicode) assert isinstance(ava1.attr, unicode) assert isinstance(ava1.value, unicode) assert ava1.value == self.arabic_hello_unicode self.assert_equal_utf8(ava1, b'cn=' + self.arabic_hello_utf8) with self.fail_py3(TypeError): ava1 = AVA('cn', self.arabic_hello_utf8) if six.PY2: assert isinstance(ava1.attr, unicode) assert isinstance(ava1.value, unicode) assert ava1.value == self.arabic_hello_unicode self.assert_equal_utf8(ava1, b'cn=' + self.arabic_hello_utf8) # RDN's # test attr i18n rdn1 = RDN((self.arabic_hello_unicode, 'foo')) assert isinstance(rdn1.attr, unicode) assert isinstance(rdn1.value, unicode) assert rdn1.attr == self.arabic_hello_unicode self.assert_equal_utf8(rdn1, self.arabic_hello_utf8 + b'=foo') with self.fail_py3(TypeError): rdn1 = RDN((self.arabic_hello_utf8, 'foo')) if six.PY2: assert isinstance(rdn1.attr, unicode) assert isinstance(rdn1.value, unicode) assert rdn1.attr == self.arabic_hello_unicode assert str(rdn1) == self.arabic_hello_utf8 + b'=foo' # test value i18n rdn1 = RDN(('cn', self.arabic_hello_unicode)) assert isinstance(rdn1.attr, unicode) assert isinstance(rdn1.value, unicode) assert rdn1.value == self.arabic_hello_unicode self.assert_equal_utf8(rdn1, b'cn=' + self.arabic_hello_utf8) with self.fail_py3(TypeError): rdn1 = RDN(('cn', self.arabic_hello_utf8)) if six.PY2: assert isinstance(rdn1.attr, unicode) assert isinstance(rdn1.value, unicode) assert rdn1.value == self.arabic_hello_unicode assert str(rdn1) == b'cn=' + self.arabic_hello_utf8 # DN's # test attr i18n dn1 = DN((self.arabic_hello_unicode, 'foo')) assert isinstance(dn1[0].attr, unicode) assert isinstance(dn1[0].value, unicode) assert dn1[0].attr == self.arabic_hello_unicode self.assert_equal_utf8(dn1, self.arabic_hello_utf8 + b'=foo') with self.fail_py3(TypeError): dn1 = DN((self.arabic_hello_utf8, 'foo')) if six.PY2: assert isinstance(dn1[0].attr, unicode) assert isinstance(dn1[0].value, unicode) assert dn1[0].attr == self.arabic_hello_unicode assert str(dn1) == self.arabic_hello_utf8 + b'=foo' # test value i18n dn1 = DN(('cn', self.arabic_hello_unicode)) assert isinstance(dn1[0].attr, unicode) assert isinstance(dn1[0].value, unicode) assert dn1[0].value == self.arabic_hello_unicode self.assert_equal_utf8(dn1, b'cn=' + self.arabic_hello_utf8) with self.fail_py3(TypeError): dn1 = DN(('cn', self.arabic_hello_utf8)) if six.PY2: assert isinstance(dn1[0].attr, unicode) assert isinstance(dn1[0].value, unicode) assert dn1[0].value == self.arabic_hello_unicode assert str(dn1) == b'cn=' + self.arabic_hello_utf8 # 1: LDAP_AVA_STRING # 4: LDAP_AVA_NONPRINTABLE @pytest.mark.parametrize( 'dnstring,expected', [ ('', []), ('cn=bob', [[('cn', 'bob', 1)]]), ('cn=Bob', [[('cn', 'Bob', 1)]]), (u'cn=b\xf6b', [[('cn', u'b\xf6b', 4)]]), ('cn=bob,sn=builder', [[('cn', 'bob', 1)], [('sn', 'builder', 1)]]), (u'cn=b\xf6b,sn=builder', [ [('cn', u'b\xf6b', 4)], [('sn', 'builder', 1)] ]), ('cn=bob+sn=builder', [[('cn', 'bob', 1), ('sn', 'builder', 1)]]), ('dc=ipa,dc=example', [[('dc', 'ipa', 1)], [('dc', 'example', 1)]]), ('cn=R\\,W privilege', [[('cn', 'R,W privilege', 1)]]), ] ) def test_str2dn2str(dnstring, expected): dn = str2dn(dnstring) assert dn == expected assert dn2str(dn) == dnstring assert dn_ctypes.str2dn(dnstring) == dn assert dn_ctypes.dn2str(dn) == dnstring @pytest.mark.parametrize( 'dnstring', [ 'cn', 'cn=foo,', 'cn=foo+bar', ] ) def test_str2dn_errors(dnstring): with pytest.raises(DECODING_ERROR): str2dn(dnstring) with pytest.raises(dn_ctypes.DECODING_ERROR): dn_ctypes.str2dn(dnstring) def test_dn2str_special(): dnstring = 'cn=R\\2cW privilege' dnstring2 = 'cn=R\\,W privilege' expected = [[('cn', 'R,W privilege', 1)]] dn = str2dn(dnstring) assert dn == expected assert dn2str(dn) == dnstring2 assert dn_ctypes.str2dn(dnstring) == dn assert dn_ctypes.dn2str(dn) == dnstring2
48,526
Python
.py
1,168
31.690925
119
0.573328
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,377
test_ldap_cache.py
freeipa_freeipa/ipatests/test_ipapython/test_ldap_cache.py
# # Copyright (C) 2021 FreeIPA Contributors see COPYING for license # """ Test the LDAPCache class. """ # pylint: disable=no-member from ipalib import api, errors from ipapython import ipaldap from ipapython.dn import DN import pytest def hits_and_misses(cache, hits, misses): assert cache._cache_hits == hits assert cache._cache_misses == misses @pytest.fixture(scope='class') @pytest.mark.tier1 @pytest.mark.needs_ipaapi def class_cache(request): cache = ipaldap.LDAPCache(api.env.ldap_uri) hits_and_misses(cache, 0, 0) request.cls.cache = cache request.cls.userdn = DN( 'uid=testuser', api.env.container_user, api.env.basedn ) rpcclient = api.Backend.rpcclient was_connected = rpcclient.isconnected() if not was_connected: rpcclient.connect() api.Command.user_add('testuser', givenname=u'Test', sn=u'User') yield try: api.Command.user_del('testuser') except Exception: pass try: if not was_connected: rpcclient.disconnect() except Exception: pass @pytest.mark.usefixtures('class_cache') @pytest.mark.skip_ipaclient_unittest @pytest.mark.needs_ipaapi class TestLDAPCache: def test_one(self): dn = DN('uid=notfound', api.env.container_user, api.env.basedn) try: self.cache.get_entry(dn) except errors.EmptyResult: pass assert dn in self.cache.cache exc = self.cache.cache[dn].exception assert isinstance(exc, errors.EmptyResult) hits_and_misses(self.cache, 0, 1) def test_retrieve_exception(self): dn = DN('uid=notfound', api.env.container_user, api.env.basedn) try: self.cache.get_entry(dn) except errors.EmptyResult: pass assert dn in self.cache.cache exc = self.cache.cache[dn].exception assert isinstance(exc, errors.EmptyResult) hits_and_misses(self.cache, 1, 1) def test_get_testuser(self): assert self.userdn not in self.cache.cache self.cache.get_entry(self.userdn) assert self.userdn in self.cache.cache hits_and_misses(self.cache, 1, 2) def test_get_testuser_again(self): assert self.userdn in self.cache.cache # get the user again with with no attributes requested (so all) self.cache.get_entry(self.userdn) hits_and_misses(self.cache, 2, 2) # Now get the user with a subset of cached attributes entry = self.cache.get_entry(self.userdn, ('givenname', 'sn', 'cn')) # Make sure we only got three attributes, as requested assert len(entry.items()) == 3 hits_and_misses(self.cache, 3, 2) def test_update_testuser(self): entry = self.cache.cache[self.userdn].entry try: self.cache.update_entry(entry) except errors.EmptyModlist: pass assert self.userdn not in self.cache.cache hits_and_misses(self.cache, 3, 2) def test_modify_testuser(self): self.cache.get_entry(self.userdn) entry = self.cache.cache[self.userdn].entry try: self.cache.modify_s(entry.dn, []) except errors.EmptyModlist: pass assert self.userdn not in self.cache.cache hits_and_misses(self.cache, 3, 3) def test_delete_entry(self): # We don't care if this is successful or not, just that the # cache doesn't retain the deleted entry try: self.cache.delete_entry(self.userdn) except Exception: pass assert self.userdn not in self.cache.cache hits_and_misses(self.cache, 3, 3) def test_add_entry(self): # We don't care if this is successful or not, just that the # cache doesn't get the added entry try: self.cache.add_entry(self.userdn) except Exception: pass assert self.userdn not in self.cache.cache hits_and_misses(self.cache, 3, 3) def test_clear_cache(self): self.cache.clear_cache() hits_and_misses(self.cache, 0, 0)
4,148
Python
.py
116
28.301724
76
0.649513
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,378
test_directivesetter.py
freeipa_freeipa/ipatests/test_ipapython/test_directivesetter.py
# # Copyright (C) 2017 FreeIPA Contributors. See COPYING for license # from __future__ import absolute_import import os import tempfile from ipapython import directivesetter EXAMPLE_CONFIG = [ 'foo=1\n', 'foobar=2\n', ] WHITESPACE_CONFIG = [ 'foo 1\n', 'foobar\t2\n', ] SUBSTRING_CONFIG = [ 'foobar=2\n', ] class test_set_directive_lines: def test_remove_directive(self): lines = directivesetter.set_directive_lines( False, '=', 'foo', None, EXAMPLE_CONFIG, comment="#") assert list(lines) == ['foobar=2\n'] def test_add_directive(self): lines = directivesetter.set_directive_lines( False, '=', 'baz', '4', EXAMPLE_CONFIG, comment="#") assert list(lines) == ['foo=1\n', 'foobar=2\n', 'baz=4\n'] def test_set_directive_does_not_clobber_suffix_key(self): lines = directivesetter.set_directive_lines( False, '=', 'foo', '3', EXAMPLE_CONFIG, comment="#") assert list(lines) == ['foo=3\n', 'foobar=2\n'] class test_set_directive_lines_whitespace: def test_remove_directive(self): lines = directivesetter.set_directive_lines( False, ' ', 'foo', None, WHITESPACE_CONFIG, comment="#") assert list(lines) == ['foobar\t2\n'] def test_add_directive(self): lines = directivesetter.set_directive_lines( False, ' ', 'baz', '4', WHITESPACE_CONFIG, comment="#") assert list(lines) == ['foo 1\n', 'foobar\t2\n', 'baz 4\n'] def test_set_directive_does_not_clobber_suffix_key(self): lines = directivesetter.set_directive_lines( False, ' ', 'foo', '3', WHITESPACE_CONFIG, comment="#") assert list(lines) == ['foo 3\n', 'foobar\t2\n'] def test_set_directive_with_tab(self): lines = directivesetter.set_directive_lines( False, ' ', 'foobar', '6', WHITESPACE_CONFIG, comment="#") assert list(lines) == ['foo 1\n', 'foobar 6\n'] class test_set_directive: def test_set_directive(self): """Check that set_directive writes the new data and preserves mode.""" fd, filename = tempfile.mkstemp() try: os.close(fd) stat_pre = os.stat(filename) with open(filename, 'w') as f: for line in EXAMPLE_CONFIG: f.write(line) directivesetter.set_directive( filename, 'foo', '3', False, '=', "#") stat_post = os.stat(filename) with open(filename, 'r') as f: lines = list(f) assert lines == ['foo=3\n', 'foobar=2\n'] assert stat_pre.st_mode == stat_post.st_mode assert stat_pre.st_uid == stat_post.st_uid assert stat_pre.st_gid == stat_post.st_gid finally: os.remove(filename) class test_get_directive: def test_get_directive(self, tmpdir): """Test retrieving known values from a config file""" configfile = tmpdir.join('config') configfile.write(''.join(EXAMPLE_CONFIG)) assert '1' == directivesetter.get_directive(str(configfile), 'foo', separator='=') assert '2' == directivesetter.get_directive(str(configfile), 'foobar', separator='=') assert None is directivesetter.get_directive(str(configfile), 'notfound', separator='=') def test_get_directive_substring(self, tmpdir): """Test retrieving values from a config file where there is a similar substring that is not present. """ configfile = tmpdir.join('config') configfile.write(''.join(SUBSTRING_CONFIG)) assert None is directivesetter.get_directive(str(configfile), 'foo', separator='=') assert '2' == directivesetter.get_directive(str(configfile), 'foobar', separator='=') def test_get_directive_none(self, tmpdir): """Test retrieving a value from a config file where the directive is None. i.e. don't fail. """ configfile = tmpdir.join('config') configfile.write(''.join(EXAMPLE_CONFIG)) assert None is directivesetter.get_directive(str(configfile), None, separator='=') class test_get_directive_whitespace: def test_get_directive(self, tmpdir): configfile = tmpdir.join('config') configfile.write(''.join(WHITESPACE_CONFIG)) assert '1' == directivesetter.get_directive(str(configfile), 'foo') assert '2' == directivesetter.get_directive(str(configfile), 'foobar') def test_directivesetter(tempdir): filename = os.path.join(tempdir, 'example.conf') with open(filename, 'w') as f: for line in EXAMPLE_CONFIG: f.write(line) ds = directivesetter.DirectiveSetter(filename) assert ds.lines is None with ds: assert ds.lines == EXAMPLE_CONFIG ds.set('foo', '3') # quoted, space separated, doesn't change 'foo=' ds.set('foobar', None, separator='=') # remove ds.set('baz', '4', False, '=') # add ds.setitems([ ('list1', 'value1'), ('list2', 'value2'), ]) ds.setitems({ 'dict1': 'value1', 'dict2': 'value2', }) with open(filename, 'r') as f: lines = list(f) assert lines == [ 'foo=1\n', 'foo "3"\n', 'baz=4\n', 'list1 "value1"\n', 'list2 "value2"\n', 'dict1 "value1"\n', 'dict2 "value2"\n', ] with directivesetter.DirectiveSetter(filename, True, '=') as ds: ds.set('foo', '4') # doesn't change 'foo ' with open(filename, 'r') as f: lines = list(f) assert lines == [ 'foo="4"\n', 'foo "3"\n', 'baz=4\n', 'list1 "value1"\n', 'list2 "value2"\n', 'dict1 "value1"\n', 'dict2 "value2"\n', ]
6,576
Python
.py
156
29.769231
78
0.526959
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,379
test_trust.py
freeipa_freeipa/ipatests/test_webui/test_trust.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Trust tests """ import pytest import ipatests.test_webui.data_group as group import ipatests.test_webui.data_idviews as idview from ipatests.test_webui.ui_driver import UI_driver from ipatests.test_webui.ui_driver import screenshot from ipatests.test_webui.task_range import TRUSTED_ID_RANGE, range_tasks ENTITY = 'trust' CONFIG_ENTITY = 'trustconfig' DEFAULT_TRUST_VIEW = 'Default Trust View' CONFIG_DATA = { 'mod': [ ['combobox', 'ipantfallbackprimarygroup', 'admins'], ] } CONFIG_DATA2 = { 'mod': [ ['combobox', 'ipantfallbackprimarygroup', 'Default SMB Group'] ] } @pytest.mark.tier1 class trust_tasks(UI_driver): @pytest.fixture(autouse=True) def trusttasks_setup(self, ui_driver_fsetup): pass def get_data(self, add_data=None): domain = self.config.get('ad_domain') if not add_data: add_data = self.get_add_data() data = { 'pkey': domain, 'add': add_data, 'mod': [ ('multivalued', 'ipantsidblacklistincoming', [ ('del', 'S-1-5-18'), ('add', 'S-1-5-21'), ]), ('multivalued', 'ipantsidblacklistoutgoing', [ ('del', 'S-1-5-18'), ('add', 'S-1-5-21'), ]), ], } return data def get_add_data(self, range_type=None, base_id=None, range_size=None): domain = self.config.get('ad_domain') admin = self.config.get('ad_admin') psw = self.config.get('ad_password') add = [ ('textbox', 'realm_server', domain), ('textbox', 'realm_admin', admin), ('password', 'realm_passwd', psw), ] if range_type: add.append(('radio', 'range_type', range_type)) if base_id: add.append(('textbox', 'base_id', base_id)) if range_size: add.append(('textbox', 'range_size', range_size)) return add def get_range_name(self): domain = self.config.get('ad_domain') return domain.upper() + '_id_range' @pytest.mark.tier1 class test_trust(trust_tasks): request_timeout = 120 @pytest.fixture(autouse=True) def trust_setup(self, trusttasks_setup): if not self.has_trusts(): self.skip('Trusts not configured') @screenshot def test_crud(self): """ Basic basic CRUD: trust Test establishing trust by using Windows admin credentials """ self.init_app() data = self.get_data() self.navigate_to_entity('idrange') self.delete_record(self.get_range_name()) self.basic_crud(ENTITY, data) self.navigate_to_entity('idrange') self.delete_record(self.get_range_name()) @screenshot def test_range_types(self): self.init_app() r_tasks = range_tasks() r_tasks.driver = self.driver r_tasks.config = self.config r_tasks.get_shifts() range_form = r_tasks.get_add_form_data('') base_id = range_form.base_id range_size = range_form.size range_pkey = self.get_range_name() column = 'iparangetype' self.navigate_to_entity('idrange') self.delete_record(range_pkey) add = self.get_add_data('ipa-ad-trust', base_id, range_size) data = self.get_data(add_data=add) self.add_record(ENTITY, data, delete=True) self.navigate_to_entity('idrange') self.assert_record_value('Active Directory domain range', range_pkey, column) self.delete_record(range_pkey) add = self.get_add_data('ipa-ad-trust-posix', base_id, range_size) data = self.get_data(add_data=add) self.add_record(ENTITY, data, delete=True) self.navigate_to_entity('idrange') self.assert_record_value('Active Directory trust range with POSIX attributes', range_pkey, column) self.delete_record(range_pkey) @screenshot def test_range_auto_private_groups(self): self.init_app() r_tasks = range_tasks() r_tasks.driver = self.driver r_tasks.config = self.config r_tasks.get_shifts() trust_data = self.get_data() self.add_record(ENTITY, trust_data, navigate=True) range_pkeys = [] try: for auto_private_groups in ['true', 'false', 'hybrid']: pkey = 'itest-range-apg-{}'.format(auto_private_groups) form_data = r_tasks.get_add_form_data( pkey, range_type=TRUSTED_ID_RANGE, domain=trust_data['pkey'], auto_private_groups=auto_private_groups ) range_data = r_tasks.get_data(pkey, form_data=form_data) self.add_record('idrange', range_data, navigate=True) range_pkeys.append(pkey) finally: self.navigate_to_entity(ENTITY) self.delete_record(trust_data['pkey']) self.navigate_to_entity('idrange') self.delete_record(range_pkeys) @screenshot def test_config_mod(self): self.init_app() self.navigate_to_entity(CONFIG_ENTITY) self.mod_record(CONFIG_ENTITY, CONFIG_DATA) self.mod_record(CONFIG_ENTITY, CONFIG_DATA2) @screenshot def test_group_member_idoverrideuser(self): self.init_app() # Create new trust data = self.get_data() self.add_record(ENTITY, data) # Create an user ID override ad_domain = self.config.get('ad_domain') ad_admin = self.config.get('ad_admin') idoverrideuser_pkey = '{}@{}'.format(ad_admin, ad_domain).lower() self.navigate_to_record(DEFAULT_TRUST_VIEW, entity=idview.ENTITY) self.add_record(idview.ENTITY, { 'pkey': idoverrideuser_pkey, 'add': [ ('textbox', 'ipaanchoruuid_default', idoverrideuser_pkey), ], }, facet='idoverrideuser') # Create new group and add the user ID override there self.navigate_to_entity(group.ENTITY) self.add_record(group.ENTITY, group.DATA) self.navigate_to_record(group.PKEY) self.add_associations([idoverrideuser_pkey], facet='member_idoverrideuser', delete=True) # Clean up data self.navigate_to_entity(group.ENTITY) self.delete_record(group.PKEY) self.navigate_to_record(DEFAULT_TRUST_VIEW, entity=idview.ENTITY) self.delete_record(idoverrideuser_pkey) self.navigate_to_entity(ENTITY) self.delete_record(ad_domain)
7,505
Python
.py
192
30.395833
106
0.614093
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,380
data_selfservice.py
freeipa_freeipa/ipatests/test_webui/data_selfservice.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # ENTITY = 'selfservice' PKEY = 'itest-selfservice-rule' DATA = { 'pkey': PKEY, 'add': [ ('textbox', 'aciname', PKEY), ('checkbox', 'attrs', 'audio'), ('checkbox', 'attrs', 'businesscategory'), ], 'mod': [ ('checkbox', 'attrs', 'businesscategory'), ], } PKEY1 = 'itest-selfservice-rule1' DATA1 = { 'pkey': PKEY1, 'add': [ ('textbox', 'aciname', PKEY1), ('checkbox', 'attrs', 'businesscategory'), ], 'mod': [ ('checkbox', 'attrs', 'businesscategory'), ('checkbox', 'attrs', 'departmentnumber'), ('checkbox', 'attrs', 'destinationindicator'), ], } DATA2 = [ ('checkbox', 'attrs', 'businesscategory'), ('checkbox', 'attrs', 'departmentnumber'), ('checkbox', 'attrs', 'destinationindicator'), ] DATA_ALL = { 'pkey': PKEY, 'add': [ ('textbox', 'aciname', PKEY), ('checkbox', 'attrs', 'audio'), ('checkbox', 'attrs', 'businesscategory'), ('checkbox', 'attrs', 'carlicense'), ('checkbox', 'attrs', 'cn'), ('checkbox', 'attrs', 'departmentnumber'), ('checkbox', 'attrs', 'description'), ('checkbox', 'attrs', 'destinationindicator'), ('checkbox', 'attrs', 'displayname'), ('checkbox', 'attrs', 'employeenumber'), ('checkbox', 'attrs', 'employeetype'), ('checkbox', 'attrs', 'facsimiletelephonenumber'), ('checkbox', 'attrs', 'gecos'), ('checkbox', 'attrs', 'gidnumber'), ('checkbox', 'attrs', 'givenname'), ('checkbox', 'attrs', 'homedirectory'), ('checkbox', 'attrs', 'homephone'), ('checkbox', 'attrs', 'homepostaladdress'), ('checkbox', 'attrs', 'inetuserhttpurl'), ('checkbox', 'attrs', 'inetuserstatus'), ('checkbox', 'attrs', 'initials'), ('checkbox', 'attrs', 'internationalisdnnumber'), ('checkbox', 'attrs', 'ipacertmapdata'), ('checkbox', 'attrs', 'ipakrbauthzdata'), ('checkbox', 'attrs', 'ipasshpubkey'), ('checkbox', 'attrs', 'ipatokenradiusconfiglink'), ('checkbox', 'attrs', 'ipatokenradiususername'), ('checkbox', 'attrs', 'ipauniqueid'), ('checkbox', 'attrs', 'ipauserauthtype'), ('checkbox', 'attrs', 'jpegphoto'), ('checkbox', 'attrs', 'krballowedtodelegateto'), ('checkbox', 'attrs', 'krbcanonicalname'), ('checkbox', 'attrs', 'krbextradata'), ('checkbox', 'attrs', 'krblastadminunlock'), ('checkbox', 'attrs', 'krblastfailedauth'), ('checkbox', 'attrs', 'krblastpwdchange'), ('checkbox', 'attrs', 'krblastsuccessfulauth'), ('checkbox', 'attrs', 'krbloginfailedcount'), ('checkbox', 'attrs', 'krbmaxrenewableage'), ('checkbox', 'attrs', 'krbmaxticketlife'), ('checkbox', 'attrs', 'krbpasswordexpiration'), ('checkbox', 'attrs', 'krbprincipalaliases'), ('checkbox', 'attrs', 'krbprincipalauthind'), ('checkbox', 'attrs', 'krbprincipalexpiration'), ('checkbox', 'attrs', 'krbprincipalkey'), ('checkbox', 'attrs', 'krbprincipalname'), ('checkbox', 'attrs', 'krbprincipaltype'), ('checkbox', 'attrs', 'krbpwdhistory'), ('checkbox', 'attrs', 'krbpwdpolicyreference'), ('checkbox', 'attrs', 'krbticketflags'), ('checkbox', 'attrs', 'krbticketpolicyreference'), ('checkbox', 'attrs', 'krbupenabled'), ('checkbox', 'attrs', 'l'), ('checkbox', 'attrs', 'labeleduri'), ('checkbox', 'attrs', 'loginshell'), ('checkbox', 'attrs', 'mail'), ('checkbox', 'attrs', 'manager'), ('checkbox', 'attrs', 'memberof'), ('checkbox', 'attrs', 'mepmanagedentry'), ('checkbox', 'attrs', 'mobile'), ('checkbox', 'attrs', 'o'), ('checkbox', 'attrs', 'objectclass'), ('checkbox', 'attrs', 'ou'), ('checkbox', 'attrs', 'pager'), ('checkbox', 'attrs', 'photo'), ('checkbox', 'attrs', 'physicaldeliveryofficename'), ('checkbox', 'attrs', 'postaladdress'), ('checkbox', 'attrs', 'postalcode'), ('checkbox', 'attrs', 'postofficebox'), ('checkbox', 'attrs', 'preferreddeliverymethod'), ('checkbox', 'attrs', 'preferredlanguage'), ('checkbox', 'attrs', 'registeredaddress'), ('checkbox', 'attrs', 'roomnumber'), ('checkbox', 'attrs', 'secretary'), ('checkbox', 'attrs', 'seealso'), ('checkbox', 'attrs', 'sn'), ('checkbox', 'attrs', 'st'), ('checkbox', 'attrs', 'street'), ('checkbox', 'attrs', 'telephonenumber'), ('checkbox', 'attrs', 'teletexterminalidentifier'), ('checkbox', 'attrs', 'telexnumber'), ('checkbox', 'attrs', 'title'), ('checkbox', 'attrs', 'uid'), ('checkbox', 'attrs', 'uidnumber'), ('checkbox', 'attrs', 'usercertificate'), ('checkbox', 'attrs', 'userclass'), ('checkbox', 'attrs', 'userpassword'), ('checkbox', 'attrs', 'userpkcs12'), ('checkbox', 'attrs', 'usersmimecertificate'), ('checkbox', 'attrs', 'x121address'), ('checkbox', 'attrs', 'x500uniqueidentifier'), ], }
5,306
Python
.py
130
33.138462
66
0.554911
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,381
test_user.py
freeipa_freeipa/ipatests/test_webui/test_user.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ User tests """ from ipatests.test_webui.crypto_utils import generate_csr from ipatests.test_webui.ui_driver import UI_driver from ipatests.test_webui.ui_driver import screenshot import ipatests.test_webui.data_user as user import ipatests.test_webui.data_group as group import ipatests.test_webui.data_netgroup as netgroup import ipatests.test_webui.data_hbac as hbac import ipatests.test_webui.data_pwpolicy as pwpolicy import ipatests.test_webui.test_rbac as rbac import ipatests.test_webui.data_sudo as sudo import pytest try: from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains except ImportError: pass EMPTY_MOD = 'no modifications to be performed' USR_EXIST = 'user with name "{}" already exists' USR_ADDED = 'User successfully added' INVALID_SSH_KEY = "invalid 'sshpubkey': invalid SSH public key" INV_FIRSTNAME = ("invalid 'first': Leading and trailing spaces are " "not allowed") FIELD_REQ = 'Required field' ERR_INCLUDE = 'may only include letters, numbers, _, -, . and $' ERR_MISMATCH = 'Passwords must match' ERR_ADMIN_DISABLE = ('admin cannot be deleted or disabled because ' 'it is the last member of group admins') ERR_ADMIN_DEL = ('user admin cannot be deleted/modified: privileged user') USR_EXIST = 'user with name "{}" already exists' ENTRY_EXIST = 'This entry already exists' ACTIVE_ERR = 'active user with name "{}" already exists' DISABLED = 'This entry is already disabled' LONG_LOGIN = "invalid 'login': can be at most 32 characters" @pytest.mark.tier1 class user_tasks(UI_driver): def load_file(self, path): with open(path, 'r') as file_d: content = file_d.read() return content def create_email_addr(self, pkey): """ Piece an email address together from hostname due possible different DNS setup """ domain = '.'.join(self.config.get('ipa_server').split('.')[1:]) return '{}@{}'.format(pkey, domain) def add_default_email_for_validation(self, data): """ E-mail is generated automatically and we do not know domain yet in data_user so in order to validate all mail fields we need to get it there. """ mail = self.create_email_addr(user.DATA.get('pkey')) for ele in data['mod_v']: if 'mail' in ele: ele[2].append(mail) return data def assert_user_auth_type(self, auth_type, enabled=True): """ Check if provided auth type is enabled or disabled for the user :param auth_type: one of password, radius, otp, pkinit, hardened, idp or passkey :param enabled: check if enabled if True, check for disabled if False """ s_checkbox = 'div[name="ipauserauthtype"] input[value="{}"]'.format( auth_type) checkbox = self.find(s_checkbox, By.CSS_SELECTOR, strict=True) assert checkbox.is_selected() == enabled def add_user_auth_type(self, auth_type, save=False): """ Select user auth type :param auth_type: one of password, radius, otp, pkinit, hardened, idp or passkey """ s_checkbox = 'div[name="ipauserauthtype"] input[value="{}"]'.format( auth_type) checkbox = self.find(s_checkbox, By.CSS_SELECTOR, strict=True) if not checkbox.is_selected(): checkbox.click() if save: self.facet_button_click('save') @pytest.mark.tier1 class test_user(user_tasks): @screenshot def test_crud(self): """ Basic CRUD: user """ self.init_app() data = self.add_default_email_for_validation(user.DATA) self.basic_crud(user.ENTITY, data) @screenshot def test_associations(self): """ User direct associations """ self.init_app() # prepare - add user, group, netgroup, role, hbac rule, sudo rule # --------------------------------------------------------------- self.add_record(user.ENTITY, user.DATA, navigate=False) self.add_record(group.ENTITY, group.DATA) self.add_record(netgroup.ENTITY, netgroup.DATA) self.add_record(rbac.ROLE_ENTITY, rbac.ROLE_DATA) self.add_record(hbac.RULE_ENTITY, hbac.RULE_DATA) self.add_record(sudo.RULE_ENTITY, sudo.RULE_DATA) # add & remove associations # ------------------------- self.navigate_to_entity(user.ENTITY) self.navigate_to_record(user.PKEY) self.add_associations([group.PKEY, 'editors'], facet='memberof_group', delete=True) self.add_associations([netgroup.PKEY], facet='memberof_netgroup', delete=True) self.add_associations([rbac.ROLE_PKEY], facet='memberof_role', delete=True) self.add_associations([hbac.RULE_PKEY], facet='memberof_hbacrule', delete=True) self.add_associations([sudo.RULE_PKEY], facet='memberof_sudorule', delete=True) # cleanup # ------- self.delete(user.ENTITY, [user.DATA]) self.delete(group.ENTITY, [group.DATA]) self.delete(netgroup.ENTITY, [netgroup.DATA]) self.delete(rbac.ROLE_ENTITY, [rbac.ROLE_DATA]) self.delete(hbac.RULE_ENTITY, [hbac.RULE_DATA]) self.delete(sudo.RULE_ENTITY, [sudo.RULE_DATA]) @screenshot def test_indirect_associations(self): """ User indirect associations """ self.init_app() # add # --- self.add_record(user.ENTITY, user.DATA, navigate=False) self.add_record(group.ENTITY, group.DATA) self.navigate_to_record(group.PKEY) self.add_associations([user.PKEY]) self.add_record(group.ENTITY, group.DATA2) self.navigate_to_record(group.PKEY2) self.add_associations([group.PKEY], facet='member_group') self.add_record(netgroup.ENTITY, netgroup.DATA) self.navigate_to_record(netgroup.PKEY) self.add_table_associations('memberuser_group', [group.PKEY2]) self.add_record(rbac.ROLE_ENTITY, rbac.ROLE_DATA) self.navigate_to_record(rbac.ROLE_PKEY) self.add_associations([group.PKEY2], facet='member_group') self.add_record(hbac.RULE_ENTITY, hbac.RULE_DATA) self.navigate_to_record(hbac.RULE_PKEY) self.add_table_associations('memberuser_group', [group.PKEY2]) self.add_record(sudo.RULE_ENTITY, sudo.RULE_DATA) self.navigate_to_record(sudo.RULE_PKEY) self.add_table_associations('memberuser_group', [group.PKEY2]) # check indirect associations # --------------------------- self.navigate_to_entity(user.ENTITY, 'search') self.navigate_to_record(user.PKEY) self.assert_indirect_record(group.PKEY2, user.ENTITY, 'memberof_group') self.assert_indirect_record(netgroup.PKEY, user.ENTITY, 'memberof_netgroup') self.assert_indirect_record(rbac.ROLE_PKEY, user.ENTITY, 'memberof_role') self.assert_indirect_record(hbac.RULE_PKEY, user.ENTITY, 'memberof_hbacrule') self.assert_indirect_record(sudo.RULE_PKEY, user.ENTITY, 'memberof_sudorule') # cleanup # ------- self.delete(user.ENTITY, [user.DATA]) self.delete(group.ENTITY, [group.DATA, group.DATA2]) self.delete(netgroup.ENTITY, [netgroup.DATA]) self.delete(rbac.ROLE_ENTITY, [rbac.ROLE_DATA]) self.delete(hbac.RULE_ENTITY, [hbac.RULE_DATA]) self.delete(sudo.RULE_ENTITY, [sudo.RULE_DATA]) @screenshot def test_actions(self): """ Test user actions """ self.init_app() self.add_record(user.ENTITY, user.DATA, navigate=False) self.navigate_to_record(user.PKEY) self.disable_action() self.enable_action() # reset password pwd = self.config.get('ipa_password') self.reset_password_action(pwd) self.assert_text_field('has_password', '******') # unlock option should be disabled for new user self.assert_action_list_action('unlock', enabled=False) # delete self.delete_action(user.ENTITY, user.PKEY, action='delete_active_user') @screenshot def test_certificates(self): """ Test user certificate actions Requires to have CA installed. """ if not self.has_ca(): self.skip('CA is not configured') self.init_app() cert_widget_sel = "div.certificate-widget" self.add_record(user.ENTITY, user.DATA) self.wait() self.close_notifications() self.navigate_to_record(user.PKEY) # cert request csr = generate_csr(user.PKEY, False) self.action_list_action('request_cert', confirm=False) self.wait(seconds=2) self.assert_dialog() self.fill_text("textarea[name='csr']", csr) self.dialog_button_click('issue') self.wait_for_request(n=2, d=3) self.assert_visible(cert_widget_sel) # cert view self.action_list_action('view', confirm=False, parents_css_sel=cert_widget_sel) self.assert_dialog() self.dialog_button_click('close') # cert get self.action_list_action('get', confirm=False, parents_css_sel=cert_widget_sel) self.assert_dialog() # check that the textarea is not empty self.assert_empty_value('textarea.certificate', negative=True) self.dialog_button_click('close') # cert download - we can only try to click the download action self.action_list_action('download', confirm=False, parents_css_sel=cert_widget_sel) # check that revoke action is enabled self.assert_action_list_action('revoke', parents_css_sel=cert_widget_sel, facet_actions=False) # check that remove_hold action is not enabled self.assert_action_list_action('remove_hold', enabled=False, parents_css_sel=cert_widget_sel, facet_actions=False) # cert revoke self.action_list_action('revoke', confirm=False, parents_css_sel=cert_widget_sel) self.wait() self.select('select', '6') self.dialog_button_click('ok') self.wait_for_request(n=2, d=3) self.assert_visible(cert_widget_sel + " div.watermark") # check that revoke action is not enabled self.assert_action_list_action('revoke', enabled=False, parents_css_sel=cert_widget_sel, facet_actions=False) # check that remove_hold action is enabled self.assert_action_list_action('remove_hold', parents_css_sel=cert_widget_sel, facet_actions=False) # cert remove hold self.action_list_action('remove_hold', confirm=False, parents_css_sel=cert_widget_sel) self.wait() self.dialog_button_click('ok') self.wait_for_request(n=2) # check that revoke action is enabled self.assert_action_list_action('revoke', parents_css_sel=cert_widget_sel, facet_actions=False) # check that remove_hold action is not enabled self.assert_action_list_action('remove_hold', enabled=False, parents_css_sel=cert_widget_sel, facet_actions=False) # cleanup self.navigate_to_entity(user.ENTITY, 'search') self.delete_record(user.PKEY, user.DATA.get('del')) @screenshot def test_certificate_serial(self): """Test long certificate serial no Long certificate serial no were shown in scientific notation at user details page. This test checks that it is no longer shown in scientific notation related:https://pagure.io/freeipa/issue/8754 """ if not self.has_ca(): self.skip('CA is not configured') self.init_app() self.add_record(user.ENTITY, user.DATA2) self.wait() self.close_notifications() self.navigate_to_record(user.PKEY2) self.add_cert_to_record(user.USER_CERT, user.PKEY2, save=False) # check if the cert serial is 264374074076456325397645183544606453821 self.assert_text( 'div[name="cert-serial-num"]', '264374074076456325397645183544606453821' ) # cleanup self.navigate_to_entity(user.ENTITY, 'search') self.delete_record(user.PKEY2, user.DATA2.get('del')) @screenshot def test_password_expiration_notification(self): """ Test password expiration notification """ pwd = self.config.get('ipa_password') self.init_app() self.set_ipapwdexpadvnotify('15') # create user and group and add user to that group self.add_record(user.ENTITY, user.DATA) self.add_record(group.ENTITY, group.DATA) self.navigate_to_entity(group.ENTITY) self.navigate_to_record(group.PKEY) self.add_associations([user.PKEY]) # password policy for group self.add_record('pwpolicy', { 'pkey': group.PKEY, 'add': [ ('combobox', 'cn', group.PKEY), ('textbox', 'cospriority', '12345'), ]}) self.navigate_to_record(group.PKEY) self.mod_record('pwpolicy', { 'pkey': group.PKEY, 'mod': [ ('textbox', 'krbmaxpwdlife', '7'), ('textbox', 'krbminpwdlife', '0'), ]}) # reset password self.navigate_to_record(user.PKEY, entity=user.ENTITY) self.reset_password_action(pwd) # re-login as new user self.logout() self.init_app(user.PKEY, pwd) header = self.find('.navbar-pf', By.CSS_SELECTOR) self.assert_text( '.header-passwordexpires', 'Your password expires in 6 days.', header) # test password reset self.profile_menu_action('password_reset') self.fill_password_dialog(pwd, pwd) # cleanup self.logout() self.init_app() self.set_ipapwdexpadvnotify('4') self.delete(user.ENTITY, [user.DATA]) self.delete(group.ENTITY, [group.DATA]) def set_ipapwdexpadvnotify(self, days): """ Set ipa config "Password Expiration Notification (days)" field """ self.navigate_to_entity('config') self.mod_record('config', { 'mod': [ ('textbox', 'ipapwdexpadvnotify', days), ] }) def reset_password_action(self, password): """ Execute reset password action """ self.action_list_action('reset_password', False) self.fill_password_dialog(password) def fill_password_dialog(self, password, current=None): """ Fill password dialog """ self.assert_dialog() fields = [ ('password', 'password', password), ('password', 'password2', password), ] if current: fields.append(('password', 'current_password', current)) self.fill_fields(fields) self.dialog_button_click('confirm') self.wait_for_request(n=3) self.assert_no_error_dialog() @screenshot def test_grace_login_limit(self): """ Verify existence of grace login limit field and its value based on pwpolicy value Related: https://pagure.io/freeipa/issue/9211 """ self.init_app() self.add_record(group.ENTITY, [group.DATA]) # add record DATA8 already with passwordgracelimit self.add_record(pwpolicy.ENTITY, [pwpolicy.DATA8]) self.navigate_to_record(group.PKEY) # fill with values from DATA8, passwordgracelimit has value 42 self.fill_fields(pwpolicy.DATA8['mod']) try: # click save if needed self.button_click('save') except AssertionError: # autosave active pass # add record itest-user self.add_record(user.ENTITY, user.DATA) # add itest-user to itest-group self.navigate_to_entity(group.ENTITY) self.navigate_to_record(group.PKEY) self.add_associations([user.PKEY]) self.navigate_to_record(user.PKEY, entity=user.ENTITY) self.facet_button_click('refresh') self.wait(2) field = 'passwordgracelimit' # password grace limit is currently on the 10th place expected_value = pwpolicy.DATA8['mod'][9][2] current_value = self.get_field_value(field, element="input") try: assert current_value == expected_value finally: # cleanup self.delete(user.ENTITY, [user.DATA]) self.delete(group.ENTITY, [group.DATA]) self.delete(pwpolicy.ENTITY, [pwpolicy.DATA8]) @screenshot def test_login_without_username(self): """ Try to login with no username provided """ self.init_app(login='', password='xxx123') alert_e = self.find('.alert[data-name="username"]', By.CSS_SELECTOR) assert 'Username: Required field' in alert_e.text, 'Alert expected' assert self.login_screen_visible() @screenshot def test_disable_delete_admin(self): """ Test disabling/deleting admin is not allowed """ self.init_app() self.navigate_to_entity(user.ENTITY) # try to disable admin user self.select_record('admin') self.facet_button_click('disable') self.dialog_button_click('ok') self.assert_last_error_dialog(ERR_ADMIN_DISABLE, details=True) self.dialog_button_click('ok') self.assert_record('admin') # try to delete admin user. Later we are # confirming by keyboard to test also ticket 4097 self.select_record('admin') self.facet_button_click('remove') self.dialog_button_click('ok') self.assert_last_error_dialog(ERR_ADMIN_DEL, details=True) actions = ActionChains(self.driver) actions.send_keys(Keys.TAB) actions.send_keys(Keys.ENTER).perform() self.wait(0.5) self.assert_record('admin') @screenshot def test_add_user_special(self): """ Test various add user special cases """ self.init_app() # Test invalid characters (#@*?) in login self.navigate_to_entity(user.ENTITY) self.facet_button_click('add') self.fill_textbox('uid', 'itest-user#') self.assert_field_validation(ERR_INCLUDE) self.fill_textbox('uid', 'itest-user@') self.assert_field_validation(ERR_INCLUDE) self.fill_textbox('uid', 'itest-user*') self.assert_field_validation(ERR_INCLUDE) self.fill_textbox('uid', 'itest-user?') self.assert_field_validation(ERR_INCLUDE) self.dialog_button_click('cancel') # Add an user with special chars self.basic_crud(user.ENTITY, user.DATA_SPECIAL_CHARS) # Add an user with long login (should FAIL) self.add_record(user.ENTITY, user.DATA_LONG_LOGIN, negative=True) self.assert_last_error_dialog(expected_err=LONG_LOGIN) self.close_all_dialogs() # Test password mismatch self.add_record(user.ENTITY, user.DATA_PASSWD_MISMATCH, negative=True) pass_e = self.find('.widget[name="userpassword2"]', By.CSS_SELECTOR) self.assert_field_validation(ERR_MISMATCH, parent=pass_e) self.dialog_button_click('cancel') self.assert_record(user.DATA_PASSWD_MISMATCH.get('pkey'), negative=True) # test add and edit record self.add_record(user.ENTITY, user.DATA2, dialog_btn='add_and_edit') self.action_list_action('delete_active_user') # click add and cancel self.add_record(user.ENTITY, user.DATA, dialog_btn='cancel') # add leading space before password (should SUCCEED) self.navigate_to_entity(user.ENTITY) self.facet_button_click('add') self.fill_fields(user.DATA_PASSWD_LEAD_SPACE['add']) self.dialog_button_click('add') # add trailing space before password (should SUCCEED) self.navigate_to_entity(user.ENTITY) self.facet_button_click('add') self.fill_fields(user.DATA_PASSWD_TRAIL_SPACE['add']) self.dialog_button_click('add') # add user using enter self.add_record(user.ENTITY, user.DATA2, negative=True) actions = ActionChains(self.driver) actions.send_keys(Keys.ENTER).perform() self.wait() self.assert_notification(assert_text=USR_ADDED) self.assert_record(user.PKEY2) self.close_notifications() # delete user using enter self.select_record(user.PKEY2) self.facet_button_click('remove') actions.send_keys(Keys.ENTER).perform() self.wait(0.5) self.assert_notification(assert_text='1 item(s) deleted') self.assert_record(user.PKEY2, negative=True) @screenshot def test_add_delete_undo_reset_multivalue(self): """ Test add and delete multivalue with reset and undo """ self.init_app() first_mail = self.create_email_addr(user.DATA.get('pkey')) self.add_record(user.ENTITY, user.DATA) self.wait() self.close_notifications() self.navigate_to_record(user.DATA.get('pkey')) # add a new mail (without save) and reset self.add_multivalued('mail', 'temp@ipa.test') self.assert_undo_button('mail') self.facet_button_click('revert') self.assert_undo_button('mail', visible=False) # click at delete on the first mail and reset self.del_multivalued('mail', first_mail) self.assert_undo_button('mail') self.facet_button_click('revert') self.assert_undo_button('mail', visible=False) # edit the first mail and reset self.edit_multivalued('mail', first_mail, 'temp@ipa.test') self.assert_undo_button('mail') self.facet_button_click('revert') self.assert_undo_button('mail', visible=False) # add a new mail and undo self.add_multivalued('mail', 'temp@ipa.test') self.assert_undo_button('mail') self.undo_multivalued('mail', 'temp@ipa.test') self.assert_undo_button('mail', visible=False) # edit the first mail and undo self.edit_multivalued('mail', first_mail, 'temp@ipa.test') self.assert_undo_button('mail') self.undo_multivalued('mail', 'temp@ipa.test') self.assert_undo_button('mail', visible=False) # cleanup self.delete(user.ENTITY, [user.DATA]) @screenshot def test_user_misc(self): """ Test various miscellaneous test cases under one roof to save init time """ self.init_app() # add already existing user (should fail) / also test ticket 4098 self.add_record(user.ENTITY, user.DATA) self.add_record(user.ENTITY, user.DATA, negative=True, pre_delete=False) self.assert_last_error_dialog(USR_EXIST.format(user.PKEY)) actions = ActionChains(self.driver) actions.send_keys(Keys.TAB) actions.send_keys(Keys.ENTER).perform() self.wait(0.5) self.dialog_button_click('cancel') # add user without login name self.add_record(user.ENTITY, user.DATA_NO_LOGIN) self.assert_record('nsurname10') # try to add same user without login name again (should fail) self.add_record(user.ENTITY, user.DATA_NO_LOGIN, negative=True, pre_delete=False) self.assert_last_error_dialog(USR_EXIST.format('nsurname10')) self.close_all_dialogs() # try to modify user`s UID to -1 (should fail) self.navigate_to_record(user.PKEY) self.mod_record( user.ENTITY, {'mod': [('textbox', 'uidnumber', '-1')]}, negative=True) uid_e = self.find('.widget[name="uidnumber"]', By.CSS_SELECTOR) self.assert_field_validation('Minimum value is 1', parent=uid_e) self.facet_button_click('revert') # edit user`s "First name" to value with leading space (should fail) self.fill_input('givenname', ' leading_space') self.facet_button_click('save') self.assert_last_error_dialog(INV_FIRSTNAME) self.dialog_button_click('cancel') # edit user`s "First name" to value with trailing space (should fail) self.fill_input('givenname', 'trailing_space ') self.facet_button_click('save') self.assert_last_error_dialog(INV_FIRSTNAME) self.dialog_button_click('cancel') # try with blank "First name" (should fail) gn_input_s = "input[type='text'][name='givenname']" gn_input_el = self.find(gn_input_s, By.CSS_SELECTOR, strict=True) gn_input_el.clear() gn_input_el.send_keys(Keys.BACKSPACE) self.facet_button_click('save') gn_e = self.find('.widget[name="givenname"]', By.CSS_SELECTOR) self.assert_field_validation(FIELD_REQ, parent=gn_e) self.close_notifications() # search user / multiple users self.navigate_to_entity(user.ENTITY) self.wait(0.5) self.find_record('user', user.DATA) self.add_record(user.ENTITY, user.DATA2) self.find_record('user', user.DATA2) # search for both users (just 'itest-user' will do) self.find_record('user', user.DATA) self.assert_record(user.PKEY2) # cleanup self.delete_record([user.PKEY, user.PKEY2, user.PKEY_NO_LOGIN, 'nsurname10']) @screenshot def test_menu_click_minimized_window(self): """ Test if menu is clickable when there is notification in minimized browser window. related: https://pagure.io/freeipa/issue/8120 """ self.init_app() self.driver.set_window_size(570, 600) self.add_record(user.ENTITY, user.DATA2, negative=True) self.assert_notification(assert_text=USR_ADDED) menu_button = self.find('.navbar-toggle', By.CSS_SELECTOR) menu_button.click() self.assert_record(user.PKEY2) self.close_notifications() self.driver.maximize_window() # cleanup self.delete(user.ENTITY, [user.DATA2]) @screenshot def test_enabled_by_default(self): """ Test if valid user created in both ca and caless env is enabled by default. https://pagure.io/freeipa/issue/8203 """ self.init_app() # check if the user is enabled self.add_record(user.ENTITY, user.DATA, navigate=False) self.assert_record_value(expected="Enabled", pkeys=user.PKEY, column="nsaccountlock") self.navigate_to_record(user.PKEY) self.assert_action_list_action("disable", visible=True, enabled=True) self.assert_action_list_action("reset_password", visible=True, enabled=True) # add OTP authentication type and verify the change is persistent self.add_user_auth_type("otp", save=True) self.assert_user_auth_type("otp", enabled=True) @pytest.mark.tier1 class test_user_no_private_group(UI_driver): @screenshot def test_noprivate_nonposix(self): """ User without private group and without specified GID """ self.init_app() with pytest.raises(AssertionError) as e: self.add_record(user.ENTITY, user.DATA3) assert (str(e.value) == 'Unexpected error: Default group for new ' 'users is not POSIX') @screenshot def test_noprivate_posix(self): """ User without private group and specified existing posix GID """ self.init_app() self.add_record(group.ENTITY, group.DATA6) self.add_record(user.ENTITY, user.DATA4) self.delete(user.ENTITY, [user.DATA4]) self.delete(group.ENTITY, [group.DATA6]) @screenshot def test_noprivate_gidnumber(self): """ User without private group and specified unused GID """ self.init_app() self.add_record(user.ENTITY, user.DATA4, combobox_input='gidnumber') self.delete(user.ENTITY, [user.DATA4]) @pytest.mark.tier1 class TestLifeCycles(UI_driver): @screenshot def test_life_cycles(self): """ Test user life-cycles """ self.init_app() # create "itest-user" and send him to preserved self.add_record(user.ENTITY, user.DATA) self.delete_record(user.PKEY, confirm_btn=None) self.check_option('preserve', value='true') self.dialog_button_click('ok') self.assert_notification(assert_text='1 item(s) deleted') # try to add the same user again (should fail) self.add_record(user.ENTITY, user.DATA, negative=True) self.assert_last_error_dialog(USR_EXIST.format(user.PKEY)) self.close_all_dialogs() self.wait() # restore "itest-user" user self.switch_to_facet('search_preserved') self.select_record(user.PKEY) self.button_click('undel') self.dialog_button_click('ok') self.assert_no_error_dialog() self.assert_notification(assert_text='1 user(s) restored') self.wait() # add already existing user "itest-user" to stage and try to activate # the latter (should fail) self.add_record('stageuser', user.DATA) self.select_record(user.PKEY) self.button_click('activate') self.dialog_button_click('ok') err_msg = ACTIVE_ERR.format(user.PKEY) self.assert_last_error_dialog(err_msg, details=True) self.dialog_button_click('ok') # delete "itest-user" staged user self.delete_record(user.PKEY) self.assert_record(user.PKEY, negative=True) # add "itest-user2" and send him to staged (through preserved) self.close_all_dialogs() self.add_record(user.ENTITY, user.DATA2) self.delete_record(user.PKEY2, confirm_btn=None) self.check_option('preserve', value='true') self.dialog_button_click('ok') self.switch_to_facet('search_preserved') self.select_record(user.PKEY2) self.button_click('batch_stage') self.dialog_button_click('ok') self.assert_no_error_dialog() self.wait(2) # fix assert after https://pagure.io/freeipa/issue/7477 is closed self.assert_notification(assert_text='1 users(s) staged') # add new "itest-user2" - one is already staged (should pass) self.add_record(user.ENTITY, user.DATA2) self.assert_record(user.PKEY2) # send active "itest-user2" to preserved self.delete_record(user.PKEY2, confirm_btn=None) self.check_option('preserve', value='true') self.dialog_button_click('ok') # try to activate staged "itest-user2" while one is already preserved # (should fail) self.navigate_to_entity('stageuser') self.select_record(user.PKEY2) self.button_click('activate') self.dialog_button_click('ok') self.assert_last_error_dialog(ENTRY_EXIST, details=True) self.dialog_button_click('ok') # delete preserved "itest-user2" and activate the staged one # (should pass) self.switch_to_facet('search_preserved') self.delete_record(user.PKEY2) self.navigate_to_entity('stageuser') self.select_record(user.PKEY2) self.button_click('activate') self.wait() self.dialog_button_click('ok') self.assert_notification(assert_text='1 user(s) activated') # send multiple records to preserved self.navigate_to_entity('stageuser') self.navigate_to_entity(user.ENTITY) self.delete_record([user.PKEY, user.PKEY2], confirm_btn=None) self.check_option('preserve', value='true') self.dialog_button_click('ok') self.assert_notification(assert_text='2 item(s) deleted') # restore multiple records self.switch_to_facet('search_preserved') self.select_multiple_records([user.DATA, user.DATA2]) self.button_click('undel') self.dialog_button_click('ok') self.assert_no_error_dialog() self.assert_notification(assert_text='2 user(s) restored') self.wait() # send multiple users to staged (through preserved) self.navigate_to_entity(user.ENTITY) self.delete_record([user.PKEY, user.PKEY2], confirm_btn=None) self.check_option('preserve', value='true') self.dialog_button_click('ok') self.switch_to_facet('search_preserved') self.select_multiple_records([user.DATA, user.DATA2]) self.button_click('batch_stage') self.dialog_button_click('ok') self.assert_no_error_dialog() self.wait(2) self.assert_notification(assert_text='2 users(s) staged') # activate multiple users from stage self.navigate_to_entity('stageuser') self.select_multiple_records([user.DATA, user.DATA2]) self.button_click('activate') self.dialog_button_click('ok') self.assert_notification(assert_text='2 user(s) activated') # try to disable record from user page self.navigate_to_entity(user.ENTITY) self.select_record(user.PKEY) self.facet_button_click('disable') self.dialog_button_click('ok') self.assert_record_value('Disabled', user.PKEY, 'nsaccountlock') # try to disable same record again (should fail) self.select_record(user.PKEY) self.facet_button_click('disable') self.dialog_button_click('ok') self.assert_last_error_dialog(DISABLED, details=True) self.dialog_button_click('ok') # enable the user again self.select_record(user.PKEY) self.facet_button_click('enable') self.dialog_button_click('ok') self.assert_record_value('Enabled', user.PKEY, 'nsaccountlock') # same for multiple users (disable, disable again, enable) self.select_multiple_records([user.DATA, user.DATA2]) self.facet_button_click('disable') self.dialog_button_click('ok') self.assert_record_value('Disabled', [user.PKEY, user.PKEY2], 'nsaccountlock') self.select_multiple_records([user.DATA, user.DATA2]) self.facet_button_click('disable') self.dialog_button_click('ok') self.assert_last_error_dialog(DISABLED, details=True) self.dialog_button_click('ok') self.select_multiple_records([user.DATA, user.DATA2]) self.facet_button_click('enable') self.dialog_button_click('ok') self.assert_record_value('Enabled', [user.PKEY, user.PKEY2], 'nsaccountlock') # cleanup and check for ticket 4245 (select all should not remain # checked after delete action). Two "ok" buttons at the end are needed # for delete confirmation and acknowledging that "admin" cannot be # deleted. self.navigate_to_entity(user.ENTITY) select_all_btn = self.find('input[title="Select All"]', By.CSS_SELECTOR) select_all_btn.click() self.facet_button_click('remove') self.dialog_button_click('ok') self.dialog_button_click('ok') self.assert_value_checked('admin', 'uid', negative=True) @pytest.mark.tier1 class TestSSHkeys(UI_driver): @screenshot def test_ssh_keys(self): self.init_app() # add and undo SSH key self.add_sshkey_to_record(user.SSH_RSA, 'admin', save=False, navigate=True) self.assert_num_ssh_keys(1) self.undo_ssh_keys() self.assert_num_ssh_keys(0) # add and undo 2 SSH keys (using undo all) ssh_keys = [user.SSH_RSA, user.SSH_DSA] self.add_sshkey_to_record(ssh_keys, 'admin', save=False) self.assert_num_ssh_keys(2) self.undo_ssh_keys(btn_name='undo_all') self.assert_num_ssh_keys(0) # add SSH key and refresh self.add_sshkey_to_record(user.SSH_RSA, 'admin', save=False) self.assert_num_ssh_keys(1) self.facet_button_click('refresh') self.assert_num_ssh_keys(0) # add SSH key and revert self.add_sshkey_to_record(user.SSH_RSA, 'admin', save=False) self.assert_num_ssh_keys(1) self.facet_button_click('revert') self.assert_num_ssh_keys(0) # add SSH key, move elsewhere and cancel. self.add_sshkey_to_record(user.SSH_RSA, 'admin', save=False) self.assert_num_ssh_keys(1) self.switch_to_facet('memberof_group') self.dialog_button_click('cancel') self.assert_num_ssh_keys(1) self.undo_ssh_keys() # add SSH key, move elsewhere and click reset button. self.add_sshkey_to_record(user.SSH_RSA, 'admin', save=False) self.assert_num_ssh_keys(1) self.switch_to_facet('memberof_group') self.wait_for_request() self.dialog_button_click('revert') self.wait() self.switch_to_facet('details') self.assert_num_ssh_keys(0) # add SSH key, move elsewhere and click save button. self.add_sshkey_to_record(user.SSH_RSA, 'admin', save=False) self.assert_num_ssh_keys(1) self.switch_to_facet('memberof_group') self.wait() self.dialog_button_click('save') self.wait_for_request(n=4) self.switch_to_facet('details') self.assert_num_ssh_keys(1) self.delete_record_sshkeys('admin') # add, save and delete RSA and DSA keys keys = [user.SSH_RSA, user.SSH_DSA] self.add_sshkey_to_record(keys, 'admin') self.assert_num_ssh_keys(2) self.delete_record_sshkeys('admin') self.assert_num_ssh_keys(0) # add RSA SSH keys with trailing space and "=" sign at the end keys = [user.SSH_RSA+" ", user.SSH_RSA2+"="] self.add_sshkey_to_record(keys, 'admin') self.assert_num_ssh_keys(2) self.delete_record_sshkeys('admin') self.assert_num_ssh_keys(0) # lets try to add empty SSH key (should fail) self.add_sshkey_to_record('', 'admin') self.assert_last_error_dialog(EMPTY_MOD) self.dialog_button_click('cancel') self.undo_ssh_keys() # try to add invalid SSH key self.add_sshkey_to_record('invalid_key', 'admin') self.assert_last_error_dialog(INVALID_SSH_KEY) self.dialog_button_click('cancel') self.undo_ssh_keys() # add duplicate SSH keys self.add_sshkey_to_record(user.SSH_RSA, 'admin') self.add_sshkey_to_record(user.SSH_RSA, 'admin', save=False) self.facet_button_click('save') self.assert_last_error_dialog(EMPTY_MOD) self.dialog_button_click('cancel') # test SSH key edit when user lacks write rights for related attribute # see ticket 3800 (we use DATA_SPECIAL_CHARS just for convenience) self.add_record(user.ENTITY, [user.DATA2, user.DATA_SPECIAL_CHARS]) self.add_sshkey_to_record(user.SSH_RSA, user.PKEY2, navigate=True) self.logout() self.init_app(user.PKEY_SPECIAL_CHARS, user.PASSWD_SCECIAL_CHARS) self.navigate_to_record(user.PKEY2, entity=user.ENTITY) show_ssh_key_btn = self.find('div.widget .btn[name="ipasshpubkey-0"]', By.CSS_SELECTOR) show_ssh_key_btn.click() ssh_key_e = self.find('textarea', By.CSS_SELECTOR, self.get_dialog()) assert ssh_key_e.get_attribute('readonly') == 'true' self.dialog_button_click('cancel') self.logout() self.init_app() # cleanup self.delete(user.ENTITY, [user.DATA2, user.DATA_SPECIAL_CHARS]) self.delete_record_sshkeys('admin', navigate=True)
42,211
Python
.py
961
34.046826
79
0.619608
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,382
data_host.py
freeipa_freeipa/ipatests/test_webui/data_host.py
# Copyright (C) 2018 FreeIPA Contributors see COPYING for license # BAD_IP_MSG = "Not a valid IP address" BAD_HOSTNAME_MSG = "only letters, numbers, '-' are allowed" BAS_HOSTNAME_SPACE_MSG = "Leading and trailing spaces are not allowed" empty_hostname = { 'pkey': 'empty_hostname', 'add': [ ('textbox', 'hostname', ''), ], } empty_domain = { 'pkey': 'empty_domain', 'add': [ ('textbox', 'hostname', 'itest-empty-domain'), ('textbox', 'dnszone', ''), ], } hostname_tilde = { 'pkey': 'tilde_hostname', 'add': [ ('textbox', 'hostname', '~tilde'), ], } hostname_dash = { 'pkey': 'dash_hostname', 'add': [ ('textbox', 'hostname', '-dash'), ], } hostname_leading_space = { 'pkey': 'leading_space', 'add': [ ('textbox', 'hostname', ' leading_space'), ], } hostname_trailing_space = { 'pkey': 'trailing_space', 'add': [ ('textbox', 'hostname', 'trailing_space '), ], } ip_alpha = { 'pkey': 'ip_alpha', 'add': [ ('textbox', 'hostname', 'ip-field-test'), ('textbox', 'ip_address', 'abc.10.12.14'), ], } ip_many_oct = { 'pkey': 'ip_many', 'add': [ ('textbox', 'hostname', 'ip-field-test'), ('textbox', 'ip_address', '10.10.10.1.10'), ], } ip_bad_oct = { 'pkey': 'ip_bad_octal', 'add': [ ('textbox', 'hostname', 'ip-field-test'), ('textbox', 'ip_address', '10.0.378.1'), ], } ip_special_char = { 'pkey': 'ip_special', 'add': [ ('textbox', 'hostname', 'ip-field-test'), ('textbox', 'ip_address', '10.0.##.1'), ], } mod_desc = [ ('textarea', 'description', 'description in details'), ] mod_desc_m = [ ('textarea', 'description', 'description never appear'), ] mod_locality = [ ('textbox', 'l', 'Brno Office'), ] mod_location = [ ('textbox', 'nshostlocation', 'Brno Office'), ] mod_platform = [ ('textbox', 'nshardwareplatform', 'x86_64'), ] mod_os = [ ('textbox', 'nsosversion', 'FEDORA RHEL 277'), ] otp_alpha = [ ('password', 'userpassword', 'alpha'), ('password', 'password2', 'alpha'), ] otp_num = [ ('password', 'userpassword', '1234'), ('password', 'password2', '1234'), ] otp_alphanum = [ ('password', 'userpassword', 'abc123'), ('password', 'password2', 'abc123'), ] otp_special = [ ('password', 'userpassword', '@#$'), ('password', 'password2', '@#$'), ] otp_mixed = [ ('password', 'userpassword', 'AbC12D'), ('password', 'password2', 'AbC12D'), ] ssh_nomod_error = "no modifications to be performed" ssh_invalid_error = "invalid SSH public key" ssh_rsa = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCnAOLat' + \ 'ncsaDxF+ldDhjNdPRDWXKsiZUz6Y49LjPnEr9p4Th24dZ' + \ '7ZuvOVjhXDSkivh6MRunWZC+MXxRo1lDZgkCSyQfkMq0E' + \ 'u6xkubPg3tYAdrFBZIcIl5CUNerqYMdTz2hyTq6HAR/qs' + \ '6oRbtzUemwHLPo3duqDRLWQoojP+tI8I2IEXnOO2N5oxq' + \ 'YGWAUe7bGXS/O2ukGfclt8/BfVw9e6eqHqlc7tKGqEctn' + \ 'imlsbG291ctNgco8FsvCnV5EOti/O0rLdkTmm66j7WCFj' + \ 'D9gJncfkAzxc+itWE4eUg/0B5ICIeRrFl5obD8Vu3LzTQ' + \ '4yKiwaUnY5ngXgWBoFq9 root@sshkey.testipa.ipa' ssh_dsa = 'ssh-dss AAAAB3NzaC1kc3MAAACBAO3OqwC1eNedXVJ57' + \ '/a+Q/BfVcbZiJcTxhVP6TnIIQXmI+YSu685gLXEHWEAX1' + \ '9+8eQuvUSmgWViuskErCXliE1c4PVyrwkf/2UMsH+hFaj' + \ '0jlAM4APzizSvHC59hjpr5ktPyrv1arBXGYRuWyZNphJZ' + \ 'OFbqK2DHZbz1jvhD4uz5AAAAFQDasuSv8Dkn2Khqek0U3' + \ 'EAHUaUL2wAAAIB5Wr4r7z4ZyaSoaxfiUvvKg49FCeGjrY' + \ 'jRbYN/PazAn/X0rPcGqpaF3u5FmxXP7vhvlvECZvveK7T' + \ 'FIJVz1DSKHMRu8886akKLegF1zhhjrnjN7Q4vHbwkhsCI' + \ 'aV+4rlJa7B32girkSltlooP/qWMnRde0aJIf20Zhq/IF9' + \ 'oj49AAAAIBsKrdE+nxubD13+BdX07Sq6wAPVa9RVCISqE' + \ 'simlCvopStg8vNuNfGi9swmyFyNjSMiZEgoxH2cLRME4+' + \ 'xzn7THVrmE6OQ/Duz/mQAnDvt1N0Qw4jNxv0WqoT0kz7X' + \ '21L5Dmg5qy4qdEvlcOkVI9gMrIrXhwGb+Vj8XEGtWcNmJ' + \ 'w== root@sshkey.testipa.ipa' ssh_empty = '' ssh_invalid = 'ff99cc1234dec invalid' csr_invalid_error = 'Base64 decoding failed' csr_invalid = 'invalid cert' csr_other_host_error = 'Base64 decoding failed' csr_other_host = '''-----BEGIN NEW CERTIFICATE REQUEST----- MIICpjCCAY4CAQAwMDEQMA4GA1UEChMHSVBBLklQQTEcMBoGA1UEAxMTYW5vdGhl cmhvc3QuaXBhLmlwYTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAM5Z xiBOxo0W107maJt84m4BrkOFErCi0Mk4UQABMAfg/Sbj/+nYL19CA/IgSy4NoCnt 0RK1IZcFvSzHNhJmwpyRcmaOIbEsjes35rYYA2LKV3QVBp14284tJN5xRHztuL9B 0NDaSuZOG4JERHJl7JBGOzs4mj3FkI+Ci92d/zi+vpI+T0b26BGejcpU98zkVKxE ktXNHqZp/QV7EHsqaZDdIPGTORZokZnU3VFsbUnCLDyghg3+75t+Wq4sJvwL1Y9j btO5cQLWTJiOotk1Ies2A5nrp89CpMP45ERtZmoe+G3WeWgW9Nqr182kF5NjlC/O sHKz4bP9hT9Z6bk4J3ECAwEAAaAxMC8GCSqGSIb3DQEJDjEiMCAwHgYDVR0RBBcw FYITYW5vdGhlcmhvc3QuaXBhLmlwYTANBgkqhkiG9w0BAQsFAAOCAQEAoEQNqnts Ob5fTPZRQQo8ygoKa+4GXMjM/Ue2SYs2zOa1/aYeI6JVzWzWH9xHFNvhOkdhu154 9fefKPtFKeyRTRz60KjSGcHyawDmoWyVYMPgFwmWp1lceFDEy0SlCnB58iXuxYEU mwlXmODQR1hQxLuo5Ow3Hy0Djyml7gh7DA/iHP7WrOJH3PwTegxAFFixIj7K6DYK 3Kaeng72Ht8vQeTEh0Fq4rcfIdlW6tjWywLqLqCjtwhNkak4tJna6M9/3yjeyEnk /w7Ya8CyOwlTaCvN8cjnBTxXWVVh+lIaPhujxG4UVtOMqaI30EkMIMHrocCUNnRd 2e8CMvHPLREqJw== -----END NEW CERTIFICATE REQUEST-----''' krb_enrolled = 'Kerberos Key Present, Host Provisioned' krb_not_enrolled = 'Kerberos Key Not Present'
5,376
Python
.py
157
29.802548
70
0.687079
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,383
data_dns.py
freeipa_freeipa/ipatests/test_webui/data_dns.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # ZONE_ENTITY = 'dnszone' FORWARD_ZONE_ENTITY = 'dnsforwardzone' RECORD_ENTITY = 'dnsrecord' CONFIG_ENTITY = 'dnsconfig' ZONE_DEFAULT_FACET = 'records' ZONE_PKEY = 'foo.itest.' ZONE_DATA = { 'pkey': ZONE_PKEY, 'add': [ ('textbox', 'idnsname', ZONE_PKEY), ], 'mod': [ ('checkbox', 'idnsallowsyncptr', 'checked'), ], } FORWARD_ZONE_PKEY = 'forward.itest.' FORWARD_ZONE_DATA = { 'pkey': FORWARD_ZONE_PKEY, 'add': [ ('textbox', 'idnsname', FORWARD_ZONE_PKEY), ('multivalued', 'idnsforwarders', [ ('add', '192.168.2.1'), ]), ('radio', 'idnsforwardpolicy', 'only'), ], 'mod': [ ('multivalued', 'idnsforwarders', [ ('add', '192.168.3.1'), ]), ('checkbox', 'idnsforwardpolicy', 'first'), ], } RECORD_PKEY = 'itest' A_IP = '192.168.1.10' RECORD_ADD_DATA = { 'pkey': RECORD_PKEY, 'add': [ ('textbox', 'idnsname', RECORD_PKEY), ('textbox', 'a_part_ip_address', A_IP), ] } RECORD_MOD_DATA = { 'fields': [ ('textbox', 'a_part_ip_address', '192.168.1.11'), ] } CONFIG_MOD_DATA = { 'mod': [ ('checkbox', 'idnsallowsyncptr', 'checked'), ], }
1,300
Python
.py
54
19.277778
66
0.556993
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,384
data_hostgroup.py
freeipa_freeipa/ipatests/test_webui/data_hostgroup.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ENTITY = 'hostgroup' DEFAULT_FACET = 'member_host' LEADING_SPACE = ' leading-space' TRAILING_SPACE = 'trailign-space ' NAME_SPACE = 'name space' CHAR_WARNING_MSG = "may only include letters, numbers, _, -, and ." EMPTY_WARNING_MSG = "Required field" DUPLICATE_WARNING_MSG = 'already exists' DESCRIPTION_ERROR_DIALOG = 'Leading and trailing spaces are not allowed' PKEY = 'itest-hostgroup' DATA = { 'pkey': PKEY, 'add': [ ('textbox', 'cn', PKEY), ('textarea', 'description', 'test-hostgroup desc'), ], 'mod': [ ('textarea', 'description', 'test-hostgroup desc modified'), ], } PKEY2 = 'itest-hostgroup2' DATA2 = { 'pkey': PKEY2, 'add': [ ('textbox', 'cn', PKEY2), ('textarea', 'description', 'test-hostgroup2 desc'), ], 'mod': [ ('textarea', 'description', 'test-hostgroup2 desc modified'), ], } PKEY3 = 'itest-hostgroup3' DATA3 = { 'pkey': PKEY3, 'add': [ ('textbox', 'cn', PKEY3), ('textarea', 'description', 'test-hostgroup3 desc'), ], 'mod': [ ('textarea', 'description', 'test-hostgroup3 desc modified'), ], } PKEY4 = 'itest-hostgroup4' DATA4 = { 'pkey': PKEY4, 'add': [ ('textbox', 'cn', PKEY4), ('textarea', 'description', 'test-hostgroup4 desc'), ], 'mod': [ ('textarea', 'description', 'test-hostgroup4 desc modified'), ], } PKEY5 = 'itest-hostgroup5' DATA5 = { 'pkey': PKEY5, 'add': [ ('textbox', 'cn', PKEY5), ('textarea', 'description', 'test-hostgroup5 desc'), ], 'mod': [ ('textarea', 'description', 'test-hostgroup5 desc modified'), ], } PKEY6 = 'ITEST-HOSTGROUP6' DATA6 = { 'pkey': PKEY6, 'add': [ ('textbox', 'cn', PKEY6), ('textarea', 'description', 'TEST-HOSTGROUP6 DESC'), ], } PKEY7 = 'Itest-hostGROUP7' DATA7 = { 'pkey': PKEY7, 'add': [ ('textbox', 'cn', PKEY7), ('textarea', 'description', 'TesT-HosTGroUP7 DESC'), ], } PKEY8 = 16 * 'long-name-hostgroup8' DKEY8 = 16 * 'long hostgroup description' DATA8 = { 'pkey': PKEY8, 'add': [ ('textbox', 'cn', PKEY8), ('textarea', 'description', DKEY8), ], }
3,009
Python
.py
107
24.17757
72
0.627119
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,385
data_hbac.py
freeipa_freeipa/ipatests/test_webui/data_hbac.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. RULE_ENTITY = 'hbacrule' RULE_PKEY = 'itesthbacrule' RULE_DATA = { 'pkey': RULE_PKEY, 'add': [ ('textbox', 'cn', RULE_PKEY), ], 'mod': [ ('textarea', 'description', 'testhbacrulec desc'), ], } SVC_ENTITY = 'hbacsvc' SVC_PKEY = 'itesthbacsvc' SVC_DATA = { 'pkey': SVC_PKEY, 'add': [ ('textbox', 'cn', SVC_PKEY), ('textarea', 'description', 'testhbacsvc desc'), ], 'mod': [ ('textarea', 'description', 'testhbacsvc desc mod'), ], } SVCGROUP_ENTITY = 'hbacsvcgroup' SVCGROUP_DEF_FACET = 'member_hbacsvc' SVCGROUP_PKEY = 'itesthbaccvcgroup' SVCGROUP_DATA = { 'pkey': SVCGROUP_PKEY, 'add': [ ('textbox', 'cn', SVCGROUP_PKEY), ('textarea', 'description', 'testhbaccvcgroup desc'), ], 'mod': [ ('textarea', 'description', 'testhbaccvcgroup desc mod'), ], }
1,650
Python
.py
54
27.203704
71
0.670433
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,386
test_host.py
freeipa_freeipa/ipatests/test_webui/test_host.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Host tests """ import uuid from random import randint from ipatests.test_webui.crypto_utils import generate_certificate, generate_csr from ipatests.test_webui.ui_driver import UI_driver from ipatests.test_webui.ui_driver import screenshot import ipatests.test_webui.data_hostgroup as hostgroup import ipatests.test_webui.data_netgroup as netgroup import ipatests.test_webui.data_hbac as hbac import ipatests.test_webui.test_rbac as rbac import ipatests.test_webui.data_sudo as sudo import ipatests.test_webui.data_host as host import pytest try: from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains except ImportError: NO_SELENIUM = True ENTITY = 'host' @pytest.mark.tier1 class host_tasks(UI_driver): @pytest.fixture(autouse=True) def hosttasks_setup(self, ui_driver_fsetup): self.prep_data() self.prep_data2() self.prep_data3() self.prep_data4() def prep_data(self): host = self.rand_host() domain = self.config.get('ipa_domain') ip = self.get_ip() self.data = self.get_data(host, domain, ip) self.pkey = self.data['pkey'] return self.data def prep_data2(self): host = self.rand_host() domain = self.config.get('ipa_domain') self.data2 = self.get_data(host, domain) self.pkey2 = self.data2['pkey'] return self.data2 def prep_data3(self): host = self.rand_host() domain = self.config.get('ipa_domain') self.data3 = self.get_data(host, domain) self.pkey3 = self.data3['pkey'] return self.data3 def prep_data4(self): host = self.rand_host() domain = self.config.get('ipa_domain') self.data4 = self.get_data(host, domain) self.pkey4 = self.data4['pkey'] return self.data4 def get_data(self, host, domain, ip=None): if self.has_dns(): add_data = [ ('textbox', 'hostname', host), ('combobox', 'dnszone', domain+'.'), ] if ip: add_data.append(('textbox', 'ip_address', ip)) add_data.append(('checkbox', 'force', None)) del_data = [ ('checkbox', 'updatedns', None) ] else: add_data = [ ('textbox', 'fqdn', '%s.%s' % (host, domain)), ('checkbox', 'force', None), ] del_data = None data = { 'pkey': '%s.%s' % (host, domain), 'add': add_data, 'mod': [ ('textarea', 'description', 'Desc'), ], 'del': del_data, } return data def get_ip(self): """ Get next IP """ ip = self.config.get('ipa_ip') if not ip: self.skip('FreeIPA Server IP address not configured') while True: new_ip = '10.{}.{}.{}'.format( randint(0, 255), randint(0, 255), randint(1, 254) ) if new_ip != ip: break return new_ip @staticmethod def rand_host(): return 'host-{}'.format(uuid.uuid4().hex[:8]) def load_file(self, path): """ Load file helper mainly for CSR load_file """ with open(path, 'r') as file_d: content = file_d.read() return content @pytest.mark.tier1 class test_host(host_tasks): @screenshot def test_crud(self): """ Basic CRUD: host """ self.init_app() self.basic_crud(ENTITY, self.data) @screenshot def test_certificates(self): """ Test host certificate actions """ if not self.has_ca(): self.skip('CA is not configured') self.init_app() cert_widget_sel = "div.certificate-widget" self.add_record(ENTITY, self.data) self.navigate_to_record(self.pkey) # cert request csr = generate_csr(self.pkey) self.action_list_action('request_cert', confirm=False) self.assert_dialog() self.fill_text("textarea[name='csr']", csr) self.dialog_button_click('issue') self.wait_for_request(n=2, d=3) self.assert_visible(cert_widget_sel) widget = self.find(cert_widget_sel, By.CSS_SELECTOR) # cert view self.action_list_action('view', confirm=False, parents_css_sel=cert_widget_sel) self.assert_dialog() self.dialog_button_click('close') # cert get self.action_list_action('get', confirm=False, parents_css_sel=cert_widget_sel) self.assert_dialog() # check that the textarea is not empty self.assert_empty_value('textarea.certificate', negative=True) self.dialog_button_click('close') # cert download - we can only try to click the download action self.action_list_action('download', confirm=False, parents_css_sel=cert_widget_sel) # check that revoke action is enabled self.assert_action_list_action('revoke', parents_css_sel=cert_widget_sel, facet_actions=False) # check that remove_hold action is not enabled self.assert_action_list_action('remove_hold', enabled=False, parents_css_sel=cert_widget_sel, facet_actions=False) # cert revoke self.action_list_action('revoke', confirm=False, parents_css_sel=cert_widget_sel) self.wait() self.select('select', '6') self.dialog_button_click('ok') self.wait_while_working(widget) self.assert_visible(cert_widget_sel + " div.watermark") # check that revoke action is not enabled self.assert_action_list_action('revoke', enabled=False, parents_css_sel=cert_widget_sel, facet_actions=False) # check that remove_hold action is enabled self.assert_action_list_action('remove_hold', parents_css_sel=cert_widget_sel, facet_actions=False) # cert remove hold self.action_list_action('remove_hold', confirm=False, parents_css_sel=cert_widget_sel) self.wait() self.dialog_button_click('ok') self.wait_while_working(widget) # check that revoke action is enabled self.assert_action_list_action('revoke', parents_css_sel=cert_widget_sel, facet_actions=False) # check that remove_hold action is not enabled self.assert_action_list_action('remove_hold', enabled=False, parents_css_sel=cert_widget_sel, facet_actions=False) # cleanup self.navigate_to_entity(ENTITY, 'search') self.delete_record(self.pkey, self.data.get('del')) @screenshot def test_arbitrary_certificates(self): """ Test managing host arbitrary certificate. """ self.init_app() self.add_record(ENTITY, self.data) self.navigate_to_record(self.pkey) # check whether certificate section is present self.assert_visible("div[name='certificate']") # add certificate self.button_click('add', parents_css_sel="div[name='certificate']") self.assert_dialog('cert-add-dialog') cert = generate_certificate(self.pkey) self.fill_textarea('new_cert', cert) self.dialog_button_click('ok') self.assert_visible("div.certificate-widget") # cert view self.action_list_action('view', confirm=False, parents_css_sel="div.certificate-widget") self.assert_dialog() self.dialog_button_click('close') # cert get self.action_list_action('get', confirm=False, parents_css_sel="div.certificate-widget") self.assert_dialog() # check that the textarea is not empty self.assert_empty_value('textarea.certificate', negative=True) self.dialog_button_click('close') # cert download - we can only try to click the download action self.action_list_action('download', confirm=False, parents_css_sel="div.certificate-widget") # check that revoke action is not enabled self.assert_action_list_action( 'revoke', enabled=False, parents_css_sel="div.certificate-widget", facet_actions=False) # check that remove_hold action is not enabled self.assert_action_list_action( 'remove_hold', enabled=False, parents_css_sel="div.certificate-widget", facet_actions=False) # cleanup self.navigate_to_entity(ENTITY, 'search') self.delete_record(self.pkey, self.data.get('del')) @screenshot def test_ca_less(self): """ Test host certificate actions in CA-less install http://www.freeipa.org/page/V3/CA-less_install """ if self.has_ca(): self.skip('CA is installed') self.init_app() self.add_record(ENTITY, self.data) self.navigate_to_record(self.pkey) self.assert_action_list_action('request_cert', visible=False) self.navigate_by_breadcrumb('Hosts') self.delete_record(self.pkey, self.data.get('del')) @screenshot def test_kerberos_flags(self): """ Test Kerberos flags http://www.freeipa.org/page/V3/Kerberos_Flags """ name = 'ipakrbokasdelegate' mod = {'mod': [('checkbox', name, None)]} checked = ['checked'] self.init_app() self.add_record(ENTITY, self.data) self.navigate_to_record(self.pkey) if self.get_field_checked(name) == checked: self.mod_record(ENTITY, mod) # uncheck self.mod_record(ENTITY, mod) self.validate_fields([('checkbox', name, checked)]) self.mod_record(ENTITY, mod) self.validate_fields([('checkbox', name, [])]) self.close_notifications() self.delete(ENTITY, [self.data]) @screenshot def test_associations(self): """ Host direct associations """ self.init_app() # prepare # ------- self.add_record(ENTITY, self.data) self.add_record(ENTITY, self.data2, navigate=False) self.add_record(hostgroup.ENTITY, hostgroup.DATA) self.add_record(netgroup.ENTITY, netgroup.DATA) self.add_record(rbac.ROLE_ENTITY, rbac.ROLE_DATA) self.add_record(hbac.RULE_ENTITY, hbac.RULE_DATA) self.add_record(sudo.RULE_ENTITY, sudo.RULE_DATA) # add & remove associations # ------------------------- self.navigate_to_entity(ENTITY) self.navigate_to_record(self.pkey) self.add_associations([hostgroup.PKEY], facet='memberof_hostgroup', delete=True) self.add_associations([netgroup.PKEY], facet='memberof_netgroup', delete=True) self.add_associations([rbac.ROLE_PKEY], facet='memberof_role', delete=True) self.add_associations([hbac.RULE_PKEY], facet='memberof_hbacrule', delete=True) self.add_associations([sudo.RULE_PKEY], facet='memberof_sudorule', delete=True) self.add_associations([self.pkey2], facet='managedby_host', delete=True) # cleanup # ------- self.delete(ENTITY, [self.data, self.data2]) self.delete(hostgroup.ENTITY, [hostgroup.DATA]) self.delete(netgroup.ENTITY, [netgroup.DATA]) self.delete(rbac.ROLE_ENTITY, [rbac.ROLE_DATA]) self.delete(hbac.RULE_ENTITY, [hbac.RULE_DATA]) self.delete(sudo.RULE_ENTITY, [sudo.RULE_DATA]) @screenshot def test_indirect_associations(self): """ Host indirect associations """ self.init_app() # add # --- self.add_record(ENTITY, self.data) self.add_record(hostgroup.ENTITY, hostgroup.DATA) self.navigate_to_record(hostgroup.PKEY) self.add_associations([self.pkey]) self.add_record(hostgroup.ENTITY, hostgroup.DATA2) self.navigate_to_record(hostgroup.PKEY2) self.switch_to_facet('member_hostgroup') self.add_associations([hostgroup.PKEY]) self.add_record(netgroup.ENTITY, netgroup.DATA) self.navigate_to_record(netgroup.PKEY) self.add_table_associations('memberhost_hostgroup', [hostgroup.PKEY2]) self.add_record(rbac.ROLE_ENTITY, rbac.ROLE_DATA) self.navigate_to_record(rbac.ROLE_PKEY) self.switch_to_facet('member_hostgroup') self.add_associations([hostgroup.PKEY2]) self.add_record(hbac.RULE_ENTITY, hbac.RULE_DATA) self.navigate_to_record(hbac.RULE_PKEY) self.add_table_associations('memberhost_hostgroup', [hostgroup.PKEY2]) self.add_record(sudo.RULE_ENTITY, sudo.RULE_DATA) self.navigate_to_record(sudo.RULE_PKEY) self.add_table_associations('memberhost_hostgroup', [hostgroup.PKEY2]) # check indirect associations # --------------------------- self.navigate_to_entity(ENTITY, 'search') self.navigate_to_record(self.pkey) self.assert_indirect_record(hostgroup.PKEY2, ENTITY, 'memberof_hostgroup') self.assert_indirect_record(netgroup.PKEY, ENTITY, 'memberof_netgroup') self.assert_indirect_record(rbac.ROLE_PKEY, ENTITY, 'memberof_role') self.assert_indirect_record(hbac.RULE_PKEY, ENTITY, 'memberof_hbacrule') self.assert_indirect_record(sudo.RULE_PKEY, ENTITY, 'memberof_sudorule') # cleanup # ------- self.delete(ENTITY, [self.data]) self.delete(hostgroup.ENTITY, [hostgroup.DATA, hostgroup.DATA2]) self.delete(netgroup.ENTITY, [netgroup.DATA]) self.delete(rbac.ROLE_ENTITY, [rbac.ROLE_DATA]) self.delete(hbac.RULE_ENTITY, [hbac.RULE_DATA]) self.delete(sudo.RULE_ENTITY, [sudo.RULE_DATA]) @screenshot def test_buttons(self): """Test buttons""" self.init_app() self.navigate_to_entity(ENTITY) # add with enter key self.navigate_to_entity(ENTITY) self.button_click('add') self.fill_textbox("hostname", self.pkey) self.check_option('force') actions = ActionChains(self.driver) actions.send_keys(Keys.ENTER).perform() self.wait_for_request(n=3) self.assert_record(self.pkey) # add and another self.add_record(ENTITY, [self.data2, self.data3]) # add and edit record self.add_record(ENTITY, self.data4, dialog_btn='add_and_edit') self.assert_facet(ENTITY, facet="details") # cancel managedby self.add_associations([self.pkey3], facet='managedby_host', confirm_btn="cancel") self.wait() self.select_record(self.pkey4, table_name='fqdn') self.button_click('remove') self.dialog_button_click('cancel') self.assert_record(self.pkey4) # add duplicate self.add_record(ENTITY, self.data2, negative=True, pre_delete=False) dialog_info = self.get_dialog_info() expected_msg = 'host with name "' + self.data2['pkey'] + \ '" already exist' if expected_msg in dialog_info['text']: self.dialog_button_click('cancel') self.dialog_button_click('cancel') else: assert False, "Duplicate dialog missing or have wrong text." # duplicate with pressed keys self.add_record(ENTITY, self.data2, negative=True, pre_delete=False) self.wait() actions = ActionChains(self.driver) actions.send_keys(Keys.TAB).perform() self.wait() actions = ActionChains(self.driver) actions.send_keys(Keys.ENTER).perform() self.wait(2) self.dialog_button_click('cancel') self.assert_no_dialog() # remove multiple self.navigate_to_entity(ENTITY) self.select_multiple_records([self.data2, self.data3, self.data4]) self.facet_button_click('remove') self.wait() self.check_option('updatedns') self.dialog_button_click('ok') self.assert_notification() self.close_notifications() # remove without updatedns self.select_record(self.pkey) self.facet_button_click('remove') self.dialog_button_click('ok') self.assert_notification() self.close_notifications() @screenshot def test_negative_add_input(self): """ Test field validations for adding """ self.init_app() # wrong hostname input hosts_tests = [host.hostname_tilde, host.hostname_trailing_space, host.hostname_dash] for hostname_test in hosts_tests: self.add_record(ENTITY, hostname_test, negative=True) dialog_info = self.get_dialog_info() if host.BAD_HOSTNAME_MSG in dialog_info['text']: self.dialog_button_click('cancel') self.dialog_button_click('cancel') # leading space in hostname self.add_record(ENTITY, host.hostname_leading_space, negative=True) dialog_info = self.get_dialog_info() if host.BAS_HOSTNAME_SPACE_MSG in dialog_info['text']: self.dialog_button_click('cancel') self.dialog_button_click('cancel') # empty hostname self.add_record(ENTITY, host.empty_hostname, negative=True) self.assert_field_validation_required(field='hostname') self.dialog_button_click('cancel') # empty domain self.add_record(ENTITY, host.empty_domain, negative=True) self.assert_field_validation_required(field='dnszone') self.dialog_button_click('cancel') # Wrong IP input ip_tests = [host.ip_alpha, host.ip_many_oct, host.ip_bad_oct, host.ip_special_char] for ip_test in ip_tests: self.add_record(ENTITY, ip_test, negative=True) self.assert_field_validation(host.BAD_IP_MSG, field='ip_address') self.dialog_button_click('cancel') @screenshot def test_details_input(self): """ Test text fields in details page """ self.init_app() self.add_record(ENTITY, self.data2) self.navigate_to_record(self.data2['pkey'], entity=ENTITY) # modify modify_tests = [host.mod_desc, host.mod_locality, host.mod_location, host.mod_platform, host.mod_os] for mod_test in modify_tests: self.fill_fields(mod_test) self.button_click('save') self.assert_notification() self.close_notifications() self.fill_fields(host.mod_desc_m) self.click_undo_button('description') self.delete(ENTITY, [self.data2]) # otp set_otp otp_tests = [host.otp_alpha, host.otp_num, host.otp_alphanum, host.otp_special, host.otp_mixed] for otp_test in otp_tests: self.add_record(ENTITY, self.data2) self.close_notifications() self.navigate_to_record(self.data2['pkey'], entity=ENTITY) self.action_list_action('set_otp', confirm=False) self.fill_fields(otp_test) self.dialog_button_click('confirm') self.assert_notification() self.close_notifications() self.delete(ENTITY, [self.data2]) self.close_notifications() # otp cancel and reset self.add_record(ENTITY, self.data2) self.navigate_to_record(self.data2['pkey'], entity=ENTITY) self.action_list_action('set_otp', confirm=False) self.assert_dialog() self.dialog_button_click('cancel') self.assert_no_dialog() self.navigate_to_record(self.data2['pkey'], entity=ENTITY) self.action_list_action('set_otp', confirm=False) self.fill_fields(host.otp_alpha) self.dialog_button_click('confirm') self.assert_notification() self.close_notifications() self.action_list_action('reset_otp', confirm=False) self.assert_dialog() self.dialog_button_click('cancel') self.assert_no_dialog() # cleanup self.delete(ENTITY, [self.data2]) @screenshot def test_sshkey(self): """ Test ssh keys """ self.init_app() self.add_record(ENTITY, self.data2) self.close_notifications() # add dsa key self.add_sshkey_to_record(host.ssh_dsa, self.data2['pkey'], entity=ENTITY, navigate=True) self.assert_notification() self.close_notifications() # delete ssh key self.delete_record_sshkeys(self.data2['pkey'], entity=ENTITY, navigate=True) # add rsa key self.add_sshkey_to_record(host.ssh_rsa, self.data2['pkey'], entity=ENTITY, navigate=True) self.assert_notification() self.close_notifications() # negative ssh key input neg_key_tests = [host.ssh_empty, host.ssh_rsa] for key in neg_key_tests: self.add_sshkey_to_record(key, self.data2['pkey'], entity=ENTITY, navigate=True) self.assert_dialog() dialog_info = self.get_dialog_info() if host.ssh_nomod_error in dialog_info['text']: self.dialog_button_click('cancel') # invalid ssh key self.add_sshkey_to_record(host.ssh_invalid, self.data2['pkey'], entity=ENTITY, navigate=True) self.assert_dialog() dialog_info = self.get_dialog_info() if host.ssh_invalid_error in dialog_info['text']: self.dialog_button_click('cancel') # undo all and delete ssh keys self.undo_ssh_keys(btn_name='undo_all') self.delete_record_sshkeys(self.data2['pkey'], entity=ENTITY) # undo self.add_sshkey_to_record(host.ssh_rsa, self.data2['pkey'], entity=ENTITY, navigate=True, save=False) self.undo_ssh_keys() # refresh self.add_sshkey_to_record(host.ssh_rsa, self.data2['pkey'], entity=ENTITY, navigate=True, save=False) self.facet_button_click('refresh') self.assert_num_ssh_keys(0) # revert self.add_sshkey_to_record(host.ssh_rsa, self.data2['pkey'], entity=ENTITY, navigate=True, save=False) self.facet_button_click('revert') self.assert_num_ssh_keys(0) # cleanup self.delete(ENTITY, [self.data2]) @screenshot def test_negative_cert(self): """ Test negative CSR """ self.init_app() self.add_record(ENTITY, self.data2) self.close_notifications() self.navigate_to_record(self.data2['pkey'], entity=ENTITY) # emtpy CSR csr_add = 'div[name="certificate"] button[name="add"]' csr_add_btn = self.find(csr_add, By.CSS_SELECTOR, strict=True) csr_add_btn.click() self.wait() self.dialog_button_click('ok') self.assert_field_validation_required() self.dialog_button_click('cancel') # invalid CSR csr_add = 'div[name="certificate"] button[name="add"]' csr_add_btn = self.find(csr_add, By.CSS_SELECTOR, strict=True) csr_add_btn.click() self.wait() self.fill_textarea('new_cert', host.csr_invalid) self.dialog_button_click('ok') dialog_info = self.get_dialog_info() self.wait() if host.csr_invalid_error in dialog_info['text']: self.dialog_button_click('cancel') self.dialog_button_click('cancel') # other hostname CSR self.action_list_action('request_cert', confirm=False) self.assert_dialog() self.fill_text("textarea[name='csr']", host.csr_other_host) self.dialog_button_click('issue') dialog_info = self.get_dialog_info() if host.csr_other_host_error in dialog_info['text']: self.dialog_button_click('cancel') self.dialog_button_click('cancel') # cleanup self.delete(ENTITY, [self.data2]) @screenshot def test_keytab(self): """ Test keytab """ self.init_app() self.add_record(ENTITY, self.data2) # provision keytab kt_tmp = '/tmp/test.keytab' hostname = self.data2['pkey'] realm = self.config.get('ipa_realm') principal = 'host/{}@{}'.format(hostname, realm) self.run_cmd_on_ui_host('/usr/sbin/ipa-getkeytab ' '-p {} ' '-k {} '.format(principal, kt_tmp)) self.navigate_to_record(hostname, entity=ENTITY) self.wait(3) enroll = 'div[name="has_keytab"] label[name="present"]' self.assert_text(enroll, host.krb_enrolled) # test cancel button exist self.action_list_action('unprovision', confirm=False) self.dialog_button_click('cancel') # unprovision keytab self.action_list_action('unprovision', confirm=False) self.dialog_button_click('unprovision') self.wait_for_request(n=4) self.facet_button_click('refresh') enroll = 'div[name="has_keytab"] label[name="missing"]' self.assert_text(enroll, host.krb_not_enrolled) # cleanup self.delete(ENTITY, [self.data2]) def test_search(self): self.init_app() self.navigate_to_entity(ENTITY) self.add_record(ENTITY, [self.data2, self.data3]) # positive search filter self.fill_search_filter(self.pkey2) actions = ActionChains(self.driver) actions.send_keys(Keys.ENTER).perform() self.wait(0.5) self.assert_record(self.pkey2) # negative search filter self.fill_search_filter(self.pkey3) actions = ActionChains(self.driver) actions.send_keys(Keys.ENTER).perform() self.wait(0.5) self.assert_record(self.pkey4, negative=True) # cleanup self.fill_search_filter('') actions = ActionChains(self.driver) actions.send_keys(Keys.ENTER).perform() self.wait(0.5) self.delete_record([self.pkey2, self.pkey3])
28,012
Python
.py
662
31.851964
88
0.600698
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,387
test_hostgroup.py
freeipa_freeipa/ipatests/test_webui/test_hostgroup.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Hostgroup tests """ from ipatests.test_webui.ui_driver import UI_driver from ipatests.test_webui.ui_driver import screenshot import ipatests.test_webui.data_group as group import ipatests.test_webui.data_hostgroup as hostgroup from ipatests.test_webui.test_host import host_tasks, ENTITY as HOST_ENTITY import ipatests.test_webui.data_netgroup as netgroup import ipatests.test_webui.data_hbac as hbac import ipatests.test_webui.data_sudo as sudo import ipatests.test_webui.data_user as user import pytest def check_invalid_names(self, names, error_link): self.navigate_to_entity(hostgroup.ENTITY) for name in names: self.button_click(name='add') self.fill_input('cn', name) text_warning = self.get_text('.help-block', parent=self.get_dialog()) assert text_warning in error_link self.dialog_button_click(name='cancel') @pytest.mark.tier1 class test_hostgroup(UI_driver): @screenshot def test_crud(self): """ Basic CRUD: hostgroup """ self.init_app() self.basic_crud(hostgroup.ENTITY, hostgroup.DATA, default_facet=hostgroup.DEFAULT_FACET) @screenshot def test_associations(self): """ Hostgroup associations """ self.init_app() host = host_tasks() host.driver = self.driver host.config = self.config host.prep_data2() # prepare # ------- self.add_record(hostgroup.ENTITY, hostgroup.DATA) self.add_record(hostgroup.ENTITY, hostgroup.DATA2, navigate=False) self.add_record(hostgroup.ENTITY, hostgroup.DATA3, navigate=False) self.add_record(HOST_ENTITY, host.data2) self.add_record(netgroup.ENTITY, netgroup.DATA) self.add_record(hbac.RULE_ENTITY, hbac.RULE_DATA) self.add_record(sudo.RULE_ENTITY, sudo.RULE_DATA) # add & remove associations # ------------------------- self.navigate_to_entity(hostgroup.ENTITY) self.navigate_to_record(hostgroup.PKEY) # members self.add_associations([hostgroup.PKEY2], facet='member_hostgroup', delete=True) self.add_associations([host.pkey2], facet='member_host', delete=True) # member of self.add_associations([hostgroup.PKEY3], facet='memberof_hostgroup', delete=True) self.add_associations([netgroup.PKEY], facet='memberof_netgroup', delete=True) self.add_associations([hbac.RULE_PKEY], facet='memberof_hbacrule', delete=True) self.add_associations([sudo.RULE_PKEY], facet='memberof_sudorule', delete=True) # cleanup # ------- self.delete(hostgroup.ENTITY, [hostgroup.DATA, hostgroup.DATA2, hostgroup.DATA3]) self.delete(HOST_ENTITY, [host.data2]) self.delete(netgroup.ENTITY, [netgroup.DATA]) self.delete(hbac.RULE_ENTITY, [hbac.RULE_DATA]) self.delete(sudo.RULE_ENTITY, [sudo.RULE_DATA]) @screenshot def test_indirect_associations(self): """ Hostgroup indirect associations """ self.init_app() host = host_tasks() host.driver = self.driver host.config = self.config host.prep_data2() # add # --- self.add_record(hostgroup.ENTITY, hostgroup.DATA) self.add_record(hostgroup.ENTITY, hostgroup.DATA2, navigate=False) self.add_record(hostgroup.ENTITY, hostgroup.DATA3, navigate=False) self.add_record(hostgroup.ENTITY, hostgroup.DATA4, navigate=False) self.add_record(hostgroup.ENTITY, hostgroup.DATA5, navigate=False) self.add_record(HOST_ENTITY, host.data2) # prepare indirect member self.navigate_to_entity(hostgroup.ENTITY, 'search') self.navigate_to_record(hostgroup.PKEY2) self.add_associations([host.pkey2]) self.add_associations([hostgroup.PKEY3], 'member_hostgroup') self.navigate_to_entity(hostgroup.ENTITY, 'search') self.navigate_to_record(hostgroup.PKEY) self.add_associations([hostgroup.PKEY2], 'member_hostgroup') # prepare indirect memberof self.navigate_to_entity(hostgroup.ENTITY, 'search') self.navigate_to_record(hostgroup.PKEY4) self.add_associations([hostgroup.PKEY], 'member_hostgroup') self.add_associations([hostgroup.PKEY5], 'memberof_hostgroup') self.add_record(hbac.RULE_ENTITY, hbac.RULE_DATA) self.navigate_to_record(hbac.RULE_PKEY) self.add_table_associations('memberhost_hostgroup', [hostgroup.PKEY4]) self.add_record(sudo.RULE_ENTITY, sudo.RULE_DATA) self.navigate_to_record(sudo.RULE_PKEY) self.add_table_associations('memberhost_hostgroup', [hostgroup.PKEY4]) # check indirect associations # --------------------------- self.navigate_to_entity(hostgroup.ENTITY, 'search') self.navigate_to_record(hostgroup.PKEY) self.assert_indirect_record(hostgroup.PKEY3, hostgroup.ENTITY, 'member_hostgroup') self.assert_indirect_record(host.pkey2, hostgroup.ENTITY, 'member_host') self.assert_indirect_record(hostgroup.PKEY5, hostgroup.ENTITY, 'memberof_hostgroup') self.assert_indirect_record(hbac.RULE_PKEY, hostgroup.ENTITY, 'memberof_hbacrule') self.assert_indirect_record(sudo.RULE_PKEY, hostgroup.ENTITY, 'memberof_sudorule') # cleanup # ------- self.delete(hostgroup.ENTITY, [hostgroup.DATA, hostgroup.DATA2, hostgroup.DATA3, hostgroup.DATA4, hostgroup.DATA5]) self.delete(HOST_ENTITY, [host.data2]) self.delete(hbac.RULE_ENTITY, [hbac.RULE_DATA]) self.delete(sudo.RULE_ENTITY, [sudo.RULE_DATA]) @screenshot def test_member_manager_user(self): """ Test member manager user has permissions to add and remove host group members """ self.init_app() host = host_tasks() host.driver = self.driver host.config = self.config host.prep_data2() self.add_record(user.ENTITY, [user.DATA_MEMBER_MANAGER]) self.add_record(HOST_ENTITY, host.data2) self.add_record(hostgroup.ENTITY, hostgroup.DATA) self.navigate_to_record(hostgroup.PKEY) self.add_associations([user.PKEY_MEMBER_MANAGER], facet='membermanager_user') # try to add host to group with member manager permissions self.logout() self.login(user.PKEY_MEMBER_MANAGER, user.PASSWD_MEMBER_MANAGER) self.navigate_to_record(hostgroup.PKEY, entity=hostgroup.ENTITY) self.add_associations([host.pkey2], delete=True) # re-login as admin and clean up data self.logout() self.init_app() self.delete(HOST_ENTITY, [host.data2]) self.delete(user.ENTITY, [user.DATA_MEMBER_MANAGER]) self.delete(hostgroup.ENTITY, [hostgroup.DATA]) @screenshot def test_member_manager_group(self): """ Test member managers group has permissions to add and remove host group members """ self.init_app() host = host_tasks() host.driver = self.driver host.config = self.config host.prep_data2() self.add_record(user.ENTITY, user.DATA_MEMBER_MANAGER) self.add_record(group.ENTITY, [group.DATA2]) self.navigate_to_record(group.PKEY2) self.add_associations([user.PKEY_MEMBER_MANAGER], facet='member_user') self.add_record(HOST_ENTITY, host.data2) self.add_record(hostgroup.ENTITY, hostgroup.DATA) self.navigate_to_record(hostgroup.PKEY) self.add_associations([group.PKEY2], facet='membermanager_group') # try to add host to group with member manager permissions self.logout() self.login(user.PKEY_MEMBER_MANAGER, user.PASSWD_MEMBER_MANAGER) self.navigate_to_record(hostgroup.PKEY, entity=hostgroup.ENTITY) self.add_associations([host.pkey2], delete=True) # re-login as admin and clean up data self.logout() self.init_app() self.delete(HOST_ENTITY, [host.data2]) self.delete(user.ENTITY, [user.DATA_MEMBER_MANAGER]) self.delete(group.ENTITY, [group.DATA2]) self.delete(hostgroup.ENTITY, [hostgroup.DATA]) @screenshot def test_names_and_button(self): """ Hostgroup names and buttons """ self.init_app() host = host_tasks() host.driver = self.driver host.config = self.config self.add_record(hostgroup.ENTITY, hostgroup.DATA6) self.add_record(hostgroup.ENTITY, hostgroup.DATA7, navigate=False) self.add_record(hostgroup.ENTITY, hostgroup.DATA8, navigate=False) # test invalid names invalid_names = [hostgroup.LEADING_SPACE, hostgroup.TRAILING_SPACE, hostgroup.NAME_SPACE] check_invalid_names(self, invalid_names, hostgroup.CHAR_WARNING_MSG) invalid_names = [hostgroup.PKEY6] check_invalid_names(self, invalid_names, hostgroup.DUPLICATE_WARNING_MSG) # test invalid description self.button_click(name='add') self.fill_input('cn', hostgroup.PKEY) self.fill_textarea('description', hostgroup.LEADING_SPACE) self.dialog_button_click('add') assert hostgroup.DESCRIPTION_ERROR_DIALOG in \ self.get_last_error_dialog().text self.dialog_button_click('cancel') self.wait() self.fill_textarea('description', hostgroup.TRAILING_SPACE) self.dialog_button_click('add') assert hostgroup.DESCRIPTION_ERROR_DIALOG in \ self.get_last_error_dialog().text self.dialog_button_click('cancel') self.wait(0.6) # wait for modal dialog to appear self.dialog_button_click('cancel') # duplicate self.button_click(name='add') self.fill_input('cn', hostgroup.PKEY6) self.dialog_button_click('add') assert hostgroup.DUPLICATE_WARNING_MSG in \ self.get_last_error_dialog().text self.dialog_button_click('cancel') self.dialog_button_click('cancel') self.button_click(name='add') self.fill_input('cn', "") self.dialog_button_click('add') text_warning = self.get_text('.help-block', parent=self.get_dialog()) assert text_warning in hostgroup.EMPTY_WARNING_MSG self.dialog_button_click(name='cancel') # test buttons self.button_click('add') self.fill_input('cn', hostgroup.DATA['pkey']) self.dialog_button_click(name='add_and_add_another') self.wait_for_request(n=3) self.fill_input('cn', hostgroup.DATA2['pkey']) self.dialog_button_click(name='add_and_edit') self.wait_for_request(n=4) self.navigate_to_entity(hostgroup.ENTITY) self.button_click('add') self.fill_input('cn', hostgroup.DATA['pkey']) self.dialog_button_click('cancel') self.select_record(hostgroup.PKEY) self.button_click('remove') self.dialog_button_click('cancel') self.wait() self.select_record(hostgroup.PKEY, unselect=True) # test to rewrite invalid input_type self.button_click('add') self.fill_input('cn', hostgroup.LEADING_SPACE) self.fill_input('cn', hostgroup.PKEY3) self.dialog_button_click('add') self.wait_for_request(n=3) self.button_click('add') self.fill_input('cn', hostgroup.TRAILING_SPACE) self.fill_input('cn', hostgroup.PKEY4) self.dialog_button_click('add') self.wait_for_request(n=3) # multiple delete clean up self.select_record(hostgroup.PKEY6.lower()) self.select_record(hostgroup.PKEY7.lower()) self.button_click('remove') self.dialog_button_click('ok') # clean up self.delete(hostgroup.ENTITY, [hostgroup.DATA, hostgroup.DATA2, hostgroup.DATA3, hostgroup.DATA4, hostgroup.DATA8])
13,031
Python
.py
287
36.557491
92
0.655974
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,388
data_netgroup.py
freeipa_freeipa/ipatests/test_webui/data_netgroup.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ENTITY = 'netgroup' PKEY = 'itest-netgroup' DATA = { 'pkey': PKEY, 'add': [ ('textbox', 'cn', PKEY), ('textarea', 'description', 'test-netgroup desc'), ], 'mod': [ ('textarea', 'description', 'test-netgroup desc modified'), ], } PKEY2 = 'itest-netgroup2' DATA2 = { 'pkey': PKEY2, 'add': [ ('textbox', 'cn', PKEY2), ('textarea', 'description', 'test-netgroup2 desc'), ], 'mod': [ ('textarea', 'description', 'test-netgroup2 desc modified'), ], } PKEY3 = 'itest-netgroup3' DATA3 = { 'pkey': PKEY3, 'add': [ ('textbox', 'cn', PKEY3), ('textarea', 'description', 'test-netgroup3 desc'), ] } PKEY4 = 'itest-netgroup4' DATA4 = { 'pkey': PKEY4, 'add': [ ('textbox', 'cn', PKEY4), ('textarea', 'description', 'test-netgroup4 desc'), ] } PKEY5 = 'NewNetGroup' DATA_MIXED_CASE = { 'pkey': PKEY5, 'add': [ ('textbox', 'cn', PKEY5), ('textarea', 'description', 'Trying to add mixed case netgroup name'), ] } PKEY6 = 'long-netgroup-name_{}'.format('long' * 15) DATA_LONG_NAME = { 'pkey': PKEY6, 'add': [ ('textbox', 'cn', PKEY6), ('textarea', 'description', 'Trying to add long netgroup name'), ] } PKEY7 = 'a' DATA_SINGLE_CHAR = { 'pkey': PKEY7, 'add': [ ('textbox', 'cn', PKEY7), ('textarea', 'description', 'Trying to add single character netgroup' ' name'), ] } PKEY8 = 'itest-netgroup8' DATA8 = { 'pkey': PKEY8, 'add': [ ('textbox', 'cn', PKEY8), ('textarea', 'description', 'test-netgroup8 desc'), ], 'mod': [ ('textarea', 'description', 'description modified for testing buttons' ), ], }
2,580
Python
.py
94
22.989362
78
0.604923
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,389
test_delegation.py
freeipa_freeipa/ipatests/test_webui/test_delegation.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Delegation tests """ from ipatests.test_webui.ui_driver import UI_driver from ipatests.test_webui.ui_driver import screenshot import pytest ENTITY = 'delegation' PKEY = 'itest-delegation-rule' DATA = { 'pkey': PKEY, 'add': [ ('textbox', 'aciname', PKEY), ('combobox', 'group', 'editors'), ('combobox', 'memberof', 'ipausers'), ('checkbox', 'attrs', 'audio'), ('checkbox', 'attrs', 'businesscategory'), ], 'mod': [ ('checkbox', 'attrs', 'businesscategory'), ], } @pytest.mark.tier1 class test_delegation(UI_driver): @screenshot def test_crud(self): """ Basic CRUD: delegation """ self.init_app() self.basic_crud(ENTITY, DATA)
1,525
Python
.py
48
28.208333
71
0.689796
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,390
data_user.py
freeipa_freeipa/ipatests/test_webui/data_user.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ENTITY = 'user' PKEY = 'itest-user' DATA = { 'pkey': PKEY, 'add': [ ('textbox', 'uid', PKEY), ('textbox', 'givenname', 'Name'), ('textbox', 'sn', 'Surname'), ], 'add_v': [ ('textbox', 'givenname', 'Name'), ('textbox', 'sn', 'Surname'), ('label', 'uid', PKEY), ], 'mod': [ ('textbox', 'givenname', 'OtherName'), ('textbox', 'sn', 'OtherSurname'), ('textbox', 'initials', 'NOS'), ('textbox', 'loginshell', '/bin/csh'), ('textbox', 'homedirectory', '/home/alias'), ('multivalued', 'telephonenumber', [ ('add', '123456789'), ('add', '987654321'), ]), ('multivalued', 'mail', [ ('add', 'one@ipa.test'), ('add', 'two@ipa.test'), ('add', 'three@ipa.test'), ]), ('multivalued', 'pager', [ ('add', '1234567'), ('add', '7654321'), ]), ('multivalued', 'mobile', [ ('add', '001123456'), ('add', '001654321'), ]), ('multivalued', 'facsimiletelephonenumber', [ ('add', '1122334'), ('add', '4332211'), ]), ('textbox', 'street', 'Wonderwall ave.'), ('textbox', 'l', 'Atlantis'), ('textbox', 'st', 'Universe'), ('textbox', 'postalcode', '61600'), ('multivalued', 'carlicense', [ ('add', 'ZLA-1336'), ]), ('textbox', 'ou', 'QE'), ('combobox', 'manager', 'admin'), ('textbox', 'employeenumber', '123'), ('textbox', 'employeetype', 'contractor'), ('textbox', 'preferredlanguage', 'Spanish'), ], 'mod_v': [ ('textbox', 'givenname', 'OtherName'), ('textbox', 'sn', 'OtherSurname'), ('textbox', 'initials', 'NOS'), ('textbox', 'loginshell', '/bin/csh'), ('textbox', 'homedirectory', '/home/alias'), ('label', 'krbmaxrenewableage', '604800'), ('label', 'krbmaxticketlife', '86400'), ('multivalued', 'telephonenumber', ['123456789', '987654321']), ('multivalued', 'mail', ['one@ipa.test', 'two@ipa.test', 'three@ipa.test']), ('multivalued', 'pager', ['1234567', '7654321']), ('multivalued', 'mobile', ['001123456', '001654321']), ('multivalued', 'facsimiletelephonenumber', ['1122334', '4332211']), ('textbox', 'street', 'Wonderwall ave.'), ('textbox', 'l', 'Atlantis'), ('textbox', 'st', 'Universe'), ('textbox', 'postalcode', '61600'), ('multivalued', 'carlicense', ['ZLA-1336']), ('textbox', 'ou', 'QE'), ('combobox', 'manager', 'admin'), ('textbox', 'employeenumber', '123'), ('textbox', 'employeetype', 'contractor'), ('textbox', 'preferredlanguage', 'Spanish'), ], } PKEY2 = 'itest-user2' DATA2 = { 'pkey': PKEY2, 'add': [ ('textbox', 'uid', PKEY2), ('textbox', 'givenname', 'Name2'), ('textbox', 'sn', 'Surname2'), ], 'mod': [ ('textbox', 'givenname', 'OtherName2'), ('textbox', 'sn', 'OtherSurname2'), ('textbox', 'postalcode', '007007'), ], } PKEY3 = 'itest-user3' DATA3 = { 'pkey': PKEY3, 'add': [ ('textbox', 'uid', PKEY3), ('textbox', 'givenname', 'Name3'), ('textbox', 'sn', 'Surname3'), ('checkbox', 'noprivate', None), ] } PKEY4 = 'itest-user4' DATA4 = { 'pkey': PKEY4, 'add': [ ('textbox', 'uid', PKEY4), ('textbox', 'givenname', 'Name4'), ('textbox', 'sn', 'Surname4'), ('checkbox', 'noprivate', None), ('combobox', 'gidnumber', '77777'), ] } PKEY_SPECIAL_CHARS = '1spe.cial_us-er$' PASSWD_SCECIAL_CHARS = '!!!@@@###$$$' DATA_SPECIAL_CHARS = { 'pkey': PKEY_SPECIAL_CHARS, 'add': [ ('textbox', 'uid', PKEY_SPECIAL_CHARS), ('textbox', 'givenname', 'S$p|e>c--i_a%l_'), ('textbox', 'sn', '%U&s?e+r'), ('password', 'userpassword', PASSWD_SCECIAL_CHARS), ('password', 'userpassword2', PASSWD_SCECIAL_CHARS), ] } PKEY_LONG_LOGIN = 'itest-user' * 5 DATA_LONG_LOGIN = { 'pkey': PKEY_LONG_LOGIN, 'add': [ ('textbox', 'uid', PKEY_LONG_LOGIN), ('textbox', 'givenname', 'Name8'), ('textbox', 'sn', 'Surname8'), ] } PKEY_PASSWD_LEAD_SPACE = 'itest-user-passwd-leading-space' DATA_PASSWD_LEAD_SPACE = { 'pkey': PKEY_PASSWD_LEAD_SPACE, 'add': [ ('textbox', 'uid', PKEY_PASSWD_LEAD_SPACE), ('textbox', 'givenname', 'Name7'), ('textbox', 'sn', 'Surname7'), ('password', 'userpassword', ' Password123 '), ('password', 'userpassword2', ' Password123 '), ] } PKEY_PASSWD_TRAIL_SPACE = 'itest-user-passwd-trailing-space' DATA_PASSWD_TRAIL_SPACE = { 'pkey': PKEY_PASSWD_TRAIL_SPACE, 'add': [ ('textbox', 'uid', PKEY_PASSWD_TRAIL_SPACE), ('textbox', 'givenname', 'Name8'), ('textbox', 'sn', 'Surname8'), ('password', 'userpassword', 'Password123 '), ('password', 'userpassword2', 'Password123 '), ] } PKEY_PASSWD_MISMATCH = 'itest-user-passwd-mismatch' DATA_PASSWD_MISMATCH = { 'pkey': PKEY_PASSWD_MISMATCH, 'add': [ ('textbox', 'uid', PKEY_PASSWD_MISMATCH), ('textbox', 'givenname', 'Name9'), ('textbox', 'sn', 'Surname9'), ('password', 'userpassword', 'Password123'), ('password', 'userpassword2', 'Password12'), ] } PKEY_NO_LOGIN = 'itest-user-no-login' DATA_NO_LOGIN = { 'pkey': PKEY_NO_LOGIN, 'add': [ ('textbox', 'givenname', 'Name10'), ('textbox', 'sn', 'Surname10'), ('password', 'userpassword', 'Password123'), ('password', 'userpassword2', 'Password123'), ] } PKEY_MEMBER_MANAGER = 'member-manager' PASSWD_MEMBER_MANAGER = 'Password123' DATA_MEMBER_MANAGER = { 'pkey': PKEY_MEMBER_MANAGER, 'add': [ ('textbox', 'uid', PKEY_MEMBER_MANAGER), ('textbox', 'givenname', 'Name'), ('textbox', 'sn', 'Surname'), ('password', 'userpassword', PASSWD_MEMBER_MANAGER), ('password', 'userpassword2', PASSWD_MEMBER_MANAGER), ], } SSH_RSA = ( 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDBVmLXpTDhrYkABOPlADFk' 'GV8/QfgQqUQ0xn29hk18t/NTEQOW/Daq4EF84e9aTiopRXIk7jahBLzwWTZI' 'WwuvegGYqs89bDhUHZEnS9TBfXkkYq9LamlEVooR5kxb/kPtCnmMMXhQUOzH' 'xqakuZiN4AduRCzaecu0mearVjZWAChM3fYp4sMXKoRzek2F/xOUh81GxrW0' 'kbhpbaeXd6oG8p6AC3QCrEspzX78WEOCPSTJlx/BAv77A27b5zO2cSeZNbZq' 'XFqaQQj8AX46qoATWLhOnokoE2xeJTKikG/4nmc3D2KO6SRh66dEQWtJuVVw' 'ZqgQRdaseDjjgR1FKbC1' ) SSH_RSA2 = ( 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDBVmLXpTDhrYkABOPlADFk' 'GV8/QfgQqUQ0xn29hk18t/NTEQOW/Daq4EF84e9aTiopRXIk7jahBLzwWTZI' 'WwuvegGYqs89bDhUHZEnS9TBfXkkYq9LamlEVooR5kxb/kPtCnmMMXhQUOzH' 'xqakuZiN4AduRCzaecu0mearVjZWAChM3fYp4sMXKoRzek2F/xOUh81GxrW0' 'kbhpbaeXd6oG8p6AC3QCrEspzX78WEOCPSTJlx/BAv77A27b5zO2cSeZNbZq' 'XFqaQQj8AX46qoATWLhOnokoE2xeJTKikG/4nmc3D2KO6SRh66dEQWtJuVVw' 'ZqgQRdaseDjjgR1FK222' ) SSH_DSA = ( 'ssh-dss AAAAB3NzaC1kc3MAAACBAKSh2gHHQ0lsPEKZU7utlx3I/M8FtSMx' '+MtE+QjReRPIWHjwTHLC6j5Bh2A8kwwiiqiiiDbvkJPgV3+5zmrnWvTICzet' 'zS4vOgk6ymDux2J/1JPRb6c2yjjFaYL0SndC6abdgohyUAJPzNkgEhnQll/o' 'QeavJXzLyonaX1wcl+R1AAAAFQCuMfl69Zyrx5B1qZmUsRVqG24W7wAAAIEA' 'pFVe4JOuhRjSufJXMV+nzoqkhIhDEOYLqcpnq3cUrvBFEkQ5tKyYephFJxq+' 'u7xkFx4d/K5eC7NH6/o/ziBocKJ7ESXBihC2lGLsHnWqreN9vCBihspBij+n' '/wUpgcq2dMBDC2BzqCfdashM1xHm1XahqCvV87pvjRhl1avy+K0AAACAEQKs' '3kKhEB/WGuAQa+tojRyIwtBc4lzZuJia4qOg6R4oSviKINwEtFtH08snteGn' 'c4qiZ6XBrfYJT2VS1yjFVj+OmGSHmrX1GdfRfco8Y1ZYC7VLwt20dutw9hKK' 'MSHI9NrJ5oOZ/GONlaKuqzKtTNb/vOIn/8yz52Od3X2Ehh1=' ) USER_CERT = ( '-----BEGIN CERTIFICATE-----' 'MIIHUzCCBTugAwIBAgIRAMbkmDZJZqhTAAAAAFZl8D0wDQYJKoZIhvcNAQELBQAw' 'RDELMAkGA1UEBhMCSFIxHTAbBgNVBAoTFEZpbmFuY2lqc2thIGFnZW5jaWphMRYw' 'FAYDVQQDEw1GaW5hIFJEQyAyMDE1MB4XDTE5MTAxNDEyMTMyMFoXDTIxMTAxNDEy' 'MTMyMFowgakxCzAJBgNVBAYTAkhSMRQwEgYDVQQKEwtIT1BTIEQuTy5PLjEWMBQG' 'A1UEYRMNSFIxMzE0ODgyMTYzMzEPMA0GA1UEBxMGWkFHUkVCMQ8wDQYDVQQEEwZI' 'Uk5KQUsxEjAQBgNVBCoTCUtSVU5PU0xBVjEZMBcGA1UEAxMQS1JVTk9TTEFWIEhS' 'TkpBSzEbMBkGA1UEBRMSSFI1NzI4OTI5NDg5NC4yLjIxMIIBIjANBgkqhkiG9w0B' 'AQEFAAOCAQ8AMIIBCgKCAQEAig6HRn4uUvbUgFltOqWWo5OLnoWyuc6pAtBdaj+U' 'z3TM06ZVJtpnEsPsYPZ3iRLSUWz4ymkc+uv9YeWSbpOo0ft6UQ4HYN155DchpSgX' 'ycwgiJXMCyic61RcX05xNXfdnm4gJOeh8E46P3IEb2wKEj5rYe5Uk/ZJ59cPNu1e' '4rPKMTUH835awkyRCh1jWCXzWDowp8dl7kzroaotwRrJdxeL0taopyc9abUUm6kG' 'fTkdUbBw9uvFKq/uDJl+6IjmW2cMu8ZSPSctBDVEbySWk6yHW0ZXs+xvD+NYgBZT' '8Mqzc8LFhHT3ERYjf2JfZuWwQ9ODAfQOZr5nS5Me3hGWRwIDAQABo4IC2DCCAtQw' 'DgYDVR0PAQH/BAQDAgWgMB0GA1UdJQQWMBQGCCsGAQUFBwMEBggrBgEFBQcDAjCB' 'sAYDVR0gBIGoMIGlMIGYBgkrfIhQBQwMBAIwgYowQwYIKwYBBQUHAgEWN2h0dHA6' 'Ly9yZGMuZmluYS5oci9SREMyMDE1L0ZpbmFSREMyMDE1LUNQU05RQzEtMy1oci5w' 'ZGYwQwYIKwYBBQUHAgEWN2h0dHA6Ly9yZGMuZmluYS5oci9SREMyMDE1L0ZpbmFS' 'REMyMDE1LUNQU05RQzEtMy1lbi5wZGYwCAYGBACPegECMGkGCCsGAQUFBwEBBF0w' 'WzAfBggrBgEFBQcwAYYTaHR0cDovL29jc3AuZmluYS5ocjA4BggrBgEFBQcwAoYs' 'aHR0cDovL3JkYy5maW5hLmhyL1JEQzIwMTUvRmluYVJEQ0NBMjAxNS5jZXIwIwYD' 'VR0RBBwwGoEYa3J1bm9zbGF2Lmhybmpha0Bob3BzLmhyMIIBEwYDVR0fBIIBCjCC' 'AQYwgaSggaGggZ6GLGh0dHA6Ly9yZGMuZmluYS5oci9SREMyMDE1L0ZpbmFSREND' 'QTIwMTUuY3Jshm5sZGFwOi8vcmRjLWxkYXAyLmZpbmEuaHIvY249RmluYSUyMFJE' 'QyUyMDIwMTUsbz1GaW5hbmNpanNrYSUyMGFnZW5jaWphLGM9SFI/Y2VydGlmaWNh' 'dGVSZXZvY2F0aW9uTGlzdCUzQmJpbmFyeTBdoFugWaRXMFUxCzAJBgNVBAYTAkhS' 'MR0wGwYDVQQKExRGaW5hbmNpanNrYSBhZ2VuY2lqYTEWMBQGA1UEAxMNRmluYSBS' 'REMgMjAxNTEPMA0GA1UEAxMGQ1JMNzUxMB8GA1UdIwQYMBaAFBRjEbt7MwNodBwV' '7eYswTxIG5ghMB0GA1UdDgQWBBTsd+TYygvZpCDO4kDpEnMKUkZOfTAJBgNVHRME' 'AjAAMA0GCSqGSIb3DQEBCwUAA4ICAQBIhFElngJOz+K+Q1FZLhEVLngMI92k858M' 'W6WHJ17SXhiR/m/ESOM5mVkOyiOQoM1po1I/jdUjE2mHHjiT12tJgkavkDxXz6aX' 'hKdj9VDVnzSp0wRvzIgQKWJF0JO82umt0I9x265cGXmRnRjxnDbEmgGKdFeSTbkp' 'gJfk73rdRbkIEI7FoOIzuaIRcHRIREkfUltu/1zD+bCMSY2pFA/0FQ15dFUDAeiD' '6gqyjZgJJC5Rqd6SuMLfF4aAmz7FBgpk7iVm5jGRPltHCK3aH7OEczsDi1fYVtRA' 'PdRvKlzqbajv6Qj0YICMg3byh3ObN5xZp4qQmxGu9w7sJioMRP7DxxMuQKx4byV2' 'O0Jo7cdnc6BXfR+EipXz/phExWvRKwSOaelweOZUjz9sffpNYmvfuqmGhL5axNtj' 'XQmAJ1wOo8m7j4Czz7m7WFtxdiZ0SYGBxnr0xpCJrHgxLU640a/T/vDPh/SSai5S' 'E4unGGIf6vT0+5KY2gU6Jly7pqKpc44FHFrOdhWTEZzbmaiGL2QMh8VE2bAV9dNp' 'YT7djK+WY554vVLE3N7M21qiCNxD5awuIEkpZoF1d7A/wMgAe40ZMZ6UbYawzAPf' 'Tca3LXBLJOR4Ox2ZEbFt/JlIe7pZqR67s628axLaKCdQhOLP77KsNPMahzjQ7JmR' 'znZSOnBy/Q==' '-----END CERTIFICATE-----' )
11,462
Python
.py
283
34.448763
76
0.676223
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,391
test_automember.py
freeipa_freeipa/ipatests/test_webui/test_automember.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Automember tests """ from ipatests.test_webui.ui_driver import UI_driver, screenshot import ipatests.test_webui.data_hostgroup as hostgroup from ipatests.test_webui.test_host import host_tasks import pytest ENTITY = 'automember' USER_GROUP_PKEY = 'admins' USER_GROUP_DATA = { 'pkey': USER_GROUP_PKEY, 'add': [ ('combobox', 'cn', USER_GROUP_PKEY), ], 'mod': [ ('textarea', 'description', 'user group rule description'), ], } HOST_GROUP_DATA = { 'pkey': hostgroup.PKEY, 'add': [ ('combobox', 'cn', hostgroup.PKEY), ], 'mod': [ ('textarea', 'description', 'host group rule description'), ], } SEARCH_CASES = { 'name': 'search-123', 'description': 'Short description !@#$%^&*()', 'positive': [ 'search-123', 'search', 'search ', ' search', 'SEARCH', '123', '!@#$%^&*()', 'hort descr', 'description !', ], 'negative': [ 'searc-123', '321', 'search 123', 'search Short', 'description!', ], } # Condition types INCLUSIVE = 'inclusive' EXCLUSIVE = 'exclusive' rebuild_warning_msg = ('Are you sure you want to rebuild auto membership? ' 'In case of a high number of users, hosts or ' 'groups, the operation may require high CPU usage.') @pytest.mark.tier1 class TestAutomember(UI_driver): AUTOMEMBER_RULE_EXISTS_ERROR = ( 'Automember rule with name "{}" already exists' ) @pytest.fixture(autouse=True) def automember_setup(self, ui_driver_fsetup): self.init_app() def add_user_group_rules(self, *pkeys, **kwargs): # We implicitly trigger "Add and Add Another" by passing multiple # records to add_record method. # TODO: Create more transparent mechanism to test "Add <entity>" dialog self.add_record( ENTITY, [{ 'pkey': pkey, 'add': [('combobox', 'cn', pkey)], } for pkey in pkeys], facet='searchgroup', **kwargs ) def add_host_group_rules(self, *pkeys, **kwargs): self.add_record( ENTITY, [{ 'pkey': pkey, 'add': [('combobox', 'cn', pkey)], } for pkey in pkeys], facet='searchhostgroup', **kwargs ) def add_user(self, pkey, name, surname): self.add_record('user', { 'pkey': pkey, 'add': [ ('textbox', 'uid', pkey), ('textbox', 'givenname', name), ('textbox', 'sn', surname), ] }) def add_user_group(self, pkey, description=''): self.add_record('group', { 'pkey': pkey, 'add': [ ('textbox', 'cn', pkey), ('textarea', 'description', description), ] }) def add_host_group(self, pkey, description=''): self.add_record('hostgroup', { 'pkey': pkey, 'add': [ ('textbox', 'cn', pkey), ('textarea', 'description', description), ] }) def delete_users(self, *pkeys): self.delete('user', [{'pkey': pkey} for pkey in pkeys]) def delete_user_groups(self, *pkeys): self.delete('group', [{'pkey': pkey} for pkey in pkeys]) def delete_user_group_rules(self, *pkeys): self.delete(ENTITY, [{'pkey': pkey} for pkey in pkeys], facet='searchgroup') def delete_host_groups(self, *pkeys): self.delete('hostgroup', [{'pkey': pkey} for pkey in pkeys]) def delete_host_group_rules(self, *pkeys): self.delete(ENTITY, [{'pkey': pkey} for pkey in pkeys], facet='searchhostgroup') def add_conditions(self, conditions, condition_type): """ Add conditions to a rule :param conditions: list of conditions where condition is a pair (attribute, expression) :param condition_type: can be 'inclusive' or 'exclusive' """ name = 'automember{}regex'.format(condition_type) attribute, expression = conditions[0] another_conditions = conditions[1:] another_conditions.reverse() self.add_table_record(name, {'fields': [ ('selectbox', 'key', attribute), ('textbox', name, expression) ]}, add_another=bool(another_conditions)) while another_conditions: attribute, expression = another_conditions.pop() self.add_another_table_record( {'fields': [ ('selectbox', 'key', attribute), ('textbox', name, expression) ]}, add_another=bool(another_conditions) ) def delete_conditions(self, conditions, condition_type): """ Delete rule conditions :param conditions: list of conditions where condition is a pair (attribute, expression) :param condition_type: can be 'inclusive' or 'exclusive' """ self.delete_record( ['{}={}'.format(attr, exp) for attr, exp in conditions], parent=self.get_facet(), table_name='automember{}regex'.format(condition_type) ) def open_new_condition_dialog(self, condition_type): table = self.find_by_selector( "table[name='automember{}regex'].table".format(condition_type), strict=True ) btn = self.find_by_selector(".btn[name=add]", table, strict=True) btn.click() self.wait() def get_host_util(self): host_util = host_tasks() host_util.driver = self.driver host_util.config = self.config return host_util @screenshot def test_crud(self): """ Basic CRUD: automember """ # user group rule self.basic_crud(ENTITY, USER_GROUP_DATA, search_facet='searchgroup', default_facet='usergrouprule', details_facet='usergrouprule', ) # prepare host group self.basic_crud(hostgroup.ENTITY, hostgroup.DATA, default_facet=hostgroup.DEFAULT_FACET, delete=False) # host group rule self.navigate_by_menu('identity/automember/amhostgroup') self.basic_crud(ENTITY, HOST_GROUP_DATA, search_facet='searchhostgroup', default_facet='hostgrouprule', details_facet='hostgrouprule', navigate=False, breadcrumb='Host group rules', ) # cleanup self.delete(hostgroup.ENTITY, [hostgroup.DATA]) @screenshot def test_rebuild_membership_hosts(self): """ Test automember rebuild membership feature for hosts """ host_util = self.get_host_util() domain = self.config.get('ipa_domain') host1 = 'web1.%s' % domain host2 = 'web2.%s' % domain # Add a hostgroup self.add_host_group('webservers', 'webservers') # Add hosts self.add_record('host', host_util.get_data("web1", domain)) self.add_record('host', host_util.get_data("web2", domain)) # Add an automember rule self.add_host_group_rules('webservers') # Add a condition for automember rule self.navigate_to_record('webservers') self.add_conditions([('fqdn', '^web[1-9]+')], condition_type=INCLUSIVE) # Assert that hosts are not members of hostgroup self.navigate_to_record('webservers', entity='hostgroup') self.facet_button_click('refresh') self.wait_for_request() self.assert_record(host1, negative=True) self.assert_record(host2, negative=True) # Rebuild membership for first host, using action on host details facet self.navigate_to_record(host1, entity='host') self.action_list_action('automember_rebuild', confirm=False) dialog_info = self.get_dialog_info() assert dialog_info['text'] == rebuild_warning_msg self.dialog_button_click('ok') # Assert that host is now a member of hostgroup self.navigate_to_record('webservers', entity='hostgroup') self.facet_button_click('refresh') self.wait_for_request() self.assert_record(host1) self.assert_record(host2, negative=True) # Remove host from hostgroup self.delete_record(host1) # Assert that host was re-added to the group. # The behavior is expected with the plugin default setting: # the entry cn=Auto Membership Plugin,cn=plugins,cn=config has # a default value autoMemberProcessModifyOps: on # # See https://www.port389.org/docs/389ds/design/automember-postop-modify-design.html # noqa: E501 self.facet_button_click('refresh') self.wait_for_request() self.assert_record(host1) # Rebuild membership for all hosts, using action on hosts search facet self.navigate_by_menu('identity/host') self.action_list_action('automember_rebuild', confirm=False) dialog_info = self.get_dialog_info() assert dialog_info['text'] == rebuild_warning_msg self.dialog_button_click('ok') # Assert that hosts are now members of hostgroup self.navigate_to_record('webservers', entity='hostgroup') self.facet_button_click('refresh') self.wait_for_request() self.assert_record(host1) self.assert_record(host2) # Delete hostgroup, hosts and automember rule self.delete('host', [{'pkey': host1}, {'pkey': host2}]) self.delete_host_group_rules('webservers') self.delete_host_groups('webservers') @screenshot def test_rebuild_membership_users(self): """ Test automember rebuild membership feature for users """ # Add a group self.add_user_group('devel', 'devel') # Add users self.add_user('dev1', 'Dev', 'One') self.add_user('dev2', 'Dev', 'Two') # Add an automember rule self.add_user_group_rules('devel') # Add a condition for automember rule self.navigate_to_record('devel') self.add_conditions([('uid', '^dev[1-9]+')], condition_type=INCLUSIVE) # Assert that users are not members of group self.navigate_to_record('devel', entity='group') self.facet_button_click('refresh') self.wait_for_request() self.assert_record('dev1', negative=True) self.assert_record('dev2', negative=True) # Rebuild membership for first user, using action on user details facet self.navigate_to_record('dev1', entity='user') self.action_list_action('automember_rebuild', confirm=False) dialog_info = self.get_dialog_info() assert dialog_info['text'] == rebuild_warning_msg self.dialog_button_click('ok') # Assert that user is now a member of group self.navigate_to_record('devel', entity='group') self.facet_button_click('refresh') self.wait_for_request() self.assert_record('dev1') self.assert_record('dev2', negative=True) # Remove user from group self.delete_record('dev1') # Assert that user was re-added to the group # The behavior is expected with the plugin default setting: # the entry cn=Auto Membership Plugin,cn=plugins,cn=config has # a default value autoMemberProcessModifyOps: on # # See https://www.port389.org/docs/389ds/design/automember-postop-modify-design.html # noqa: E501 self.facet_button_click('refresh') self.wait_for_request() self.assert_record('dev1') # Rebuild membership for all users, using action on users search facet self.navigate_by_menu('identity/user_search') self.action_list_action('automember_rebuild', confirm=False) dialog_info = self.get_dialog_info() assert dialog_info['text'] == rebuild_warning_msg self.dialog_button_click('ok') # Assert that users are now members of group self.navigate_to_record('devel', entity='group') self.facet_button_click('refresh') self.wait_for_request() self.assert_record('dev1') self.assert_record('dev2') # Delete group, users and automember rule self.delete_users('dev1', 'dev2') self.delete_user_group_rules('devel') self.delete_user_groups('devel') @screenshot def test_add_multiple_user_group_rules(self): """ Test creating and deleting multiple user group rules """ groups = ['group1', 'group2', 'group3'] for group in groups: self.add_user_group(group) self.add_user_group_rules(*groups) self.delete_user_group_rules(*groups) @screenshot def test_add_multiple_host_group_rules(self): """ Test creating and deleting multiple host group rules """ groups = ['group1', 'group2', 'group3'] for group in groups: self.add_host_group(group) self.add_host_group_rules(*groups) self.delete_host_group_rules(*groups) @screenshot def test_search_user_group_rule(self): """ Test searching user group rules using filter """ pkey = SEARCH_CASES['name'] self.add_user_group(pkey, '') self.add_user_group_rules(pkey) self.navigate_to_record(pkey) self.mod_record(ENTITY, {'mod': [ ('textarea', 'description', SEARCH_CASES['description']), ]}, facet='usergrouprule') self.navigate_to_entity(ENTITY, facet='searchgroup') for text in SEARCH_CASES['positive']: self.apply_search_filter(text) self.wait_for_request() self.assert_record(pkey) for text in SEARCH_CASES['negative']: self.apply_search_filter(text) self.wait_for_request() self.assert_record(pkey, negative=True) self.delete_user_group_rules(pkey) self.delete_user_groups(pkey) @screenshot def test_search_host_group_rule(self): """ Test searching host group rules using filter """ pkey = SEARCH_CASES['name'] self.add_host_group(pkey, '') self.add_host_group_rules(pkey, navigate=True) self.navigate_to_record(pkey) self.mod_record(ENTITY, {'mod': [ ('textarea', 'description', SEARCH_CASES['description']), ]}, facet='hostgrouprule') self.navigate_to_entity(ENTITY, facet='searchhostgroup') for text in SEARCH_CASES['positive']: self.apply_search_filter(text) self.wait_for_request() self.assert_record(pkey) for text in SEARCH_CASES['negative']: self.apply_search_filter(text) self.wait_for_request() self.assert_record(pkey, negative=True) self.delete_host_group_rules(pkey) self.delete_host_groups(pkey) @screenshot def test_add_user_group_rule_conditions(self): """ Test creating and deleting user group rule conditions """ pkey = 'devel' one_inc_condition = ('employeetype', '*engineer*') inc_conditions = [ ('cn', 'inclusive-expression'), ('description', 'other-inclusive-expression'), ] one_exc_condition = ('employeetype', '*manager*') exc_conditions = [ ('cn', 'exclusive-expression'), ('description', 'other-exclusive-expression'), ] self.add_user_group(pkey) self.add_user_group_rules(pkey) self.navigate_to_record(pkey) self.add_conditions([one_inc_condition], condition_type=INCLUSIVE) self.add_conditions(inc_conditions, condition_type=INCLUSIVE) self.add_conditions([one_exc_condition], condition_type=EXCLUSIVE) self.add_conditions(exc_conditions, condition_type=EXCLUSIVE) self.delete_conditions([one_inc_condition], condition_type=INCLUSIVE) self.delete_conditions(inc_conditions, condition_type=INCLUSIVE) self.delete_conditions([one_exc_condition], condition_type=EXCLUSIVE) self.delete_conditions(inc_conditions, condition_type=EXCLUSIVE) self.delete_user_group_rules(pkey) self.delete_user_groups(pkey) @screenshot def test_add_host_group_rule_conditions(self): """ Test creating and deleting user group rule conditions """ pkey = 'devel' one_inc_condition = ('ipaclientversion', '4.8') inc_conditions = [ ('cn', 'inclusive-expression'), ('description', 'other-inclusive-expression'), ] one_exc_condition = ('ipaclientversion', '4.7') exc_conditions = [ ('cn', 'exclusive-expression'), ('description', 'other-exclusive-expression'), ] self.add_host_group(pkey) self.add_host_group_rules(pkey) self.navigate_to_record(pkey) self.add_conditions([one_inc_condition], condition_type=INCLUSIVE) self.add_conditions(inc_conditions, condition_type=INCLUSIVE) self.add_conditions([one_exc_condition], condition_type=EXCLUSIVE) self.add_conditions(exc_conditions, condition_type=EXCLUSIVE) self.delete_conditions([one_inc_condition], condition_type=INCLUSIVE) self.delete_conditions(inc_conditions, condition_type=INCLUSIVE) self.delete_conditions([one_exc_condition], condition_type=EXCLUSIVE) self.delete_conditions(inc_conditions, condition_type=EXCLUSIVE) self.delete_host_group_rules(pkey) self.delete_host_groups(pkey) @screenshot def test_cancel_new_user_group_rule_condition_dialog(self): """ Test canceling of creating new user group rule condition """ pkey = 'devel' self.add_user_group(pkey) self.add_user_group_rules(pkey) self.navigate_to_record(pkey) for condition_type in [INCLUSIVE, EXCLUSIVE]: self.open_new_condition_dialog(condition_type) self.fill_fields([('selectbox', 'key', 'title')]) self.dialog_button_click('cancel') self.delete_user_group_rules(pkey) self.delete_user_groups(pkey) @screenshot def test_cancel_new_host_group_rule_condition_dialog(self): """ Test canceling of creating new host group rule condition """ pkey = 'devel' self.add_host_group(pkey) self.add_host_group_rules(pkey) self.navigate_to_record(pkey) for condition_type in [INCLUSIVE, EXCLUSIVE]: self.open_new_condition_dialog(condition_type) self.fill_fields([('selectbox', 'key', 'serverhostname')]) self.dialog_button_click('cancel') self.delete_host_group_rules(pkey) self.delete_host_groups(pkey) @screenshot def test_set_default_user_group(self): """ Test setting default user group """ pkey = 'default-user-group' user_pkey = 'some-user' self.add_user_group(pkey) self.navigate_by_menu('identity/automember/amgroup') self.select_combobox('automemberdefaultgroup', pkey) self.dialog_button_click('ok') self.add_user(user_pkey, 'Some', 'User') self.navigate_to_record(user_pkey) self.switch_to_facet('memberof_group') self.assert_record(pkey) # Clear default user group self.navigate_by_menu('identity/automember/amgroup') self.select_combobox('automemberdefaultgroup', '') self.dialog_button_click('ok') self.delete_users(user_pkey) self.delete_user_groups(pkey) @screenshot def test_set_default_host_group(self): """ Test setting default host group """ pkey = 'default-host-group' host_util = self.get_host_util() domain = self.config.get('ipa_domain') self.add_host_group(pkey) self.navigate_by_menu('identity/automember/amhostgroup') self.select_combobox('automemberdefaultgroup', pkey) self.dialog_button_click('ok') host_data = host_util.get_data('some-host', domain) self.add_record('host', host_data) self.navigate_to_record(host_data['pkey']) self.switch_to_facet('memberof_hostgroup') self.assert_record(pkey) # Clear default host group self.navigate_by_menu('identity/automember/amhostgroup') self.select_combobox('automemberdefaultgroup', '') self.dialog_button_click('ok') self.delete('host', [{'pkey': host_data['pkey']}]) self.delete_host_groups(pkey) @screenshot def test_add_user_group_rule_with_no_group(self): self.add_record( ENTITY, {'pkey': 'empty-user-group', 'add': []}, facet='searchgroup', negative=True ) @screenshot def test_add_host_group_rule_with_no_group(self): self.add_record( ENTITY, {'pkey': 'empty-host-group', 'add': []}, facet='searchhostgroup', negative=True ) @screenshot def test_add_user_group_rules_for_same_group(self): """ Test creating user group rules for same group """ group_name = 'some-user-group' self.add_user_group(group_name) self.add_user_group_rules(group_name) self.add_user_group_rules(group_name, negative=True, pre_delete=False) self.assert_last_error_dialog( self.AUTOMEMBER_RULE_EXISTS_ERROR.format(group_name) ) self.delete_user_group_rules(group_name) self.delete_user_groups(group_name) @screenshot def test_add_host_group_rules_for_same_group(self): """ Test creating host group rules for same group """ group_name = 'some-host-group' self.add_host_group(group_name) self.add_host_group_rules(group_name) self.add_host_group_rules(group_name, negative=True, pre_delete=False) self.assert_last_error_dialog( self.AUTOMEMBER_RULE_EXISTS_ERROR.format(group_name) ) self.delete_host_group_rules(group_name) self.delete_host_groups(group_name) @screenshot def test_cancel_group_rule_creating(self): """ Test canceling of creating new automember group rule """ self.add_user_group_rules('some-user-group', dialog_btn='cancel') self.add_host_group_rules('some-host-group', dialog_btn='cancel')
23,911
Python
.py
589
31.190153
105
0.610126
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,392
data_sudo.py
freeipa_freeipa/ipatests/test_webui/data_sudo.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. RULE_ENTITY = 'sudorule' CMDENTITY = 'sudocmd' CMDGROUP_ENTITY = 'sudocmdgroup' CMDGROUP_DEF_FACET = 'member_sudocmd' RULE_PKEY = 'itestsudorule' RULE_DATA = { 'pkey': RULE_PKEY, 'add': [ ('textbox', 'cn', RULE_PKEY), ], 'mod': [ ('textarea', 'description', 'itestsudorule desc'), ], } CMD_PKEY = 'itestsudocmd' CMD_DATA = { 'pkey': CMD_PKEY, 'add': [ ('textbox', 'sudocmd', CMD_PKEY), ('textarea', 'description', 'itestsudocmd desc'), ], 'mod': [ ('textarea', 'description', 'itestsudocmd desc mod'), ], } CMD_PKEY2 = 'itestsudocmd2' CMD_DATA2 = { 'pkey': CMD_PKEY2, 'add': [ ('textbox', 'sudocmd', CMD_PKEY2), ('textarea', 'description', 'itestsudocmd2 desc'), ], 'mod': [ ('textarea', 'description', 'itestsudocmd2 desc mod'), ], } CMD_GROUP_PKEY = 'itestsudocmdgroup' CMDGROUP_DATA = { 'pkey': CMD_GROUP_PKEY, 'add': [ ('textbox', 'cn', CMD_GROUP_PKEY), ('textarea', 'description', 'itestsudocmdgroup desc'), ], 'mod': [ ('textarea', 'description', 'itestsudocmdgroup desc mod'), ], } CMD_GROUP_PKEY2 = 'itestsudocmdgroup2' CMDGROUP_DATA2 = { 'pkey': CMD_GROUP_PKEY2, 'add': [ ('textbox', 'cn', CMD_GROUP_PKEY2), ('textarea', 'description', 'itestsudocmdgroup2 desc'), ], 'mod': [ ('textarea', 'description', 'itestsudocmdgroup2 desc mod'), ], }
2,241
Python
.py
76
25.618421
71
0.646132
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,393
test_topology.py
freeipa_freeipa/ipatests/test_webui/test_topology.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # from ipatests.test_webui.ui_driver import screenshot, UI_driver class TestTopology(UI_driver): @screenshot def test_topology_graph(self): self.init_app() self.navigate_to_page('topology-graph') self.assert_visible('.topology-view')
339
Python
.py
10
29.3
66
0.726154
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,394
test_hbac.py
freeipa_freeipa/ipatests/test_webui/test_hbac.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ HBAC tests """ from ipatests.test_webui.ui_driver import UI_driver from ipatests.test_webui.ui_driver import screenshot import ipatests.test_webui.data_hbac as hbac import ipatests.test_webui.data_hostgroup as hostgroup import pytest @pytest.mark.tier1 class test_hbac(UI_driver): @screenshot def test_crud(self): """ Basic CRUD: hbac """ self.init_app() self.basic_crud(hbac.RULE_ENTITY, hbac.RULE_DATA) self.basic_crud(hbac.SVC_ENTITY, hbac.SVC_DATA) self.basic_crud(hbac.SVCGROUP_ENTITY, hbac.SVCGROUP_DATA, default_facet=hbac.SVCGROUP_DEF_FACET) @screenshot def test_mod(self): """ Mod: hbac """ self.init_app() host_key = self.config.get('ipa_server').strip() self.add_record(hostgroup.ENTITY, hostgroup.DATA) self.add_record(hbac.RULE_ENTITY, hbac.RULE_DATA) self.navigate_to_record(hbac.RULE_PKEY) tables = [ ['memberuser_user', ['admin'], ], ['memberuser_group', ['editors'], ], ['memberhost_host', [host_key], ], ['memberhost_hostgroup', [hostgroup.PKEY], ], ['memberservice_hbacsvc', ['ftp'], ], ['memberservice_hbacsvcgroup', ['Sudo'], ], ] categories = [ 'usercategory', 'hostcategory', 'servicecategory', ] self.mod_rule_tables(tables, categories, []) # cleanup # ------- self.delete(hbac.RULE_ENTITY, [hbac.RULE_DATA]) self.delete(hostgroup.ENTITY, [hostgroup.DATA]) @screenshot def test_actions(self): """ Test hbac rule actions """ self.init_app() self.add_record(hbac.RULE_ENTITY, hbac.RULE_DATA) self.navigate_to_record(hbac.RULE_PKEY) self.disable_action() self.enable_action() self.delete_action(hbac.RULE_ENTITY, hbac.RULE_PKEY) @screenshot def test_hbac_test(self): """ Test HBAC test UI Test: * basic functionality * navigation by next/prev buttons * navigation by facet tabs * resetting test """ self.init_app() host_key = self.config.get('ipa_server').strip() self.navigate_to_entity('hbactest', 'user') self.assert_facet('hbactest', 'user') self.select_record('admin') self.button_click('next') self.wait_for_request(n=2) self.assert_facet('hbactest', 'targethost') self.select_record(host_key) self.button_click('prev') self.assert_facet('hbactest', 'user') self.switch_to_facet('targethost') self.button_click('next') self.wait_for_request(n=2) self.assert_facet('hbactest', 'service') self.select_record('ftp') self.button_click('prev') self.assert_facet('hbactest', 'targethost') self.switch_to_facet('service') self.button_click('next') self.wait_for_request(n=2) self.assert_facet('hbactest', 'rules') self.select_record('allow_all') self.button_click('prev') self.assert_facet('hbactest', 'service') self.switch_to_facet('rules') self.button_click('next') self.wait_for_request(n=2) self.assert_facet('hbactest', 'run_test') self.button_click('run_test') self.assert_text("div.hbac-test-result-panel p", 'Access Granted'.upper()) self.button_click('prev') self.assert_facet('hbactest', 'rules') self.switch_to_facet('run_test') self.wait_for_request(n=2) self.button_click('new_test') self.assert_facet('hbactest', 'user') # test pre-run validation and navigation to related facet def __hbac_ui_click_on_run_test(self): self.wait_for_request(n=2) self.switch_to_facet('run_test') self.wait_for_request(n=2) self.button_click('run_test') self.assert_dialog('message_dialog') __hbac_ui_click_on_run_test(self) self.click_on_link('Target host') self.assert_facet('hbactest', 'targethost') __hbac_ui_click_on_run_test(self) self.click_on_link('Service') self.assert_facet('hbactest', 'service')
5,139
Python
.py
137
29.664234
82
0.623392
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,395
test_netgroup.py
freeipa_freeipa/ipatests/test_webui/test_netgroup.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Netgroup tests """ from ipatests.test_webui.ui_driver import UI_driver from ipatests.test_webui.ui_driver import screenshot import ipatests.test_webui.data_netgroup as netgroup import ipatests.test_webui.data_user as user import ipatests.test_webui.data_group as group import ipatests.test_webui.data_hostgroup as hostgroup from ipatests.test_webui.test_host import host_tasks, ENTITY as HOST_ENTITY import pytest try: from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains except ImportError: pass @pytest.mark.tier1 class test_netgroup(UI_driver): @screenshot def test_crud(self): """ Basic CRUD: netgroup """ self.init_app() self.basic_crud(netgroup.ENTITY, netgroup.DATA) @screenshot def test_basic_workflows(self): """ add and delete netgroup with various scenarios. """ self.init_app() # add mixed case netgroup name self.add_record(netgroup.ENTITY, netgroup.DATA_MIXED_CASE) pkey = netgroup.DATA_MIXED_CASE['pkey'].lower() self.delete_record(pkey) # add long netgroup name self.add_record(netgroup.ENTITY, netgroup.DATA_LONG_NAME, delete=True) # add single character netgroup name ticket#2671 self.add_record(netgroup.ENTITY, netgroup.DATA_SINGLE_CHAR, delete=True) # add netgroup using enter self.add_record(netgroup.ENTITY, netgroup.DATA, dialog_btn=None) actions = ActionChains(self.driver) actions.send_keys(Keys.TAB) actions.send_keys(Keys.ENTER).perform() self.wait_for_request(d=0.5) self.assert_record(netgroup.PKEY) self.close_notifications() # delete netgroup using enter self.select_record(netgroup.PKEY) self.facet_button_click('remove') self.wait_for_request() actions = ActionChains(self.driver) actions.send_keys(Keys.ENTER).perform() self.wait_for_request(d=0.5) self.assert_record(netgroup.PKEY, negative=True) self.close_all_dialogs() # delete and cancel self.add_record(netgroup.ENTITY, netgroup.DATA) self.select_record(netgroup.PKEY) self.facet_button_click('remove') self.dialog_button_click('cancel') self.assert_record(netgroup.PKEY) self.select_record(netgroup.PKEY, unselect=True) self.delete_record(netgroup.PKEY) # add multiple records using add_and_another button self.add_record(netgroup.ENTITY, [netgroup.DATA, netgroup.DATA2, netgroup.DATA3, netgroup.DATA4]) # search record pkey = netgroup.DATA2['pkey'] self.search_pkey(pkey) self.assert_record(pkey) # Negative search pkey = netgroup.DATA_MIXED_CASE['pkey'] self.search_pkey(pkey) self.assert_record(pkey, negative=True) # delete multiple records records = [netgroup.DATA, netgroup.DATA2, netgroup.DATA3] self.navigate_to_entity(netgroup.ENTITY) self.select_multiple_records(records) self.facet_button_click('remove') self.dialog_button_click('ok') # Find and delete pkey = netgroup.DATA4['pkey'] self.search_pkey(pkey) self.select_record(pkey) self.facet_button_click('remove') self.dialog_button_click('ok') def search_pkey(self, pkey): search_field_s = '.search-filter input[name=filter]' self.fill_text(search_field_s, pkey) self.action_button_click('find', parent=None) self.wait_for_request(n=2) @screenshot def test_add_netgroup_negative(self): """ Negative test for adding netgroup """ self.init_app() # add then cancel self.add_record(netgroup.ENTITY, netgroup.DATA, dialog_btn='cancel') # add duplicate self.add_record(netgroup.ENTITY, netgroup.DATA) expected_error = 'group with name "%s" already exists' % netgroup.PKEY self.navigate_to_entity(netgroup.ENTITY) self.facet_button_click('add') self.fill_input('cn', netgroup.PKEY) self.cancel_retry_dialog(expected_error) self.delete_record(netgroup.PKEY) # empty netgroup self.navigate_to_entity(netgroup.ENTITY) self.facet_button_click('add') self.dialog_button_click('add') elem = self.find(".widget[name='cn']") self.assert_field_validation_required(elem) self.dialog_button_click('cancel') # invalid_group_name expected_error = 'may only include letters, numbers, _, -, and .' pkey = ';test-gr@up' self.navigate_to_entity(netgroup.ENTITY) self.facet_button_click('add') self.fill_input('cn', pkey) elem = self.find(".widget[name='cn']") self.assert_field_validation(expected_error, parent=elem) self.dialog_button_click('cancel') def cancel_retry_dialog(self, expected_error): self.dialog_button_click('add') dialog = self.get_last_error_dialog() assert (expected_error in dialog.text) self.wait_for_request() # Key press for Retry actions = ActionChains(self.driver) actions.send_keys(Keys.ENTER).perform() self.wait_for_request(n=2) self.dialog_button_click('cancel') self.wait_for_request(n=2) self.dialog_button_click('cancel') @screenshot def test_unsaved_changes(self): """ verifying unsaved changes dialog ticket#2075 """ self.init_app() self.add_record(netgroup.ENTITY, netgroup.DATA8, dialog_btn='add_and_edit') mod_description = (netgroup.DATA8['mod'][0][2]) # verifying Cancel button self.fill_fields(netgroup.DATA8['mod']) self.click_on_link('Netgroups') self.assert_dialog() self.dialog_button_click('cancel') self.assert_facet_button_enabled('save') # verifying Revert button self.click_on_link('Netgroups') self.assert_dialog() self.dialog_button_click('revert') self.navigate_to_record(netgroup.PKEY8) self.verify_btn_action(mod_description) # verifying Save button self.fill_fields(netgroup.DATA8['mod']) self.click_on_link('Netgroups') self.assert_dialog() self.dialog_button_click('save') self.navigate_to_record(netgroup.PKEY8) self.verify_btn_action(mod_description, negative=True) @screenshot def test_add_and_edit_group(self): """ 1. add and switch to edit mode 2. verifying Save, Revert, Refresh and Undo button """ self.init_app() # add and edit record self.add_record(netgroup.ENTITY, netgroup.DATA8, dialog_btn='add_and_edit') mod_description = (netgroup.DATA8['mod'][0][2]) # verifying undo button self.fill_fields(netgroup.DATA8['mod']) self.undo_click() self.verify_btn_action(mod_description) self.wait_for_request(n=2) # verifying revert button self.mod_record(netgroup.ENTITY, netgroup.DATA8, facet_btn='revert') self.wait_for_request() self.verify_btn_action(mod_description) self.wait_for_request(n=2) # verifying refresh button self.fill_fields(netgroup.DATA8['mod'], undo=True) self.facet_button_click('refresh') self.verify_btn_action(mod_description) self.wait_for_request(n=2) # verifying Save button self.mod_record(netgroup.ENTITY, netgroup.DATA8) self.wait_for_request() self.verify_btn_action(mod_description, negative=True) self.wait_for_request(n=2) # clean up self.navigate_to_entity(netgroup.ENTITY) self.delete_record(netgroup.PKEY8) def undo_click(self): facet = self.get_facet() s = ".textarea-widget button[name='undo']" self._button_click(s, facet) def verify_btn_action(self, mod_description, negative=False): """ camparing current description with modified description """ current_description = self.get_field_value("description", element="textarea") if negative: assert current_description == mod_description else: assert current_description != mod_description @screenshot def test_add_members(self): """ Adding members and membersof """ self.init_app() records = [netgroup.DATA, netgroup.DATA2, netgroup.DATA3, netgroup.DATA4, netgroup.DATA8] self.add_record(netgroup.ENTITY, records) # adding netgroup "members" self.navigate_to_record(netgroup.PKEY2) self.add_associations([netgroup.PKEY3, netgroup.PKEY4], 'member_netgroup', delete=True, search=True) # adding netgroup "memberof" self.add_associations([netgroup.PKEY, netgroup.PKEY8], 'memberof_netgroup', delete=True) self.delete(netgroup.ENTITY, records) @screenshot def test_mod(self): """ Mod: netgroup """ self.init_app() host = host_tasks() host.driver = self.driver host.config = self.config host.prep_data() host.prep_data2() self.add_record(netgroup.ENTITY, netgroup.DATA2) self.add_record(user.ENTITY, user.DATA) self.add_record(user.ENTITY, user.DATA2, navigate=False) self.add_record(group.ENTITY, group.DATA) self.add_record(group.ENTITY, group.DATA2, navigate=False) self.add_record(HOST_ENTITY, host.data) self.add_record(HOST_ENTITY, host.data2, navigate=False) self.add_record(hostgroup.ENTITY, hostgroup.DATA) self.add_record(hostgroup.ENTITY, hostgroup.DATA2, navigate=False) self.add_record(netgroup.ENTITY, netgroup.DATA) self.navigate_to_record(netgroup.PKEY, entity=netgroup.ENTITY) tables = [ ['memberuser_user', [user.PKEY, user.PKEY2], ], ['memberuser_group', [group.PKEY, group.PKEY2], ], ['memberhost_host', [host.pkey, host.pkey2], ], ['memberhost_hostgroup', [hostgroup.PKEY, hostgroup.PKEY2], ], ] categories = [ 'usercategory', 'hostcategory', ] self.mod_rule_tables(tables, categories, []) # add associations then cancel def get_t_vals(t): table = t[0] k = t[1] e = [] if len(t) > 2: e = t[2] return table, k, e for t in tables: table, keys, _exts = get_t_vals(t) self.add_table_associations(table, [keys[0]], confirm_btn='cancel') # verifying members listed as links ticket#2670 self.add_table_associations(table, [keys[0]]) self.wait_for_request(n=2) self.navigate_to_record(keys[0], table_name=table) page_pkey = self.get_text('.facet-pkey') assert keys[0] in page_pkey self.navigate_to_record(netgroup.PKEY, entity=netgroup.ENTITY) for cat in categories: # verifying undo on memberships self.check_option(cat, 'all') self.assert_facet_button_enabled('save', enabled=True) undo = "div[name = %s] > button[name='undo']" % cat self._button_click(undo, parent=None) self.assert_facet_button_enabled('save', enabled=False) # verifying Revert on memberships self.check_option(cat, 'all') self.facet_button_click('revert') self.assert_facet_button_enabled('save', enabled=False) # verifying refresh on memberships self.check_option(cat, 'all') self.facet_button_click('refresh') self.assert_facet_button_enabled('save', enabled=False) # cleanup # ------- self.delete(netgroup.ENTITY, [netgroup.DATA, netgroup.DATA2]) self.delete(user.ENTITY, [user.DATA, user.DATA2]) self.delete(group.ENTITY, [group.DATA, group.DATA2]) self.delete(HOST_ENTITY, [host.data, host.data2]) self.delete(hostgroup.ENTITY, [hostgroup.DATA, hostgroup.DATA2])
13,371
Python
.py
321
32.542056
79
0.634251
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,396
test_rbac.py
freeipa_freeipa/ipatests/test_webui/test_rbac.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ RBAC tests """ from ipatests.test_webui.ui_driver import UI_driver from ipatests.test_webui.ui_driver import screenshot import pytest ROLE_ENTITY = 'role' ROLE_DEF_FACET = 'member_user' ROLE_PKEY = 'AAtest_role' ROLE_DATA = { 'pkey': ROLE_PKEY, 'add': [ ('textbox', 'cn', ROLE_PKEY), ('textarea', 'description', 'role desc'), ], 'mod': [ ('textarea', 'description', 'role desc mod'), ], } PRIVILEGE_ENTITY = 'privilege' PRIVILEGE_DEF_FACET = 'memberof_permission' PRIVILEGE_PKEY = 'AAtest_privilege' PRIVILEGE_DATA = { 'pkey': PRIVILEGE_PKEY, 'add': [ ('textbox', 'cn', PRIVILEGE_PKEY), ('textarea', 'description', 'privilege desc'), ], 'mod': [ ('textarea', 'description', 'privilege desc mod'), ], } PERMISSION_ENTITY = 'permission' PERMISSION_PKEY = 'AAtest_perm' PERMISSION_DATA = { 'pkey': PERMISSION_PKEY, 'add': [ ('textbox', 'cn', PERMISSION_PKEY), ('checkbox', 'ipapermright', 'write'), ('checkbox', 'ipapermright', 'read'), ('selectbox', 'type', 'user'), ('checkbox', 'attrs', 'audio'), ('checkbox', 'attrs', 'cn'), ], 'mod': [ ('checkbox', 'attrs', 'carlicense'), ], } @pytest.mark.tier1 class test_rbac(UI_driver): @screenshot def test_crud(self): """ Basic CRUD: RBAC """ self.init_app() self.basic_crud(ROLE_ENTITY, ROLE_DATA, default_facet=ROLE_DEF_FACET ) self.basic_crud(PRIVILEGE_ENTITY, PRIVILEGE_DATA, default_facet=PRIVILEGE_DEF_FACET ) self.basic_crud(PERMISSION_ENTITY, PERMISSION_DATA)
2,521
Python
.py
81
26
71
0.635802
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,397
test_pwpolicy.py
freeipa_freeipa/ipatests/test_webui/test_pwpolicy.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Password policy tests """ from ipatests.test_webui.ui_driver import UI_driver from ipatests.test_webui.ui_driver import screenshot import ipatests.test_webui.data_group as group import ipatests.test_webui.data_pwpolicy as pwpolicy import pytest try: from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains except ImportError: pass FIELDS = ['krbmaxpwdlife', 'krbminpwdlife', 'krbpwdhistorylength', 'krbpwdmindiffchars', 'krbpwdminlength', 'krbpwdmaxfailure', 'krbpwdfailurecountinterval', 'krbpwdlockoutduration', 'cospriority', 'passwordgracelimit'] EXPECTED_ERR = "invalid 'group': cannot delete global password policy" EXPECTED_MSG = 'Password Policy successfully added' @pytest.mark.tier1 class test_pwpolicy(UI_driver): @screenshot def test_crud(self): """ Basic CRUD: pwpolicy """ self.init_app() self.basic_crud(pwpolicy.ENTITY, pwpolicy.DATA) @screenshot def test_misc(self): """ various test cases covered in one place """ # Basic requirement : create user group for test self.init_app() self.navigate_to_entity(group.ENTITY) self.add_record(group.ENTITY, [group.DATA, group.DATA2, group.DATA3, group.DATA_SPECIAL_CHAR_GROUP]) # add then cancel self.add_record(pwpolicy.ENTITY, pwpolicy.DATA1, dialog_btn='cancel') # test add and add another record self.add_record(pwpolicy.ENTITY, [pwpolicy.DATA1, pwpolicy.DATA2]) # test add and edit record self.add_record(pwpolicy.ENTITY, pwpolicy.DATA, dialog_btn='add_and_edit') # test delete multiple records self.navigate_to_entity(pwpolicy.ENTITY) records = [pwpolicy.DATA, pwpolicy.DATA1, pwpolicy.DATA2] self.select_multiple_records(records) self.facet_button_click('remove') self.dialog_button_click('ok') # test add password policy for special characters group self.add_record(pwpolicy.ENTITY, pwpolicy.DATA_SPECIAL_CHAR, delete=True) # empty group and priority (requires the field) self.facet_button_click('add') self.dialog_button_click('add') self.assert_field_validation_required(field='cn') self.assert_field_validation_required(field='cospriority') self.close_all_dialogs() # test delete default policy and # confirming by keyboard to test ticket #4097 self.select_record(pwpolicy.DEFAULT_POLICY) self.facet_button_click('remove') self.dialog_button_click('ok') self.assert_last_error_dialog(EXPECTED_ERR, details=True) actions = ActionChains(self.driver) actions.send_keys(Keys.TAB) actions.send_keys(Keys.ENTER).perform() self.wait(0.5) self.assert_record(pwpolicy.DEFAULT_POLICY) # test add/delete Passwordpolicy confirming using # ENTER key ticket #3200 self.add_record(pwpolicy.ENTITY, pwpolicy.DATA3, dialog_btn=None) actions = ActionChains(self.driver) actions.send_keys(Keys.ENTER).perform() self.wait_for_request(d=0.5) self.assert_notification(assert_text=EXPECTED_MSG) self.assert_record(pwpolicy.PKEY3) self.close_notifications() self.delete_record(pwpolicy.PKEY3, confirm_btn=None) actions = ActionChains(self.driver) actions.send_keys(Keys.ENTER).perform() self.wait_for_request(d=0.5) self.assert_notification(assert_text='1 item(s) deleted') self.assert_record(pwpolicy.PKEY3, negative=True) self.close_notifications() # cleanup self.delete(group.ENTITY, [group.DATA, group.DATA2, group.DATA3, group.DATA_SPECIAL_CHAR_GROUP]) @screenshot def test_negative_value(self): """ Negative test for Password policy fields in edit page """ self.init_app() self.add_record(group.ENTITY, [group.DATA, group.DATA4]) self.navigate_to_entity(pwpolicy.ENTITY) non_interger_expected_error = 'Must be an integer' minimum_value_expected_error = 'Minimum value is 0' non_integer = 'nonInteger' maximum_value = '2147483649' minimum_value = '-1' self.add_record(pwpolicy.ENTITY, pwpolicy.DATA1, dialog_btn='add_and_edit') for field in FIELDS: # bigger than max value # verifying if field value is more than 20000 if field == 'krbmaxpwdlife': self.check_expected_error(field, 'Maximum value is 20000', maximum_value) # verifying if field value is more than 5 elif field == 'krbpwdmindiffchars': self.check_expected_error(field, 'Maximum value is 5', maximum_value) # verifying if field value is more than 2147483647 else: self.check_expected_error(field, 'Maximum value is 2147483647', maximum_value) # string used instead of integer self.check_expected_error(field, non_interger_expected_error, non_integer) # smaller than min value if field != 'passwordgracelimit': self.check_expected_error(field, minimum_value_expected_error, minimum_value) else: self.check_expected_error(field, 'Minimum value is -1', '-2') self.navigate_to_entity(pwpolicy.ENTITY) self.delete_record(pwpolicy.group.PKEY) # Negative test for policy priority field_priority = 'cospriority' self.add_record(pwpolicy.ENTITY, pwpolicy.DATA7, dialog_btn=None) # non integer for policy priority self.fill_input(field_priority, non_integer) self.assert_field_validation(non_interger_expected_error, field=field_priority) # lower bound of data range self.fill_input(field_priority, minimum_value) self.assert_field_validation(minimum_value_expected_error, field=field_priority) # upper bound of data range self.fill_input(field_priority, maximum_value) self.assert_field_validation(expect_error='Maximum value is' ' 2147483647', field=field_priority) self.close_all_dialogs() # cleanup self.delete(group.ENTITY, [group.DATA, group.DATA4]) def check_expected_error(self, pwdfield, expected_error, value): """ Validating password policy fields and asserting expected error """ self.fill_textbox(pwdfield, value) self.wait_for_request() self.assert_field_validation(expected_error, field=pwdfield) self.facet_button_click('revert') @screenshot def test_undo_refresh_revert(self): """ Test to verify undo/refresh/revert """ self.init_app() self.add_record(group.ENTITY, [group.DATA6]) self.add_record(pwpolicy.ENTITY, pwpolicy.DATA_RESET) self.navigate_to_record(pwpolicy.PKEY6) # test undo self.fill_fields(pwpolicy.DATA_RESET['mod']) mod_field = 0 for field in FIELDS: modified_value = (pwpolicy.DATA_RESET['mod'][mod_field][2]) self.click_undo_button(field) self.field_equals(field, modified_value) mod_field += 1 # test refresh mod_field = 0 for field in FIELDS: self.fill_fields(pwpolicy.DATA_RESET['mod']) modified_value = (pwpolicy.DATA_RESET['mod'][mod_field][2]) self.facet_button_click('refresh') self.field_equals(field, modified_value) mod_field += 1 # test revert mod_field = 0 for field in FIELDS: self.fill_fields(pwpolicy.DATA_RESET['mod']) modified_value = (pwpolicy.DATA_RESET['mod'][mod_field][2]) self.facet_button_click('revert') self.field_equals(field, modified_value) mod_field += 1 # cleanup self.navigate_to_entity(pwpolicy.ENTITY) self.delete_record(pwpolicy.group.PKEY6) self.delete(group.ENTITY, [group.DATA6]) def field_equals(self, field, mod_value, negative=True): """ comparing current value with modified value """ current_value = self.get_field_value(field, element="input") if negative: assert current_value != mod_value else: assert current_value == mod_value @screenshot def test_verify_measurement_unit(self): """ verifying measurement unit for password policy ticket #2437 """ self.init_app() self.navigate_to_entity(pwpolicy.ENTITY) self.navigate_to_record('global_policy') krbmaxpwdlife = self.get_text('label[name="krbmaxpwdlife"]') krbminpwdlife = self.get_text('label[name="krbminpwdlife"]') krbpwdhistorylen = self.get_text('label[name="krbpwdhistorylength"]') krbpwdfailurecountinterval = \ self.get_text('label[name="krbpwdfailurecountinterval"]') krbpwdlockoutduration = \ self.get_text('label[name="krbpwdlockoutduration"]') assert "Max lifetime (days)" in krbmaxpwdlife assert "Min lifetime (hours)" in krbminpwdlife assert "History size (number of passwords)" in krbpwdhistorylen assert "Failure reset interval (seconds)" in krbpwdfailurecountinterval assert "Lockout duration (seconds)" in krbpwdlockoutduration @screenshot def test_grace_login_limit(self): """ Verify existence of grace login limit field and its constraints Related: https://pagure.io/freeipa/issue/9211 """ self.init_app() self.add_record(group.ENTITY, [group.DATA]) # add record DATA8 already with passwordgracelimit self.add_record(pwpolicy.ENTITY, [pwpolicy.DATA8]) field = 'passwordgracelimit' self.navigate_to_record(group.PKEY) # fill with values from DATA8, passwordgracelimit has value 42 self.fill_fields(pwpolicy.DATA8['mod']) current_value = self.get_field_value(field, element="input") try: assert current_value == '42' finally: # cleanup self.delete(group.ENTITY, [group.DATA]) self.delete(pwpolicy.ENTITY, [pwpolicy.DATA8])
11,731
Python
.py
263
34.403042
79
0.633604
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,398
test_misc_cases.py
freeipa_freeipa/ipatests/test_webui/test_misc_cases.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # """ Place for various miscellaneous test cases that do not fit to other suites """ from ipatests.test_webui.ui_driver import UI_driver from ipatests.test_webui.ui_driver import screenshot import pytest import re try: from selenium.webdriver.common.by import By except ImportError: pass @pytest.mark.tier1 class TestMiscCases(UI_driver): @screenshot def test_version_present(self): self.init_app() self.profile_menu_action('about') about_text = self.get_text('div[data-name="version_dialog"] p') ver_re = re.compile('version: .*') assert re.search(ver_re, about_text), 'Version not found' self.dialog_button_click('ok') @screenshot def test_customization_pagination_input_required(self): """Test if 'pagination size' is required when submitting the form.""" self.init_app() self.profile_menu_action('configuration') self.fill_input('pagination_size', '') self.dialog_button_click('save') pagination_size_elem = self.find( ".widget[name='pagination_size']", By.CSS_SELECTOR) self.assert_field_validation_required(parent=pagination_size_elem)
1,264
Python
.py
34
31.676471
77
0.701726
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,399
test_cert.py
freeipa_freeipa/ipatests/test_webui/test_cert.py
# Authors: # Petr Vobornik <pvoborni@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Cert tests """ from ipatests.test_webui.crypto_utils import generate_csr from ipatests.test_webui.ui_driver import UI_driver from ipatests.test_webui.ui_driver import screenshot from datetime import date, timedelta import pytest ENTITY = 'cert' ERR_SPACE = "invalid '{}': Leading and trailing spaces are not allowed" ERR_MUST_INTEGER = "invalid '{}': must be an integer" LEAST_SERIAL = "invalid '{}': must be at least 0" INV_DATE = ("invalid '{}': does not match any of accepted formats: " "%Y%m%d%H%M%SZ, %Y-%m-%dT%H:%M:%SZ, %Y-%m-%dT%H:%MZ, " "%Y-%m-%dZ, %Y-%m-%d %H:%M:%SZ, %Y-%m-%d %H:%MZ") def search_pkey(self, pkey): search_field_s = '.search-filter input[name=filter]' self.fill_text(search_field_s, pkey) self.action_button_click('find', parent=None) self.wait_for_request(n=2) def check_option_negative(self, date, option): self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', option) search_pkey(self, date) self.assert_last_error_dialog(INV_DATE.format(option)) self.close_all_dialogs() def check_space_error(self, string, option): self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', option) search_pkey(self, string) self.assert_last_error_dialog(ERR_SPACE.format(option)) self.close_all_dialogs() def check_integer(self, string, option): """ Method to check if provided value is integer. If not check for error dialog """ self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', option) search_pkey(self, string) self.assert_last_error_dialog(ERR_MUST_INTEGER.format(option)) self.close_all_dialogs() def check_minimum_serial(self, serial, option): self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', option) search_pkey(self, serial) self.assert_last_error_dialog(LEAST_SERIAL.format(option)) self.close_all_dialogs() @pytest.mark.tier1 class test_cert(UI_driver): @pytest.fixture(autouse=True) def cert_setup(self, ui_driver_fsetup): if not self.has_ca(): self.skip('CA not configured') def _add_and_revoke_cert(self, reason='1'): hostname = self.config.get('ipa_server') csr = generate_csr(hostname) self.navigate_to_entity(ENTITY) self.facet_button_click('request_cert') self.fill_textbox('principal', 'HTTP/{}'.format(hostname)) self.check_option('add', 'checked') self.fill_textarea('csr', csr) self.dialog_button_click('issue') self.assert_notification(assert_text='Certificate requested') self.navigate_to_entity(ENTITY) rows = self.get_rows() cert = rows[-1] self.navigate_to_row_record(cert) self.action_list_action('revoke_cert', False) self.select('select[name=revocation_reason]', reason) self.dialog_button_click('ok') self.close_notifications() self.navigate_to_entity(ENTITY) return cert @screenshot def test_read(self): """ Basic read: cert Certs don't have standard mod, add and delete methods. """ self.init_app() self.navigate_to_entity(ENTITY) rows = self.get_rows() self.navigate_to_row_record(rows[0]) self.navigate_by_breadcrumb("Certificates") @screenshot def test_search_subject(self): """ Try to search certificate by subject """ self.init_app() self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'subject') search_pkey(self, 'Certificate Authority') rows = self.get_rows() assert len(rows) != 0 # try to search non-existent subject self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'subject') search_pkey(self, 'nonexistent') rows = self.get_rows() assert len(rows) == 0 # try to search subject with speacial char self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'subject') search_pkey(self, '<,>.?/') rows = self.get_rows() assert len(rows) == 0 # try to search subject with leading space check_space_error(self, ' Certificate Authority', 'subject') # try to search subject with trailing space check_space_error(self, 'Certificate Authority ', 'subject') @screenshot def test_search_revocation_reason(self): """ Try to search certificates by revocation reason """ self.init_app() # revoke new certificate self._add_and_revoke_cert() # search cert by revocation reason self.select('select[name=search_option]', 'revocation_reason') search_pkey(self, '1') rows = self.get_rows() assert len(rows) != 0 # search cert by string. check_integer(self, 'nonexistent', 'revocation_reason') # search cert by special char check_integer(self, '<,>.?/', 'revocation_reason') # search revocation reason negative Number. self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'revocation_reason') search_pkey(self, '-1') rows = self.get_rows() assert len(rows) == 0 # valid revocation reason can be value from 0 to 10 # try revocation reason as other than valid value self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'revocation_reason') search_pkey(self, '11') rows = self.get_rows() assert len(rows) == 0 @screenshot def test_search_minimum_serial(self): """ Try to search cert using minimum serial number option """ self.init_app() self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'min_serial_number') search_pkey(self, '1') rows = self.get_rows() assert len(rows) != 0 # try search using string check_integer(self, 'nonexistent', 'min_serial_number') # try searching using -1 check_minimum_serial(self, '-1', 'min_serial_number') # try using higher value than no. of certs present self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'min_serial_number') search_pkey(self, '99') rows = self.get_rows() assert len(rows) == 0 @screenshot def test_search_maximum_serial(self): """ Try to search cert using maximum serial number option """ self.init_app() self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'max_serial_number') search_pkey(self, '2') rows = self.get_rows() assert len(rows) == 2 # try to search using string check_integer(self, 'nonexisting', 'max_serial_number') # try to search using -1 check_minimum_serial(self, '-1', 'max_serial_number') @screenshot def test_search_valid_not_after_from(self): """ Try to search cert using valid not after from option """ today = date.today() self.init_app() # revoke new certificate self._add_and_revoke_cert() self.select('select[name=search_option]', 'validnotafter_from') search_pkey(self, str(today)) rows = self.get_rows() assert len(rows) != 0 # try to search with string check_option_negative(self, 'nonexistent', 'validnotafter_from') # try to search using invalid date check_option_negative(self, '2018-02-30', 'validnotafter_from') # try to search using date beyond self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'validnotafter_from') search_pkey(self, str(today + timedelta(weeks=52 * 30))) rows = self.get_rows() assert len(rows) == 0 # try to search using leading space check_option_negative(self, ' {}'.format(str(today)), 'validnotafter_from') # try to search trailing space check_option_negative(self, '{} '.format(str(today)), 'validnotafter_from') @screenshot def test_search_valid_not_after_to(self): """ Try to search cert using valid not after to option """ today = date.today() self.init_app() # revoke new certificate self._add_and_revoke_cert() self.select('select[name=search_option]', 'validnotafter_to') search_pkey(self, str(today + timedelta(weeks=52 * 30))) rows = self.get_rows() assert len(rows) != 0 # try to search with string check_option_negative(self, 'nonexistent', 'validnotafter_to') # try to search using invalid date check_option_negative(self, '2018-02-30', 'validnotafter_to') # try to search using date ago self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'validnotafter_to') search_pkey(self, str(today - timedelta(weeks=52 * 10))) rows = self.get_rows() assert len(rows) == 0 # try to search with leading space check_option_negative(self, ' {}'.format(str(today)), 'validnotafter_to') # try to search with trailing space check_option_negative(self, '{} '.format(str(today)), 'validnotafter_to') @screenshot def test_search_valid_not_before_from(self): """ Try to search cert using valid not before from option """ today = date.today() self.init_app() # revoke new certificate self._add_and_revoke_cert() self.select('select[name=search_option]', 'validnotbefore_from') search_pkey(self, str(today)) rows = self.get_rows() assert len(rows) != 0 # try to search with string check_option_negative(self, 'nonexistent', 'validnotafter_from') # try to search using invalid date check_option_negative(self, '2018-02-30', 'validnotafter_from') # try to search using current beyond self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'validnotbefore_from') search_pkey(self, str(today + timedelta(weeks=52 * 30))) rows = self.get_rows() assert len(rows) == 0 # try to search with leading space check_option_negative(self, ' {}'.format(str(today)), 'validnotafter_from') # try to search with trailing space check_option_negative(self, '{} '.format(str(today)), 'validnotafter_from') @screenshot def test_search_valid_not_before_to(self): """ Try to search cert using valid not before to option """ today = date.today() self.init_app() # revoke new certificate self._add_and_revoke_cert() self.select('select[name=search_option]', 'validnotbefore_to') search_pkey(self, str(today + timedelta(weeks=52 * 30))) rows = self.get_rows() assert len(rows) != 0 # try to search with string check_option_negative(self, 'nonexistent', 'validnotafter_from') # try to search using invalid date check_option_negative(self, '2018-02-30', 'validnotafter_from') # try to search using date ago self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'validnotbefore_to') search_pkey(self, str(today - timedelta(weeks=52 * 10))) rows = self.get_rows() assert len(rows) == 0 # try to search with leading space check_option_negative(self, ' {}'.format(str(today)), 'validnotafter_from') # try to search with trailing space check_option_negative(self, '{} '.format(str(today)), 'validnotafter_from') @screenshot def test_search_issued_on_from(self): """ Try to search cert using issued on from option """ today = date.today() self.init_app() # revoke new certificate self._add_and_revoke_cert() self.select('select[name=search_option]', 'issuedon_from') search_pkey(self, str(today)) rows = self.get_rows() assert len(rows) != 0 # try to search with string check_option_negative(self, 'nonexistent', 'issuedon_from') # try to search using invalid date check_option_negative(self, '2018-02-30', 'issuedon_from') # try to search using date beyond self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'issuedon_from') search_pkey(self, str(today + timedelta(weeks=52 * 30))) rows = self.get_rows() assert len(rows) == 0 # try to search with leading space check_option_negative(self, ' {}'.format(str(today)), 'issuedon_from') # try to search with trailing space check_option_negative(self, '{} '.format(str(today)), 'issuedon_from') @screenshot def test_search_issued_on_to(self): """ Try to search cert using issued on to option """ today = date.today() self.init_app() # revoke new certificate self._add_and_revoke_cert() self.select('select[name=search_option]', 'issuedon_to') search_pkey(self, str(today)) rows = self.get_rows() assert len(rows) != 0 # try to search with string check_option_negative(self, 'nonexistent', 'issuedon_to') # try to search using invalid date check_option_negative(self, '2018-02-30', 'issuedon_to') # try to search using date ago self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'issuedon_to') search_pkey(self, str(today - timedelta(weeks=52 * 10))) rows = self.get_rows() assert len(rows) == 0 # try to search with leading space check_option_negative(self, ' {}'.format(str(today)), 'issuedon_to') # try to search with trailing space check_option_negative(self, '{} '.format(str(today)), 'issuedon_to') @screenshot def test_search_revoked_on_from(self): """ Try to search cert using revoked on from option """ today = date.today() self.init_app() # revoke new certificate self._add_and_revoke_cert() self.select('select[name=search_option]', 'revokedon_from') search_pkey(self, str(today)) rows = self.get_rows() assert len(rows) != 0 # try to search with string check_option_negative(self, 'nonexistent', 'revokedon_from') # try to search using invalid date check_option_negative(self, '2018-02-30', 'revokedon_from') # try to search using date beyond self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'revokedon_from') search_pkey(self, str(today + timedelta(weeks=52 * 30))) rows = self.get_rows() assert len(rows) == 0 # try to search with leading space check_option_negative(self, ' {}'.format(str(today)), 'revokedon_from') # try to search with trailing space check_option_negative(self, '{} '.format(str(today)), 'revokedon_from') @screenshot def test_search_revoked_on_to(self): """ Try to search cert using revoked on to option """ today = date.today() self.init_app() # revoke new certificate self._add_and_revoke_cert() self.select('select[name=search_option]', 'revokedon_to') search_pkey(self, str(today)) rows = self.get_rows() assert len(rows) != 0 # try to search with string check_option_negative(self, 'nonexistent', 'revokedon_to') # try to search using invalid date check_option_negative(self, '2018-02-30', 'revokedon_to') # try to search using date ago self.navigate_to_entity(ENTITY) self.select('select[name=search_option]', 'revokedon_to') search_pkey(self, str(today - timedelta(weeks=52 * 10))) rows = self.get_rows() assert len(rows) == 0 # try to search with leading space check_option_negative(self, ' {}'.format(str(today)), 'revokedon_to') # try to search with trailing space check_option_negative(self, '{} '.format(str(today)), 'revokedon_to')
17,878
Python
.py
428
32.915888
79
0.615775
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)